local love = assert( love )

local mat4 = require( "mat4" )
local alph = 1/math.sqrt(2)
local testMesh = love.graphics.newMesh(
  {--attributes
    {"VertexPosition", "float", 4},
    {"VertexColor", "float", 3},
    {"VertexTexCoord", "float", 2},
  },
  {--vertices
    { 1, 0, -alph, 1,
      1, 1, 1,
      1, 0 },
    { -1, 0, -alph, 1,
      1, 0, 0,
      0, 0 },
    { 0, 1, alph, 1,
      0, 1, 0,
      1, 1, },
    { 0, -1, alph, 1,
      0, 0, 1,
      0, 1, },
  },
  "strip",
  "static"
)
testMesh:setVertexMap{ 1,2,3,4,1,2 }
local rockTexture = love.graphics.newImage( "tex/rock.png" )
rockTexture:setWrap( "repeat", "repeat" )
testMesh:setTexture( rockTexture )

--Transforms
mat4.randomise()
local instanceTransforms = love.graphics.newMesh( {
    {"itx", "float", 4},
    {"ity", "float", 4},
    {"itz", "float", 4},
    {"itw", "float", 4}}, 1024, nil, "static" )
instanceTransforms:setVertices( mat4.data )
testMesh:attachAttribute( "itx", instanceTransforms, "perinstance" )
testMesh:attachAttribute( "ity", instanceTransforms, "perinstance" )
testMesh:attachAttribute( "itz", instanceTransforms, "perinstance" )
testMesh:attachAttribute( "itw", instanceTransforms, "perinstance" )


local instanceShader = [[
  varying vec4 itxdbg;
#ifdef VERTEX
  attribute vec4 itx;
  attribute vec4 ity;
  attribute vec4 itz;
  attribute vec4 itw;
  uniform mat4 view;
  uniform mat4 proj;
  vec4 position( mat4 _, vec4 pos ){
    mat4 inst = mat4( itx, ity, itz, itw );
    vec4 cam = view*pos;
    itxdbg = itw;
    return proj * cam;
  }
#endif
#ifdef PIXEL
  vec4 effect( vec4 color, Image tex, vec2 texuv, vec2 scruv) {
    return color * Texel(tex, texuv) * vec4( 2.0, 2.0, 2.0, itxdbg.w ) ;
  }
#endif
]]
instanceShader = love.graphics.newShader( instanceShader, instanceShader )

return { draw = function( view, proj )
    love.graphics.push( "all" )
    love.graphics.setShader( instanceShader )
    instanceShader:send( "view", "column", view )
    instanceShader:send( "proj", "column", proj )
    io.flush()
    love.graphics.drawInstanced( testMesh, 30, 0, 0 )
    love.graphics.pop()
  end,
  update = function()
    mat4.randomise()
  end}