Demo

Source code

 1"use strict";
 2
 3const whl = require("whale-core");
 4const mainLoop = require("whale/std/main_loop.js");
 5
 6var game = {
 7  init: function()
 8  {
 9    this.window = whl.Window("WhaleJS Hello World Triangle",
10                             whl.IVec2(800, 600), whl.Window.Options.OPENGL);
11    this.gfx = whl.RenderContext(this.window);
12
13    var indexBuffer = whl.Buffer();
14    [0, 1, 2].forEach(function(v) { indexBuffer.pushUInt32(v); });
15    this.indexBuffer = whl.BufferObject(
16      whl.BufferObject.Target.ELEMENT_ARRAY,
17      whl.BufferObject.Usage.STATIC,
18      indexBuffer
19    );
20
21    var vertexBuffer = whl.Buffer();
22    [
23      // Position      // Color
24      -0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
25       0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
26       0.0,  0.5, 0.0, 0.0, 0.0, 1.0
27    ].forEach(function(v) { vertexBuffer.pushFloat(v); });
28    this.vertexBuffer = whl.BufferObject(
29      whl.BufferObject.Target.ARRAY,
30      whl.BufferObject.Usage.STATIC,
31      vertexBuffer
32    );
33
34    this.program = whl.Program(
35      whl.Shader(
36        whl.Shader.Type.VERTEX,
37        "attribute vec3 aPosition;\n" +
38        "attribute vec3 aColor;\n" +
39        "varying vec3 vColor;\n" +
40        "void main()\n" +
41        "{\n" +
42        "  gl_Position = vec4(aPosition, 1.0);\n" +
43        "  vColor = aColor;\n" +
44        "}\n"
45      ),
46      whl.Shader(
47        whl.Shader.Type.FRAGMENT,
48        "precision mediump float;\n" +
49        "varying vec3 vColor;\n" +
50        "void main()\n" +
51        "{\n" +
52        "  gl_FragColor = vec4(vColor, 1.0);\n" +
53        "}\n"
54      )
55    );
56
57    this.attrList = whl.VertexAttrList();
58    this.attrList.push(whl.VertexAttr("aPosition", whl.VertexAttr.Type.VEC3));
59    this.attrList.push(whl.VertexAttr("aColor", whl.VertexAttr.Type.VEC3));
60  },
61
62  draw: function(time, dt)
63  {
64    this.gfx.clear(whl.Vec4());
65    this.gfx.use(this.indexBuffer);
66    this.gfx.use(this.vertexBuffer);
67    this.gfx.use(this.program);
68    this.gfx.use(this.attrList);
69    this.gfx.draw(
70      whl.RenderContext.PrimitiveType.TRIANGLES,
71      whl.RenderContext.IndexType.UNSIGNED_INT,
72      3
73    );
74    this.window.redraw();
75    Duktape.gc();
76  }
77};
78
79function loop()
80{
81  return mainLoop.run(game);
82}