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

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

local function drawBuf(buf,w,sy0,sy1,dx0,dy0,dp,flipX)
    for oy=sy0//1,sy1//1 do
        for ox=0,w do
            local dx,dy=dx0+ox,dy0+oy
--            local sp=pix(dx,dy)
            local index=flipX and (oy*w+ox) or (oy*w+(w-ox))
            local bp=buf[index]
            if bp>0 then
                pix(dx,dy,dp)
            end
        end    
    end
end

return {
    bdr=function(y,t,unitT)
    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/green-man-walking"))

            ACTOR_GMAN=R.Actor:new(MODEL_GMAN)
            ACTOR_GMAN:setDrawFn(R.poly.Draw1Colour(10),0)
            MAT_GMAN=ACTOR_GMAN:getMat()
            MAT_GMAN:mulM44(R.M44:newTrans(0,0,1.5))
            
            SCENE:registerActor(ACTOR_GMAN)
        end

        local manX,manY,manW,manH=80,10,80,120

        vbank(1)
        cls(0)
        SCENE:draw()
        local buf={}
        for oy=0,manH do
            for ox=0,manW do
                local x,y=manX+ox,manY+oy
                buf[oy*manW+ox]=pix(x,y)
            end    
        end

        vbank(0)
        cls(0)
        local xc=manW

        local sy0,sy1=manH*0,manH*.33
        local shift=(160+unitT*640)%320-160
        drawBuf(buf,manW,sy0,sy1,xc-shift,manY,4,true)

        local sy0,sy1=manH*.33,manH*.66
        drawBuf(buf,manW,sy0,sy1,xc,manY,1,true)

        sy0,sy1=manH*.66,manH*1
        drawBuf(buf,manW,sy0,sy1,xc+shift,manY,2,false)

        vbank(1)
        cls(0)
    end,
}
