R=R or {}
require("./3d/model")(R)
require("./3d/scene")(R)

local GLOBAL=require("./global")

local SCENE=nil
local MODEL_GMAN=nil
local ACTOR_GMAN=nil
local MAT_GMAN=nil

return {
    duration=6000,
    bdr=function(y,t,unitT)
        vbank(0)
        local b=R.clamp((1-unitT)*.5-y/200,0,1)
        R.setRGB(0,R.RGB:new(0,0,b))
        R.setRGB(1,GLOBAL.rgbGMan)
        for i=0,12 do
            local s=i/12
            R.setRGB(i+3,R.RGB:new(s,0,0))
        end
    end,
    musicTic=function(isFirstRun,t,unitT)
        if isFirstRun then
            vbank(1)
            cls(0)

            SCENE=R.Scene:new()

            MODEL_GMAN=R.Model:new()
            MODEL_GMAN:load(require("./data/model/greenman"))

            ACTOR_GMAN=R.Actor:new(MODEL_GMAN)
            ACTOR_GMAN:setDrawFn(R.poly.Draw1Colour(1),0)
            
            SCENE:registerActor(ACTOR_GMAN)
        end

        vbank(0)
        cls(0)
    
        local y=-1.75+unitT*3.5
        local mat=R.M44:newTrans(0,y,1.5)
        mat.mulM44(mat,R.M44:newRotZ(math.pi+math.sin(unitT*math.pi*3)*.8))
        mat.mulM44(mat,R.M44:newRotY(unitT*5*math.pi))
        ACTOR_GMAN:setMat(mat)

        local cam=SCENE:getCam()
        local yCam=y+2-unitT*3.4
        cam:setPos(R.V4:new({0,yCam,unitT*2-1,1}))
        cam:setAim(R.V4:new({0,yCam,1.5,1}))

        for i=0,100 do
            local x=(i^7)%240
            local y=(i^3-(unitT*(500+i*26)))%136
            line(x,y-4*(i/20),x,y,3+(i%12))

            if i==50 then
                SCENE:draw()
            end
        end
    end,
}
