Small grid engine
by Michal Vodicka
HTML
<script src="http://glmatrix.net/dist/gl-matrix-min.js"></script>
<canvas></canvas>
<script id="vs" type="x-shader/x-vertex">
attribute vec3 pos;
attribute vec3 color;
varying vec3 varyingColor;
uniform mat4 MMatrix;
uniform mat4 VMatrix;
uniform mat4 PMatrix;
void main(void) {
gl_Position = PMatrix * VMatrix * MMatrix * vec4(pos, 1.0);
varyingColor = color;
}
</script>
<script id="fs" type="x-shader/x-fragment">
precision mediump float;
varying vec3 varyingColor;
void main(void) {
gl_FragColor = vec4(varyingColor, 1.0);
}
</script>
JavaScript
var SmallGridEngine = function(canvasSelector) {
this.canvas = document.querySelector(canvasSelector);
this.gl = this.canvas.getContext("experimental-webgl");
this.gl.viewportWidth = this.canvas.width;
this.gl.viewportHeight = this.canvas.height;
window.requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| function(cb) {
setTimeout(cb, 1000 / 60);
};
};
SmallGridEngine.prototype.buildShader = function(scriptSelector) {
var scriptElement = document.querySelector(scriptSelector);
var sourceCode = scriptElement.textContent;
var shaderType = scriptElement.type === "x-shader/x-fragment" ? this.gl.FRAGMENT_SHADER : scriptElement.type === "x-shader/x-vertex" ? this.gl.VERTEX_SHADER : null;
var shader = gl.createShader(shaderType);
this.gl.shaderSource(shader, sourceCode);
this.gl.compileShader(shader);
return shader;
};
SmallGridEngine.prototype.buildProgram = function() {
var program = this.gl.createProgram();
for (; index < arguments.lenght; index++) {
this.gl.attachShader(program, arguments[index]);
}
this.gl.linkProgram(program);
return program;
};
SmallGridEngine.prototype.render = function() {
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
this.updateScene();
requestAnimationFrame(this.render);
};
SmallGridEngine.prototype.updateScene = function() {
};
Camera = function(canvasSelector) {
this.canvas = document.querySelector(canvasSelector);
this.camPos = mat4.create();
};
Camera.prototype.init = function() {
var rButton = false;
var camPosOrigin;
var mousePosOrigin;
var _this = this;
this.canvas.onmousedown = function(e) {
if (e.button === 1 && rButton === false) {
rButton = true;
camPosOrigin = mat4.clone(this.camPos);
mousePosOrigin = [e.clientX,...