local love = assert( love )
local ffi = require( "ffi" )
local sideLength  = 256
local vertexCount = sideLength * sideLength
local vertices = love.data.newByteData( 4 * vertexCount )
local vertexMap = love.data.newByteData( 2 * vertexCount )

local height = love.graphics.newImage( "tex/terrain.png" )

local mesh = love.graphics.newMesh(
  {{"VertexPosition", "float", 1 }},
  vertexCount,
  "strip",
  "static"
)
mesh:setTexture( height )

do
  local p = vertexMap:getFFIPointer()
  local ptr = ffi.cast( "uint16_t *", p)
  for i = 0, vertexCount - 1 do
    ptr[i] = i
  end
  mesh:setVertexMap( vertexMap, "uint16" )
  do local _ = p end --keep alive?
end

local shader = love.graphics.newShader[[
  #pragma glsl3
  #define fog vec4( 0.85, 0.85, 1.0, 1.0 )
  #define fogHigh vec4( 1.0, 1.0, 0.9, 1.0 )
  varying float depth;
//varying vec3 normal;
  varying vec4 world;
#ifdef VERTEX
  uniform mat4 view;
  uniform mat4 proj;
//  attribute vec3 VertexNormal;
  vec4 position( mat4 _, vec4 pos ){
//normal = VertexNormal;
    world = pos;
    vec4 eye = view * world;
    depth = -eye.z;
    return proj*eye;
  }
#endif
#ifdef PIXEL
//uniform vec3 light;
  vec4 effect( vec4 color, Image tex, vec2 texuv, vec2 scruv) {
//    vec3 norm  = normalize( normal );
//    vec3 toLight = normalize( light - world.xyz );
//    float diff = max( dot( norm, light ), 0.5 );
//    vec4 mainColor = vec4( diff * color.rgb, color.a );
  
    return mix( mix( color * Texel( tex, texuv ), fog,
    clamp( depth / 80.0, 0.0, 1.0)), fogHigh,
    clamp( world.y / 20.0, 0.0, 1.0)) ;
  }
#endif
]]

local obj = { height = height }

function obj.draw( view, proj )
  shader:send( "view", "column", view )
  shader:send( "proj", "column", proj )
  love.graphics.setShader( shader )
  love.graphics.draw( mesh )
end

return obj