-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphics.js
452 lines (403 loc) · 12.7 KB
/
graphics.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/**
* @file graphics.js
* @brief Graphics related functions and helpers
*/
/**
* Convert sprite to RGBA 2D array
* @returns {width, height, rgba[][]}
*/
function SpriteToRGBA(sprite1)
{
var rgba1 = [];
for (var x = 0; x < sprite1.width; ++x)
{
rgba1[x] = [];
for (var y= 0; y < sprite1.height; ++y)
{
var index = (+x+ +y*sprite1.width)*4;
var pix = [0,0,0,0];
for (var i = 0; i < pix.length; ++i)
{
pix[i] = sprite1.data[+index + +i];
}
rgba1[x][y] = pix;
}
}
return {width : sprite1.width, height : sprite1.height, rgba : rgba1};
}
/**
* Sprite based collision checking
*/
function SpriteCollision(offset, sprite1, sprite2)
{
for (var x = 0; x < sprite1.width; ++x)
{
var xx = +x + +offset[0];
if (xx < 0 || xx >= sprite2.width) continue;
for (var y = 0; y < sprite1.height; ++y)
{
var yy = +y + +offset[1];
if (yy < 0 || yy >= sprite2.height) continue;
var pix1 = sprite1.rgba[x][y];
var pix2 = sprite2.rgba[xx][yy];
if (pix1[3] > 10 && pix2[3] > 10) return true;
}
}
return false;
}
/**
* Construct a canvas for drawing things on
* Should be used on a HTML5 canvas element
*/
function Canvas(element)
{
// Commented out because on my testing laptop
// with the latest graphics driver update this causes X to crash
// *fglrx slow clap*
//this.gl = element.getContext("experimental-webgl");
this.ctx = element.getContext("2d");
if (!this.gl && !this.ctx)
{
alert("Your browser does not support Humphrey The Rabbit\nTry with Firefox\n:-(");
}
else if (!this.gl)
{
//alert("Your browser does not support WebGL\nThis may cause performance issues\n:-(");
}
this.width = element.width;
this.height = element.height;
this.textures = {};
if (this.gl) with(this.gl)
{
blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
enable(BLEND);
clearColor(0.9, 0.9, 1.0, 1.0); // Set clear colour
viewport(0,0,this.width,this.height); // Set viewport (unnecessary?)
// Initialise the buffer objects
InitBuffers(this.gl);
// Initialize the shaders
InitShaders(this.gl);
}
// Start the Game.
}
/**
* Convert coordinates in GL to pixels
*/
Canvas.prototype.LocationGLToPix = function(x, y)
{
var xx = Math.round((1+x)*this.width/2);
var yy = Math.round((1-y)*this.height/2);
return [xx,yy];
}
Canvas.prototype.Text = function(text)
{
var fontSize = 50 / (1 +Math.round(text.length/40));
const previousFont = this.ctx.font;
this.ctx.font = String(fontSize)+"px Comic Sans";
this.ctx.fillStyle = "rgba(0,0,0,1)";
this.ctx.beginPath();
this.ctx.fillText(text,this.width/16, this.height/6, 14*this.width/16);
this.ctx.font = previousFont;
}
Canvas.prototype.Message = function(text)
{
var fontSize = 12; // (1 +Math.round(text.length/40));
const previousFont = this.ctx.font;
this.ctx.font = String(fontSize)+"px Comic Sans";
this.ctx.fillStyle = "rgba(0,0,0,1)";
this.ctx.beginPath();
this.ctx.fillText(text,this.width/16, 5*this.height/6, 14*this.width/16);
this.ctx.font = previousFont;
}
Canvas.prototype.SetBackground = function(imagePath)
{
if (typeof(imagePath) == "string")
this.background = this.LoadTexture(imagePath, function() {});
}
Canvas.prototype.DrawBackground = function()
{
if (typeof(this.background) != "undefined" && typeof(this.background.img) != "undefined")
this.ctx.drawImage(this.background.img, 0, 0, this.width, this.height);
}
Canvas.prototype.SplashScreen = function(imagePath, text, backColour, onload)
{
this.cancelSplash = false;
var screen = new Entity([0,0], [0,0],[0,0],"");
if (!text) text = "";
if (!backColour) backColour = [0,0,0,0.9];
screen.scale = [0.6, 0.6];
screen.bounds = {min:[-this.width/2, -this.height/2], max:[this.width/2, this.height/2]};
var altText = "don't you have anything better to do?";
var f = () => {
console.debug("Splash for", imagePath, onload);
if (this.cancelSplash) {
console.debug("Canceled splash screen");
return;
}
if (this.gl)
{
this.gl.clearColor(background[0], background[1], background[2], background[3]);
this.gl.clear(gl.COLOR_BUFFER_BIT);
this.gl.uniform4f(uColour,1,1,1,1);
//gl.uniform4f(uColour, blend[0], blend[1], blend[2], blend[3]);
screen.Draw();
this.gl.uniform4f(uColour,1,1,1,1);
}
else if (this.ctx)
{
for (var i = 0; i < 3; ++i)
backColour[i] = Math.round(255*backColour[i]);
this.ctx.fillStyle = "rgba("+backColour+")";
this.ctx.fillRect(0,0,this.width, this.height);
if (screen.frame && screen.frame.img && screen.frame.img.width && screen.frame.img.height)
{
var drawWidth = screen.frame.img.width;
var drawHeight = screen.frame.img.height;
if (drawWidth > this.width || this.width < 300 || drawWidth < 400)
{
var scale = Math.max(drawWidth / this.width, drawHeight/this.height);
drawWidth /= scale;
drawHeight /= scale;
}
this.ctx.drawImage(screen.frame.img, this.width/2 - drawWidth/2, this.height/2 - drawHeight/2, drawWidth, drawHeight);
} else {
this.Clear();
// This should freak them out enough to turn off the adblocker
text = "Critical failure loading essential resource!";
text += "🔥🔥🔥"; // Test if they support UTF-8 or not
console.error(text)
// (Or tell me "your website is broken!")
// Hacky, but probably does the same thing the adblocker does...
g_usingAdblocker |= (imagePath && imagePath.indexOf("advert") >= 0);
altText = "(plz consider donating $50USD a month for quality humphrey the rabbit content without ads)"
console.warn(altText)
}
this.Text(text);
var fontSize = 10;// / (1 +Math.round(text.length/40));
this.ctx.font = String(fontSize)+"px Comic Sans";
this.ctx.fillStyle = "rgba(1,0,0,0.1)";
this.ctx.beginPath();
this.ctx.fillText(altText,this.width/16, 31*this.height/32 , 14*this.width/16);
}
if (typeof(onload) === "function")
{
console.debug(" Callback for splash ", imagePath);
onload();
}
//if (text)
// Debug("<b><i>"+text+"</i></b>", true);
};
console.debug("Running spash screen", imagePath);;
if (imagePath)
screen.frame = this.LoadTexture(imagePath, f);
else
f();
}
/**
* Load texture with onload callback function
* NOTE: onload is also called if the image fails to load, or pretty much any other error
*
* I promise to oneday rewrite my entire codebase to use promises
* .catch(exception) => {NEVER}
*/
Canvas.prototype.LoadTexture = function(imagePath, onload)
{
if (imagePath in this.textures)
{
// console.debug("texture", imagePath," already loaded");
if (onload) {setTimeout(onload, 0)}
return this.textures[imagePath];
}
var texture = (this.gl) ? this.gl.createTexture() : null;
var image = new Image();
this.textures[imagePath] = {tex: texture, img: image, data : null};
if (imagePath == "cookies.svg") {
debugger;
}
if (onload)
{
var c = this;
image.onload = function() {
console.debug(`${imagePath} loaded`)
c.HandleTextureLoaded(c.textures[imagePath]);
onload();
};
}
else
{
var c = this;
image.onload = function()
{
console.debug(`${imagePath} loaded`)
c.HandleTextureLoaded(c.textures[imagePath])
};
}
// Which of these are actually needed? Screw it just put them all
image.onerror = onload;
image.onabort = onload; // I'm assuming Abort and Cancel are... "different" in a subtle and important way
image.oncancel = onload;
// Bad web developer pickup line #10284:
// "Baby I'll let you violate my security policy any time you want"
image.onsecuritypolicyviolation = onload;
image.src = imagePath;
return this.textures[imagePath];
}
/**
* When a texture is loaded, do this
*/
Canvas.prototype.HandleTextureLoaded = function(texData)
{
if (!texData) {
console.warn("Skipped handling of missing texture data");
return;
}
image = texData.img;
texture = texData.tex;
if (this.gl && texture)
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
if (this.prepareSpriteCollisions || this.gl
&& ((image.width & (image.width - 1)) != 0
|| (image.height & (image.height - 1)) != 0))
{
console.debug("scaling non power of 2 texture");
var canvas = document.createElement("canvas");
var w = image.width; var h = image.height;
--w; for (var i = 1; i < 32; i <<= 1) w = w | w >> i; ++w;
--h; for (var i = 1; i < 32; i <<= 1) h = h | h >> i; ++h;
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext("2d");
//ctx.rect(0,0,w,h);
ctx.drawImage(image, w/2 - image.width/2, h/2 - image.height/2, image.width, image.height);
// This is needed for webgl but not canvas2d, removing since I'm focusing on canvas2d for now
// It is really slow.
// Is webgl really better?
// I mean, it might draw faster but it has to do all this work before it can draw
// (especially for a one off image) :S
//texData.data = SpriteToRGBA(ctx.getImageData(0,0,w,h));
texData.img = canvas;
}
if (this.gl && texture) with(this.gl)
{
texImage2D(TEXTURE_2D, 0, RGBA, RGBA, UNSIGNED_BYTE, texData.img);
texParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, LINEAR);
texParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, LINEAR_MIPMAP_NEAREST);
generateMipmap(TEXTURE_2D);
bindTexture(TEXTURE_2D, null);
}
}
/**
* Initialises buffers that will be sent to the shaders
*/
function InitBuffers(gl) {with(gl)
{
// Bind vertices (A rectangle)
gl.verticesBuffer = createBuffer();
bindBuffer(ARRAY_BUFFER, verticesBuffer);
bufferData(ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, 1,1, -1,1]), STATIC_DRAW);
// Bind vertex indices
gl.verticesIndexBuffer = createBuffer();
bindBuffer(ELEMENT_ARRAY_BUFFER, verticesIndexBuffer);
// indices of vertices of two triangles that make a square
var indices = [0,1,2, 0,3,2];
bufferData(ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), STATIC_DRAW);
// Bind texture vertices
gl.verticesTextureCoordBuffer = createBuffer();
bindBuffer(gl.ARRAY_BUFFER, verticesTextureCoordBuffer);
bufferData(gl.ARRAY_BUFFER, new Float32Array([0,1, 1,1, 1,0, 0,0]), STATIC_DRAW);
}}
//
// InitShaders
//
// Initialize the shaders, so WebGL knows how to light our scene.
//
function InitShaders(gl) {with(gl)
{
var fragmentShader = GetShader(gl, "shader-fs");
var vertexShader = GetShader(gl, "shader-vs");
// Create the shader program
gl.shaderProgram = createProgram();
attachShader(shaderProgram, vertexShader);
attachShader(shaderProgram, fragmentShader);
linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!getProgramParameter(shaderProgram, LINK_STATUS))
{
alert("Unable to initialize the shader program.");
}
useProgram(shaderProgram);
// Texture attributes
gl.aTextureCoord = getAttribLocation(shaderProgram, "aTextureCoord");
enableVertexAttribArray(aTextureCoord);
// Vertex attributes
gl.aVertexPosition = getAttribLocation(shaderProgram, "aVertexPosition");
enableVertexAttribArray(aVertexPosition);
// Set uniforms
gl.uPosition = getUniformLocation(shaderProgram, "uPosition");
gl.uAspectRatio = getUniformLocation(shaderProgram, "uAspectRatio");
gl.uScale = getUniformLocation(shaderProgram, "uScale");
gl.uColour = getUniformLocation(shaderProgram, "uColour");
uniform4f(uColour, 1,1,1,1);
// Set it
//gl.uniform1f(uAspectRatio, canvas.width/canvas.height);
uniform1f(uAspectRatio, 1);
}}
function GetShader(gl, id)
{
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
// Walk through the source element's children, building the
// shader source string.
var theSource = "";
var currentChild = shaderScript.firstChild;
while(currentChild)
{
if (currentChild.nodeType == 3)
theSource += currentChild.textContent;
currentChild = currentChild.nextSibling;
}
// Now figure out what type of shader script we have,
// based on its MIME type.
var shader;
if (shaderScript.type == "x-shader/x-fragment")
shader = gl.createShader(gl.FRAGMENT_SHADER);
else if (shaderScript.type == "x-shader/x-vertex")
shader = gl.createShader(gl.VERTEX_SHADER);
else return null;
// Send the source to the shader object
gl.shaderSource(shader, theSource);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
{
alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
Canvas.prototype.Clear = function(colour)
{
if (this.gl)
{
this.gl.clearColor(colour[0], colour[1], colour[2], colour[3]);
}
else if (this.ctx)
{
if (colour)
{
for (var i = 0; i < colour.length; ++i)
colour[i] = Math.round(colour[i]*255);
this.fillStyle = "rgba("+colour+")";
}
this.ctx.fillStyle = this.fillStyle;
this.ctx.fillRect(0,0,this.width,this.height);
}
}
Canvas.prototype.AreImagesLoaded = function() {
return Object.values(this.textures).reduce((completed, currentTexture) => {
return (completed && currentTexture.img.complete)
}, true);
}