// bunnymark
var render = use('render')
var os = use('os')
var transform = use('transform')
var dim = [500,500]
render.initialize({
  width:dim.x,
  height:dim.y,
  resolution_x:dim.x,
  resolution_y:dim.y,
  mode:"letterboxed",
  refresh: 60,
})

var camera = {
  size: [500,500],
  fov:50,
  near_z: 0,
  far_z: 1000,
  surface: null,
  viewport: {x:0,y:0,width:1,height:1},
  ortho:true,
  anchor:[0,0],
}

var draw = use('draw2d')
var sprite = use('lcdsprite')
var graphics = use('graphics')
var random = use('random')

var bunny = graphics.texture('tests/bunny')

var center = [0.5,0.5]

var vel = 50

function hsl_to_rgb(h, s, l) {
  var c = (1 - abs(2 * l - 1)) * s
  var x = c * (1 - abs((h / 60) % 2 - 1))
  var m = l - c / 2
  var r = 0, g = 0, b = 0

  if      (h <  60) { r = c; g = x }
  else if (h < 120) { r = x; g = c }
  else if (h < 180) { g = c; b = x }
  else if (h < 240) { g = x; b = c }
  else if (h < 300) { r = x; b = c }
  else              { r = c; b = x }

  return [r + m, g + m, b + m, 1]  // 0‒1 floats, alpha = 1
}

var bunny_count = 20

var i = 0;
var pct = 0;
var hue = 0;
var sp = null;
for (i = 0; i < bunny_count; i++) {
  pct = i/bunny_count
  hue = 270 * i / bunny_count
  sp = sprite.create(bunny, {
    pos: [random.random()*dim.x*pct, random.random()*dim.y*pct],
    center,
    color: hsl_to_rgb(hue, 0.5, 0.5)
  })
  sp.dir = [random.random()*vel, random.random()*vel]
}

var dt = 0
var fps_samples = []
var fps_window = 10
var fps_update_period = 0.5
var last_fps_update = os.now()
function loop()
{
  var now = os.now()
  render.clear([22/255,120/255,194/255,255/255])
  render.camera(camera)

  arrfor(sprite, x => x.move(x.dir.scale(dt)))
  var queue = sprite.queue()

  //log.console(queue)

  arrfor(queue, q => {
    if (!q.image) return
    render.geometry(q.image.texture, q.mesh)
  })

  render.present()
  dt = os.now() - now
  
  var delay = (1/60) - dt
  $delay(loop, delay)
}

loop()
