-
Notifications
You must be signed in to change notification settings - Fork 10
/
image_renderer.js
981 lines (803 loc) · 33.8 KB
/
image_renderer.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
/*
Ethereal Farm
Copyright (C) 2020-2024 Lode Vandevenne
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
/*
Abstract class for methods to render the images (with canvas, ...)
(This class isn't really necessary but shows the interfac that must be implemented)
@constructor
*/
function Renderer() {
}
// Creates a new canvas to visibly render image(s) on.
// WARNING: If re-using this function on existing div, ensure to clear it first!
// This is not for creating internal (offscreen, ...) canvases like some renderers use in setupImage to contain textures, this function is intended to create the visible element in the UI on which the image will be visibly drawn
// Does not necessarily return a 'canvas' element, but it will always be some DOM element. Depending on the renderer, this may be a canvas, a div, an svg, ...
// We still call it canvas anyway as it's the place we'll draw the image on so it is figuratively speaking a canvas.
// x, y, w and h must have HTML units (px, %, ...)
Renderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
// Empty, to implement by implementing classes
};
// Extends an image object created by generateImage, with possibly extra data needed for the renderer (such as OffscreenCanvas, ImageData, ...)
// generateImage returns a 3-element array, setupImage may add extra elements to it, but keeps the first 3 the same
// So the result of this function can be used wherever results of generateImage can be used, however setupImage must be used to make the image usable with this Renderer.
Renderer.prototype.setupImage = function(image) {
// Empty, to implement by implementing classes
};
// Render image (as created by setupImage) onto the given canvas. The canvas is completely replaced by this image, there's no alpha blending onto previous content.
// The canvas must be an element that was created by the createCanvas function of this renderer.
// The image argument must be an image that was returned by the setupImage function of this renderer.
Renderer.prototype.renderImage = function(image, canvas) {
// Empty, to implement by implementing classes
};
// Render multiple images (as created by setupImage) onto the given canvas
Renderer.prototype.renderImages = function(images, canvas) {
// Empty, to implement by implementing classes
};
// Blend image (as created by setupImage) onto the given canvas. The difference with renderImage is that it alpha-blends it on top of existing content
Renderer.prototype.blendImage = function(image, canvas) {
// Empty, to implement by implementing classes
};
// Render an individual pixel on the canvas, which must already have some image rendered on it. The pixel size used is the one of that rendered image.
// This is not necessarily fast (except possibly for some implementations that internally use this for everything), so should be used sparingly, but is useful for a small amount of pixels
Renderer.prototype.renderPixel = function(x, y, color, canvas) {
// Empty, to implement by implementing classes
};
// Static utility function, given a 2D array of images forming a grid, returns array of [w, h, w2, h2, numw, numh] where:
// w = width of individual image (all are assumed to have the same size)
// h = height of individual image (all are assumed to have the same size)
// w2 = width of the entire grid in pixels
// h2 = height of the entire grid in pixels
// numw = amount of images in x-direction
// numh = amount of images in y-direction
// Returns undefined instead of the input is empty (nothing to do)
Renderer.computeImagesSizes_ = function(images) {
var w, h;
var numw = 0;
for(var y = 0; y < images.length; y++) {
numw = Math.max(numw, images[y].length);
for(var x = 0; x < images[y].length; x++) {
if(images[y][x]) {
w = images[y][x][1];
h = images[y][x][2];
break;
}
}
}
if(w == undefined) return undefined; // nothing to do, no images
var w2 = w * numw;
var h2 = h * images.length;
return [w, h, w2, h2, numw, images.length];
}
////////////////////////////////////////////////////////////////////////////////
/*
Renders all textures on an offscreen canvas (or a non-offscreen one if OffscreenCanvas not supported by browser - we still call it 'off screen' then), then puts them from the offscreen canvases to the actual visible canvases when rendering them
@constructor
*/
function OffscreenCanvasRenderer() {
}
//OffscreenCanvasRenderer.prototype = new Renderer();
// pool of canvas elements for reuse:
// the first call to getContext (if followed by doing any action on it) on a new canvas is much slower than later calls (at least on chrome as of september 2023).
// so whenever a canvas element will be destroyed, rather than destroying it, detach it from its parent element and put it in the pool here for later reuse
// it seems to work well despite having changed parent and possibly size... though almost all images in ethereal farm are 16x16 so the latter isn't verified yet
// probably whether this slowness exists or not depends on whether hardware acceleration is enabled or not (with hw acceleration making it slower due to longer setup-time), in any case, this definitely improves things in chrome on desktop and android as of 2023
var canvaspool_ = [];
function getCanvasFromPool_() {
if(canvaspool_.length > 0) {
var result = canvaspool_[canvaspool_.length - 1];
canvaspool_.length--;
return result;
}
return document.createElement('canvas');
}
function addCanvasToPool_(canvas) {
if(canvaspool_.length > 2000) return; // avoid caching TOO much canvases
// reset event listeners, style, attributes, ... set to this HTML element, that could be completely unneeded or different when the canvas is reused elsewhere
util.cleanSlateElement(canvas);
canvaspool_[canvaspool_.length] = canvas;
}
var currentOffscreenCanvas = undefined;
var currentOffscreenCanvasNum = 0;
function createOffscreenCanvas(w, h) {
if(window.OffscreenCanvas) {
return new OffscreenCanvas(w, h);
} else {
// fallback for browsers without OffscreenCanvas support
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
return canvas;
}
}
// Copies pixels from the given regular JS data array into the ImageData object.
function arrayFillImageData(id, data, w, h, offsetx, offsety) {
for(var y = 0; y < h; y++) {
for(var x = 0; x < w; x++) {
var x2 = x + offsetx;
var y2 = y + offsety;
id.data[(y2 * w + x2) * 4 + 0] = data[y][x][0];
id.data[(y2 * w + x2) * 4 + 1] = data[y][x][1];
id.data[(y2 * w + x2) * 4 + 2] = data[y][x][2];
id.data[(y2 * w + x2) * 4 + 3] = data[y][x][3];
}
}
}
OffscreenCanvasRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var canvas = getCanvasFromPool_();//document.createElement('canvas');
canvas.style.position = 'absolute';
canvas.style.left = x;
canvas.style.top = y;
canvas.style.width = w;
canvas.style.height = h;
canvas.classList.add('pixelated');
parent.appendChild(canvas);
return canvas;
};
// Renders image on an internal canvas (in memory texture)
// Returns same format as generateImage, but with additional fields behind it:
// [data, w, h, canvas, imagedata, offsetx, offsety]
// data = the array of numeric pixel values
// w, h = dimensions
// canvas = HTML canvas on which this image is placed
// imagedata = ImageData object used on this canvas
// offsetx, offsety = an offset on the canvas in which this image is, in case a single canvas was used to contain multiple textures (where the offset points to our texture)
OffscreenCanvasRenderer.prototype.setupImage = function(image) {
if(!image) return undefined;
var data = image[0];
var w = image[1];
var h = image[2];
var canvas;
var offsetx = 0;
var offsety = 0;
if(w == 16 && h == 16) {
// combine multiple textures onto a single canvas, because having many small canvases for each individual texture seems to be slow in some browsers (too much overhead if hardware accel enabled if they're all very small?)
var n = (currentOffscreenCanvasNum & 63);
if(!n) {
currentOffscreenCanvas = createOffscreenCanvas(w * 8, h * 8);
}
canvas = currentOffscreenCanvas;
offsetx = w * (n >> 3);
offsety = h * (n & 7);
currentOffscreenCanvasNum++;
} else {
canvas = createOffscreenCanvas(w, h);
}
var ctx = canvas.getContext('2d');
var imagedata = ctx.createImageData(w, h);
arrayFillImageData(imagedata, data, w, h, 0, 0);
ctx.putImageData(imagedata, offsetx, offsety);
util.setEvent(canvas, 'contextlost', function(e) {
console.log('lost2');
e.preventDefault();
});
util.setEvent(canvas, 'contextrestored', function() {
console.log('restored2');
if(canvas.restoreFun) canvas.restoreFun();
});
return [data, w, h, canvas, imagedata, offsetx, offsety];
};
OffscreenCanvasRenderer.prototype.renderImage = function(image, canvas) {
var iw = image[1];
var ih = image[2];
var offsetx = image[5];
var offsety = image[6];
if(canvas.width != iw) canvas.width = iw;
if(canvas.height != ih) canvas.height = ih;
//var ctx = canvas.getContext("bitmaprenderer");
var ctx = canvas.getContext('2d');
//ctx.imageSmoothingEnabled = false; // this has no effect to replace the 'pixelated' CSS property when I try it.
// There are two options to draw it: using putImageData, or using drawImageData (which requires clearRect first, since it overdraws when there is alpha channel)
// It looks like the drawImage solution is faster, though as of aug 2023 putImageData instead seems faster in chrome. The other solution is available commented out in case JS performance changes
// Probably drawImage really should be the faster one anyway though, since it uses an existing canvas as input so can do whatever is most efficient, rather than be forced to start from the bytes data in image[0]
//ctx.putImageData(image[4], 0, 0);
//ctx.transferFromImageBitmap(image[3].transferToImageBitmap());
// image[3] is the offscreen canvas where a copy of the image is stored at an offset. This is copied to the canvas argument of the function, which has no offset
ctx.clearRect(0, 0, iw, ih); // this has to be done no matter what, because the canvas could be a reused one from the pool.
ctx.drawImage(image[3], offsetx, offsety, iw, ih, 0, 0, iw, ih);
};
OffscreenCanvasRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
if(canvas.width != iw2) canvas.width = iw2;
if(canvas.height != ih2) canvas.height = ih2;
var ctx = canvas.getContext('2d');
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(image) {
ctx.putImageData(image[4], x * iw, y * ih);
}
}
}
};
OffscreenCanvasRenderer.prototype.blendImage = function(image, canvas) {
var iw = image[1];
var ih = image[2];
var offsetx = image[5];
var offsety = image[6];
if(canvas.width != iw) canvas.width = iw;
if(canvas.height != ih) canvas.height = ih;
var ctx = canvas.getContext('2d');
ctx.drawImage(image[3], offsetx, offsety, iw, ih, 0, 0, iw, ih);
};
OffscreenCanvasRenderer.prototype.renderPixel = function(x, y, color, canvas) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(x, y, 1, 1);
};
////////////////////////////////////////////////////////////////////////////////
/*
Unlike OffscreenCanvasRenderer, does not use OffscreenCanvas, and will instead create new ImageData objects and render then to the context of each individual canvas at the time of rendering
This may be slower, but likely causes less issues with chrome removing canvases from memory. A current issue with chrome is that it can delete both the main and offscreen canvases from memory, but sends the 'contextrestored' events to the main canvases first even though they depend on the offscreen ones, and then restoring them is impossible
@constructor
*/
function PureCanvasRenderer() {
}
//PureCanvasRenderer.prototype = new Renderer();
PureCanvasRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var canvas = getCanvasFromPool_();//document.createElement('canvas');
canvas.style.position = 'absolute';
canvas.style.left = x;
canvas.style.top = y;
canvas.style.width = w;
canvas.style.height = h;
canvas.classList.add('pixelated');
parent.appendChild(canvas);
return canvas;
};
PureCanvasRenderer.prototype.setupImage = function(image) {
return image;
};
PureCanvasRenderer.prototype.renderImage = function(image, canvas) {
var iw = image[1];
var ih = image[2];
if(canvas.width != iw) canvas.width = iw;
if(canvas.height != ih) canvas.height = ih;
var ctx = canvas.getContext('2d');
var imagedata = ctx.createImageData(iw, ih);
arrayFillImageData(imagedata, image[0], iw, ih, 0, 0);
ctx.putImageData(imagedata, 0, 0);
// TODO: don't re-set this event each time this is recursively called
util.setEvent(canvas, 'contextrestored', function() {
showMessage('Canvas context restored');
renderImage(image, canvas);
});
};
PureCanvasRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
if(canvas.width != iw2) canvas.width = iw2;
if(canvas.height != ih2) canvas.height = ih2;
var ctx = canvas.getContext('2d');
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(image) {
var iw = image[1];
var ih = image[2];
var imagedata = ctx.createImageData(iw, ih);
arrayFillImageData(imagedata, image[0], iw, ih, 0, 0);
ctx.putImageData(imagedata, x * iw, y * ih);
}
}
}
};
PureCanvasRenderer.prototype.blendImage = function(image, canvas) {
var iw = image[1];
var ih = image[2];
if(canvas.width != iw) canvas.width = iw;
if(canvas.height != ih) canvas.height = ih;
var ctx = canvas.getContext('2d');
// temporary canvas, because alpha blending can only be done that way, it can't ise the imagedata itself directly with alphablend, putImageData does not blend, and drawImage requires a canvas
var canvas2 = document.createElement('canvas');
canvas2.width = iw;
canvas2.height = ih;
var ctx2 = canvas2.getContext('2d');
var imagedata2 = ctx2.createImageData(iw, ih);
arrayFillImageData(imagedata2, image[0], iw, ih, 0, 0);
ctx2.putImageData(imagedata2, 0, 0);
ctx.drawImage(canvas2, 0, 0, iw, ih, 0, 0, iw, ih);
};
PureCanvasRenderer.prototype.renderPixel = function(x, y, color, canvas) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = color;
ctx.fillRect(x, y, 1, 1);
};
////////////////////////////////////////////////////////////////////////////////
/*
Renders without canvas, but on a div, using a little div for every single pixel
This is very slow, but doesn't suffer from two things (that chrome does mostly on android):
-chrome removing content from canvases of background tabs with no way of knowing (not even firing contentrestored event), resulting in lost textures with no way to know that we should recreate them
-chrome sometimes being very slow with canvases, even though we're only rendering mostly 16x16 pixel images on them (maybe it's adding overhead for hardware rendering that makes things worse instead of better like hardware is supposed to do, due to how we're using multiple small canvases)
But this renderer is still unusably slow, so just exists as a proof of concept unfortunately
@constructor
*/
function DivRenderer() {
}
//DivRenderer.prototype = new Renderer();
DivRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = x;
div.style.top = y;
div.style.width = w;
div.style.height = h;
parent.appendChild(div);
return div;
};
DivRenderer.prototype.setupImage = function(image) {
return image;
};
DivRenderer.prototype.renderImage = function(image, canvas) {
canvas.innerHTML = '';
canvas.imagerenderer_w_ = image[1];
canvas.imagerenderer_h_ = image[2];
this.blendImage(image, canvas);
};
DivRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
canvas.innerHTML = '';
canvas.imagerenderer_w_ = iw2;
canvas.imagerenderer_h_ = ih2;
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(image) {
var data = image[0];
for(var y2 = 0; y2 < ih; y2++) {
for(var x2 = 0; x2 < iw; x2++) {
if(data[y2][x2][3] == 0) continue;
this.renderPixel(x * iw + x2, y * ih + y2, RGBtoCSS(data[y2][x2]), canvas)
}
}
}
}
}
};
DivRenderer.prototype.blendImage = function(image, canvas) {
var data = image[0];
var w = image[1];
var h = image[2];
for(var y = 0; y < h; y++) {
for(var x = 0; x < w; x++) {
this.renderPixel(x, y, RGBtoCSS(data[y][x]), canvas)
}
}
};
DivRenderer.prototype.renderPixel = function(x, y, color, canvas) {
var w = canvas.imagerenderer_w_;
var h = canvas.imagerenderer_h_;
var div = document.createElement('div', canvas);
div.style.position = 'absolute';
div.style.left = (100 * x / w) + '%';
div.style.top = (100 * y / h) + '%';
// extra is needed due to HTML with relative sizes not properly putting divs exactly next to each other, it can either put some 1-pixel gaps between them, or make them overlap (which looks bad for semi-translucent pixels)
// even if it looks ok on desktop, e.g. on android it may look bad anyway
var extra = 0.1;
if(CSStoRGB(color)[3] > 200) extra = 0.6; // this is to avoid ugly empty stripes when things just don't match up
div.style.width = ((100 * (x + 1) / w) - (100 * x / w) + extra) + '%';
div.style.height = ((100 * (y + 1) / h) - (100 * y / h) + extra) + '%';
div.style.backgroundColor = color;
canvas.appendChild(div);
};
////////////////////////////////////////////////////////////////////////////////
/*
Uses a technique with CSS box-shadow to put arbitrarily many pixels on a single div
Faster than DivRenderer, and has its advantages of not using canvas, but may have some issues with pixel sizes, edges of tiles not exactly touching or overlapping, ...
It's also still clearly slower than the canvas based renderers anyway
This renderer also has a bug currently that makes it not yet releasable: if you start a new game, all the field tiles will be too small compared to the grid, and this has something to do with resizing of the flexes to accomdate for not yet having the tab-UI take up space
Resizing flexes by changing the browser window size works though, for the most part... sometimes some grid artefacts there too
@constructor
*/
function CSSRenderer() {
}
//CSSRenderer.prototype = new Renderer();
CSSRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = x;
div.style.top = y;
div.style.width = w;
div.style.height = h;
parent.appendChild(div);
return div;
};
CSSRenderer.prototype.setupImage = function(image) {
return image;
};
CSSRenderer.twiddle_ = 1.2;
CSSRenderer.prototype.renderImage = function(image, canvas) {
canvas.innerHTML = '';
canvas.imagerenderer_w_ = image[1];
canvas.imagerenderer_h_ = image[2];
this.blendImage(image, canvas);
};
CSSRenderer.computeBoxShadowAt_ = function(em, image, sx, sy) {
var data = image[0];
var w = image[1];
var h = image[2];
var boxShadow = '';
for(var y = 0; y < h; y++) {
for(var x = 0; x < w; x++) {
if(!data[y][x][3]) continue;
if(boxShadow.length > 0) boxShadow += ', ';
// boxShadow does not support using % as unit, which is very unfortunate. But it does support using 'em', which is also relative, but requires ensuring 'em' is set up correctly
// em should be setup correctly by multiple getComputedStyle calls, but this is still an unfortunate brittle system and it would have been much better if % would work for box-shadow
// the reason we want relative is so that window resizes will automatically make this be correct
boxShadow += ((sx + x) * em) + 'em ';
boxShadow += ((sy + y) * em) + 'em ';
boxShadow += '0 ';
boxShadow += RGBtoCSS(data[y][x]);
}
}
return boxShadow;
};
CSSRenderer.computeBoxShadow_ = function(em, image) {
return CSSRenderer.computeBoxShadowAt_(em, image, 0, 0);
};
CSSRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
canvas.innerHTML = '';
canvas.imagerenderer_w_ = iw2;
canvas.imagerenderer_h_ = ih2;
var fontSize = parseFloat(getComputedStyle(canvas).fontSize);
var elWidth = parseFloat(getComputedStyle(canvas).width);
var em = elWidth / fontSize / iw2;
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = 0;
div.style.top = 0;
div.style.width = (100 / iw2 * CSSRenderer.twiddle_) + '%';
div.style.height = (100 / ih2 * CSSRenderer.twiddle_) + '%';
var boxShadow = '';
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(!image) continue;
if(boxShadow.length > 0) boxShadow += ', ';
boxShadow += CSSRenderer.computeBoxShadowAt_(em, image, x * iw, y * ih);
}
}
div.style.boxShadow = boxShadow;
canvas.appendChild(div);
if(images[0][0] && images[0][0][0][0][3] > 0) {
div.style.backgroundColor = RGBtoCSS(images[0][0][0][0]); // the first one doesn't work for some reason (because it's where the div itself is maybe?)
}
};
CSSRenderer.prototype.blendImage = function(image, canvas) {
var data = image[0];
var w = image[1];
var h = image[2];
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = 0;
div.style.top = 0;
div.style.width = (100 / w * CSSRenderer.twiddle_) + '%';
div.style.height = (100 / h * CSSRenderer.twiddle_) + '%';
var fontSize = parseFloat(getComputedStyle(canvas).fontSize);
var elWidth = parseFloat(getComputedStyle(canvas).width);
var em = elWidth / fontSize / w;
var boxShadow = CSSRenderer.computeBoxShadow_(em, image);
if(data[0][0][3] > 0) {
div.style.backgroundColor = RGBtoCSS(data[0][0]); // the first one doesn't work for some reason (because it's where the div itself is maybe?)
}
div.style.boxShadow = boxShadow;
canvas.appendChild(div);
};
CSSRenderer.prototype.renderPixel = function(x, y, color, canvas) {
// For now, reuse the implementation of the DivRenderer instead...
// TODO: instead add more styles to the boxShadow (or to a new boxShadow div specifically for those extra pixels), and have an 'endPixelRender' function to group them together to avoid reassigning a huge CSS style string each time
new DivRenderer().renderPixel(x, y, color, canvas);
};
////////////////////////////////////////////////////////////////////////////////
/*
Use SVG as the way to render the pixels
Unfortunately it turns out to be too slow, not as bad as DivRenderer but everything feels a bit slugglish, like opening dialogs.
@constructor
*/
function SVGRenderer() {
}
//SVGRenderer.prototype = new Renderer();
SVGRenderer.namespace = 'http://www.w3.org/2000/svg'; // This must be used with createElementNS to make SVG's work
SVGRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var svg = document.createElementNS(SVGRenderer.namespace, 'svg');
svg.style.position = 'absolute';
svg.style.left = x;
svg.style.top = y;
svg.style.width = w;
svg.style.height = h;
svg.setAttribute('shape-rendering', 'crispEdges');
parent.appendChild(svg);
return svg;
};
SVGRenderer.prototype.setupImage = function(image) {
return image;
};
SVGRenderer.prototype.renderImage = function(image, canvas) {
var w = image[1];
var h = image[2];
canvas.innerHTML = '';
canvas.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
this.blendImage(image, canvas);
};
SVGRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
canvas.innerHTML = '';
canvas.setAttribute('viewBox', '0 0 ' + iw2 + ' ' + ih2);
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(image) {
var data = image[0];
for(var y2 = 0; y2 < ih; y2++) {
for(var x2 = 0; x2 < iw; x2++) {
if(data[y2][x2][3] == 0) continue;
this.renderPixel(x * iw + x2, y * ih + y2, RGBtoCSS(data[y2][x2]), canvas)
}
}
}
}
}
};
SVGRenderer.prototype.blendImage = function(image, canvas) {
var data = image[0];
var w = image[1];
var h = image[2];
var html = '';
for(var y = 0; y < h; y++) {
var multi = 1; // combine multiple pixels of same color together to have less elements overall
for(var x = 0; x < w; x++) {
if(data[y][x][3] == 0) continue;
if(x + 1 < w && data[y][x][0] == data[y][x + 1][0]&& data[y][x][1] == data[y][x + 1][1]&& data[y][x][2] == data[y][x + 1][2]&& data[y][x][3] == data[y][x + 1][3]) {
multi++;
continue;
}
html += '<rect width="';
html += multi;
html += '" height="1" x=';
html += x - multi + 1;
html += ' y=';
html += y;
html += ' fill=';
html += RGBtoCSS(data[y][x]);
html += '></rect>';
multi = 1;
}
}
canvas.innerHTML += html;
};
SVGRenderer.prototype.renderPixel = function(x, y, color, canvas) {
//var w = canvas.imagerenderer_w_;
//var h = canvas.imagerenderer_h_;
var rect = document.createElementNS(SVGRenderer.namespace, 'rect');
rect.setAttribute('width', '1');
rect.setAttribute('height', '1');
rect.setAttribute('x', x);
rect.setAttribute('y', y);
rect.setAttribute('fill', color);
canvas.appendChild(rect);
};
////////////////////////////////////////////////////////////////////////////////
/*
Renderer based on base64-encoded PNG images set as backgroundImage in divs
@constructor
*/
function PNGRenderer() {
}
//PNGRenderer.prototype = new Renderer();
PNGRenderer.crc32_table_ = [
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
];
PNGRenderer.crc32_ = function(data) {
var r = 0xffffffff;
for(var i = 0; i < data.length; i++) {
r = PNGRenderer.crc32_table_[(r ^ data[i]) & 15] ^ (r >>> 4);
r = PNGRenderer.crc32_table_[(r ^ (data[i] >>> 4)) & 15] ^ (r >>> 4);
}
r ^= 0xffffffff;
if(r < 0) r += 4294967296;
return r;
};
PNGRenderer.adler32_ = function(data) {
var s1 = 1;
var s2 = 0;
var len = data.length;
var j = 0;
while(len > 0) {
var amount = Math.min(5552, len);
len -= amount;
for(var i = 0; i < amount; i++) {
s1 += data[j++];
s2 += s1;
}
s1 %= 65521;
s2 %= 65521;
}
return s2 * 65536 + s1;
};
PNGRenderer.uint32ToArr_ = function(i) {
return [Math.floor(i / 16777216), Math.floor(i / 65536) & 255, Math.floor(i / 256) & 255, i % 256];
};
PNGRenderer.makeChunk_ = function(type, data) {
var arr_size = PNGRenderer.uint32ToArr_(data.length);
var arr_type = [type.charCodeAt(0), type.charCodeAt(1), type.charCodeAt(2), type.charCodeAt(3)];
var arr_type_data = arr_type.concat(data);
var arr_crc = PNGRenderer.uint32ToArr_(PNGRenderer.crc32_(arr_type_data));
return arr_size.concat(arr_type_data).concat(arr_crc);
};
PNGRenderer.createPNG_ = function(image) {
var data = image[0];
var w = image[1];
var h = image[2];
var arr = [];
arr = arr.concat([137, 80, 78, 71, 13, 10, 26, 10]); // PNG signature
var ihdr = [];
ihdr = ihdr.concat(PNGRenderer.uint32ToArr_(w));
ihdr = ihdr.concat(PNGRenderer.uint32ToArr_(h));
ihdr = ihdr.concat([8, 6, 0, 0, 0]); // bit depth, color type, compression method, filter method, interlace method
arr = arr.concat(PNGRenderer.makeChunk_('IHDR', ihdr));
var pixels = [];
for(var y = 0; y < h; y++) {
pixels.push(0); // filter byte
for(var x = 0; x < w; x++) {
for(var c = 0; c < 4; c++) {
pixels.push(Math.min(Math.max(0, Math.floor(data[y][x][c])), 255));
}
}
}
var deflate = [];
var pos = 0;
while(pos < pixels.length) {
var len = pixels.length;
// uncompressed blocks supports a max length of 65535 only
len = Math.min(65535, len);
var nlen = 65535 - len;
var bfinal = (pos + len < pixels.length) ? 0 : 1;
deflate = deflate.concat([bfinal, len & 255, len >>> 8, nlen & 255, nlen >>> 8]);
deflate = deflate.concat((pos == 0 && len == pixels.length) ? pixels : pixels.slice(pos, pos + len));
pos += len;
}
var idat = [];
idat = idat.concat([120, 1]); // cmf, flevel, fdict, fcheck
idat = idat.concat(deflate);
idat = idat.concat(PNGRenderer.uint32ToArr_(PNGRenderer.adler32_(pixels)));
arr = arr.concat(PNGRenderer.makeChunk_('IDAT', idat));
arr = arr.concat([0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]); // IEND chunk
var text = '';
for(var i = 0; i < arr.length; i++) text += String.fromCharCode(arr[i]);
return btoa(text);
};
PNGRenderer.setPNGBackground_ = function(image, canvas) {
canvas.style.backgroundImage = 'url(data:image/png;base64,' + image[3] + ')';
canvas.style.backgroundSize = '100% 100%';
}
PNGRenderer.prototype.createCanvas = function(x, y, w, h, opt_parent) {
var parent = opt_parent || document.body;
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = x;
div.style.top = y;
div.style.width = w;
div.style.height = h;
div.className = 'pixelated'; // prevent blurry image due to default non-pixelated browser upscaling
parent.appendChild(div);
return div;
};
PNGRenderer.prototype.setupImage = function(image) {
var png = PNGRenderer.createPNG_(image);
return [image[0], image[1], image[2], png];
};
PNGRenderer.prototype.renderImage = function(image, canvas) {
canvas.innerHTML = '';
// Used only for the current renderPixel implementation
canvas.imagerenderer_w_ = image[1];
canvas.imagerenderer_h_ = image[2];
PNGRenderer.setPNGBackground_(image, canvas);
};
PNGRenderer.prototype.renderImages = function(images, canvas) {
var dim = Renderer.computeImagesSizes_(images);
if(dim == undefined) return;
var iw = dim[0];
var ih = dim[1];
var iw2 = dim[2];
var ih2 = dim[3];
var numw = dim[4];
var numh = dim[5];
canvas.innerHTML = '';
// Used only for the current renderPixel implementation
canvas.imagerenderer_w_ = iw2;
canvas.imagerenderer_h_ = ih2;
for(var y = 0; y < images.length; y++) {
for(var x = 0; x < images[y].length; x++) {
var image = images[y][x];
if(image) {
var ex = 100 * x / numw;
var ey = 100 * y / numh;
var ew = 100 * (x + 1) / numw - ex;
var eh = 100 * (y + 1) / numh - ey;
var subCanvas = this.createCanvas(ex + '%', ey + '%', ew + '%', eh + '%', canvas);
PNGRenderer.setPNGBackground_(image, subCanvas);
}
}
}
};
PNGRenderer.prototype.blendImage = function(image, canvas) {
var subCanvas = this.createCanvas(0, 0, '100%', '100%', canvas);
PNGRenderer.setPNGBackground_(image, subCanvas);
};
PNGRenderer.prototype.renderPixel = function(x, y, color, canvas) {
// For now, reuse the implementation of the DivRenderer instead...
new DivRenderer().renderPixel(x, y, color, canvas);
};
////////////////////////////////////////////////////////////////////////////////
//var renderer = new OffscreenCanvasRenderer();
//var renderer = new PureCanvasRenderer();
//var renderer = new DivRenderer();
//var renderer = new CSSRenderer();
//var renderer = new SVGRenderer();
var renderer = new PNGRenderer();
////////////////////////////////////////////////////////////////////////////////
function createCanvas(x, y, w, h, opt_parent) {
return renderer.createCanvas(x, y, w, h, opt_parent);
}
function setupImage(image) {
return renderer.setupImage(image);
}
// like generateImage, but also calls setupImage on it
function generateAndSetupImage(text) {
return setupImage(generateImage(text));
}
function renderImage(image, canvas) {
return renderer.renderImage(image, canvas);
}
// renders grid of images. All images must have the same size, and the grid must be rectangular.
// some images may be set to null/undefined to not render one there
// Using this is faster than using renderImage with individual canvases
function renderImages(images, canvas) {
renderer.renderImages(images, canvas);
}
// similar to renderImage, but doesn't clear the canvas first, so if the image has transparent pixels, it's drawn with the original canvas content as background
function blendImage(image, canvas) {
return renderer.blendImage(image, canvas);
}