
function init_event()
    ag.import("std")

    local rows = 5
    local offset = 1
    local pin = ag.loadModel("bowling_pin", {scale = 0.5})
    pin:setPosition(0, 0, 2)
    for row = 2, rows do
        for x = 1, row do
            local p = pin:clone()
            p:setPosition(-((row - 1) * offset) / 2 + (x - 1) * offset,
                          offset * (row - 1),
                          2)
        end
    end

    local ground = ag.createPlane(0, 0, 1, 0)
    ground:setColor(0.8, 0.5, 0.0)
    ground:setPosition(0, 0, -10)
    ag.setCamera(0.3, -25, 10, 0, 0, 1, 0, 0, 1)
    camx, camy, camz, cx, cy, cz = ag.getCamera()

    ball = ag.loadModel("checkerball", {scale = 0.5})
    ball:setPosition(2*camx - cx, 2*camy - cy, 2*camz - cz)
    ball:setMass(5)

    smallPin = std.loadModelBounds("bowling_pin", 0, 0, 1)
    smallPin:setPosition(0, -1, 1)
end

function mousebutton_down_event(button)
    local function button1()
        local newball = ball:clone()
        newball:setPosition(camx, camy, 1)
        force = 4000
        newball:addForce(force * (cx-camx),
                         force * (cy-camy),
                         force * (cz-camz))
    end
    if (button == 1) then
        button1()
    end
end

function key_down_event(key)
    if (key == "s") then
        local s = ag.createSphere(0.5)
        s:setPosition(0, 0, 5)
        s:setColor(0.1, 0.2, 0.3)
    elseif (key == "c") then
        local c = ag.loadModel("crate")
        c:setPosition(-3, -3, 5)
    elseif (key == "g") then
        ag.setGravity(0, 0, 2)
    elseif (key == "r") then
        ag.setGravity(0, 0, -9.81)
    end
end

function update_overlay_event(width, height)
    local tw, th = ag.getTextSize("Hi there", 18)
    ag.drawText("Hi there", 1, 1, 0, 18, width - tw - 40, height - th - 40)
    ag.drawText("Hello", 1, 0, 1, 20, 200, 200)
--    ag.drawLine(1, 0, 0.3, 10, 10, 40, 60)
--    ag.drawLine(1, 0.7, 1, 50, 10, 100, 60, 5)
--    ag.drawRect(0, 1, 0, 40, 40, width / 2, height / 2)
--    ag.fillRect(0, 0, 1, 20, 30, width / 2, height / 2)
--    local rot = ag.elapsedTime() / 10
--    ag.drawImage(50, 50, 80, 160, crate_texture, rot)
end
