EffectPolka = Effect:new({num = 500, r = 1, g = 0, b = 0, a = 0.5, energy = 1})

function EffectPolka:setup()
	
	self.width = width()
	self.height = height()
	self.half_width = width() * 0.5
	self.half_height = height() * 0.5
	self.max_rect_height = self.height * 1.0 / self.num
	self.max_rect_width = self.width * 1.0 / self.num
	
	self.points = {}
	
	for i = 1, self.num, 1 do
		-- w, h : rect size
		-- sx, sy : speed x y
		table.insert(self.points, { x = 0, y = 0, w = 0, h = 0, sx = 0, sy = 0 })
	end
	
end

function EffectPolka:update (time)
	local elapsed = time - self.lastTimeUpdated
	
	ortho()
		
		color(self.r, self.g, self.b, self.energy)
	
		self.energy = self.energy - elapsed
		if self.energy < 0 then
			self.energy = 0
		end
	
		blending(BLENDING_ADDITIVE)
	
		for i = 1, self.num, 1 do
			local p = self.points[i]
			rectangle(p.x, p.y, p.w, p.h)
			p.x = p.x + p.sx * elapsed
			p.y = p.y + p.sy * elapsed
		end
	
		noBlending()

	restoreProjection()

	Effect.update(self, time)	
end

function EffectPolka:processEvent(event)
	-- listen to 'hat' instrument only on C-3 / C-2 (48, 36)
	if event.instrument == 3 and (event.note == 48 or event.note == 36) then
		self.energy = self.a
		--local bx = -self.half_width + math.random() * self.width
		--local by = -self.half_height + math.random() * self.height
		local rr = 0.75
		local bx = rr * self.width * (math.random() - 0.5)
		local by = rr * self.height * (math.random() - 0.5)
		local radius = event.note * 2
		
		local rx = self.width
		local ry = self.height
		
		bx = 0 -- self.half_width
		by = 0 --self.half_height
		
		local sign
		if math.random() > 0.5 then
			sign = 1
		else
			sign = -1
		end
		
		local limiter = 0.25
		
		for i = 1, self.num, 1 do
			local p = self.points[i]
			
			p.x = bx + (math.random() - 0.5) * rx
			p.y = by + (math.random() - 0.5) * ry
			
			-- moving horizontally
			if event.note == 36 then
				p.sx = sign * math.random() * 100
				p.sy = 0
				p.w = math.random() * self.width * limiter
				p.h = self.max_rect_height
			else
				p.sx = 0
				p.sy = sign * math.random() * 100
				p.w = self.max_rect_width
				p.h = math.random() * self.width * limiter
			end
		end
	end
end
