#!/usr/bin/env ascript

// Orignal source file is written in C and is available from the site below.
// http://www.sgi.com/products/software/opengl/examples/samples/
// copy.c

import(gltester)
import(glu) {*}
import(opengl) {*}

windW = 300, windH = 300

x = 0
y = windH
zoom = 1.8

img = image(`rgb).rgbread("1.rgb")

Init() = {
	glClearColor(0.0, 0.0, 0.0, 0.0)
}

Reshape(width:number, height:number) = {
	extern(windW, windH)
	windW = width
	windH = height
	glViewport(0, 0, windW, windH)
	glMatrixMode(GL_PROJECTION)
	glLoadIdentity()
	gluOrtho2D(0, windW, 0, windH)
	glMatrixMode(GL_MODELVIEW)
}

Draw() = {
	glClear(GL_COLOR_BUFFER_BIT)
	glRasterPos3f(windW / 2 - img.width / 2, windH / 2 - img.height / 2, 0)
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
	glPixelZoom(1.0, 1.0)
	glDrawPixels(img)
	glRasterPos3f(x, windH - y, 0)
	glPixelZoom(zoom, zoom)
	[x_new, y_new] = [(windW / 2) - (img.width / 2), (windH / 2) - (img.height / 2)]
	glCopyPixels(x_new, y_new, img.width, img.height, GL_COLOR)
	glFlush()
}

lambda {
	import(gltester)
	gltester.mainloop(300, 300, 0, `idle) {
		`onInit => lambda {
			Init()
		}
		`onResize => lambda(width:number, height:number) {
			Reshape(width, height)
		}
		`onDraw => lambda {
			Draw()
		}
		`onMouseButtonDown => lambda(x_new:number, y_new:number) {
			extern(x, y)
			x = x_new
			y = y_new
		}
		`onKeyDown => %{
			`up => lambda {
				extern(zoom)
				zoom += 0.2
			}
			`down => lambda {
				extern(zoom)
				zoom -= 0.2
				if (zoom < 0.2) { zoom = 0.2 }
			}
		}
	}
}()
