-- lua script for drawing a fractal
-- some basic constants
local abort = false
local w_mid = width / 2
local h_mid = height / 2
local screen_radius = math.sqrt((w_mid * w_mid) + (h_mid * h_mid))
local r2d =  180 / 3.14159265


-- allow the user to change the settings. 
-- Note the sliders have range is 0 .. 1.0 for reading but have range 1..100 for setting
--@TBCONFIG SLIDER: Iterations, 1
--@TBCONFIG SLIDER: Zoom, 0
--@TBCONFIG SLIDER: XShift, 50
--@TBCONFIG SLIDER: YShift, 50


local uIterations = sliderVal1 * 500 + 5
local uZoom = 1 - sliderVal2 
local uXShift = (sliderVal3 - 0.5) * 2
local uYShift = (sliderVal4  - 0.5) * 2

-- ------------------------------
-- note: functions must be defined BEFORE the calling logic calls them
-- ------------------------------

function round(x)
    local xf = math.floor(x)
    if (x - xf) <= 0.5 then 
        return xf
    else
        return math.ceil(x)
    end 
end



local it, pmin, qmin, pmax, qmax, dp, p1, q1, z, xh
local OScale = 1.5
local PCenter = -0.5 + uXShift * OScale
local QCenter = 0 + uYShift * OScale

pmin = PCenter - OScale * uZoom		-- horizontal window range (pmin, pmax)
pmax = PCenter + OScale * uZoom

qmin = QCenter - OScale * uZoom		-- vertical window range (qmin, qmax)
qmax = QCenter + OScale * uZoom

dp = (pmax - pmin) / width			-- step (or pixel "size")

for x = 0, width do 
	p1 = pmin + x * dp			-- compute horizontal fractal element position
	for y = 0, height do 
    	x1 = 0.0			
    	y1 = 0.0
    	q1 = qmin + y * dp			-- compute vertical fractal element position
    	z=0.0
    	while (z < uIterations and (x1 * x1 + y1 * y1) < 10) do 
			if (is_escape() > 0) then
				abort = true; break
			end
    		xh = x1
    		x1 = xh * xh - y1 * y1 + p1		-- real 
    		y1 = 2 * xh * y1 + q1	     -- imaginary
    		z = z + 1
    	end
		if abort == true then  break end
       set_hsl(x, y, 360 * (z / uIterations) , 0.5, 0.5)
    end
	if abort == true then break end
end




