-- FIRE SPREAD MODELS
-- (C) 2010 INPE AND UFOP


-- Automaton states
INACTIVE 	= 0
BURNING 	= 1
BURNED  	= 2

-- Model parameters
STEPS 		= 30 			-- number of simulation timesteps
I		    = 0.3  			-- fire propagation probability (0.1; 0.2; 0.25; 0.3; 0.4; 0.5)
OUTPUT_PATH 		= "c:\\TerraME\\Results\\Percolation\\"

-- Define and load a TerraLib geographical database
cs = CellularSpace{
	dbType = "ADO",
	database = "c:\\TerraME\\Database\\db_teoria.mdb",
	theme = "cells",
	select = { "Col", "lin", "state" }
}
cs:load()

-- Create a Moore Neighborhood
createMooreNeighborhood(cs)

-------------------------------------------------------------------------------------------
-- Model execution
burned_total = 0
--cs:save(0,"state",{"state"})
for t = 1, STEPS do

	itF = Trajectory{cs, function(cell) return cell.state == BURNING end}
	forEachCell(itF, function(cell)
		forEachNeighbor(cell, function(cell,neigh)
			if (neigh ~= cell and neigh.state == INACTIVE) then
				p = math.random()
				if p < I then
					neigh.state = BURNING
				end
			end
		end)
		cell.state = BURNED
		burned_total = burned_total + 1
	end)

	save2PNGd(cs, t, OUTPUT_PATH, "state", {INACTIVE, BURNING, BURNED }, {GREEN, RED, BLACK})
end

print("<> The end - burned cells:",burned_total," <>")

print("Please, press <ENTER> to quit.")
io.read()