-
Notifications
You must be signed in to change notification settings - Fork 10
/
rasterize.js
1385 lines (1289 loc) · 53.8 KB
/
rasterize.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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Olli Etuaho 2012-2013.
*/
'use strict';
/**
* A base object for a rasterizer that can blend together monochrome circles and
* draw gradients. Do not instance this directly.
* Inheriting objects are expected to implement fillCircle(x, y, radius, flowAlpha, rotation),
* getPixel(coords), clear(), linearGradient(coords1, coords0) and if need be,
* flushCircles() and free().
* @constructor
*/
var BaseRasterizer = function() {};
/**
* Initialize the generic rasterizer data.
* @param {number} width Width of the rasterizer bitmap in pixels.
* @param {number} height Height of the rasterizer bitmap in pixels.
* @param {GLBrushTextures} brushTextures Collection of brush tip textures to use.
*/
BaseRasterizer.prototype.initBaseRasterizer = function(width, height, brushTextures) {
this.clipRect = new Rect(0, width, 0, height);
this.width = width;
this.height = height;
this.brushTextures = brushTextures;
this.soft = false;
this.texturized = false;
this.flowAlpha = 0; // range [0, 1]
this.prevX = null;
this.prevY = null;
this.prevR = null;
this.t = 0;
this.drawEvent = null;
this.drawEventState = null;
this.drawEventGeneration = -1;
this.drawEventTransform = null;
this.drawEventTransformGeneration = -1;
this.drawEventClipRect = new Rect(0, this.width, 0, this.height);
this.dirtyArea = new Rect();
};
/**
* Set the clipping rectangle.
* @param {Rect} rect The new clipping rectangle.
*/
BaseRasterizer.prototype.setClip = function(rect) {
this.clipRect.set(0, this.width, 0, this.height);
this.clipRect.intersectRect(rect);
};
/**
* Reset the clipping rectangle.
*/
BaseRasterizer.prototype.resetClip = function() {
this.clipRect.set(0, this.width, 0, this.height);
};
/**
* Clear all the pixels that have been touched by draw operations, disregarding
* current clipping rectangle.
*/
BaseRasterizer.prototype.clearDirty = function() {
if (!this.dirtyArea.isEmpty()) {
var restoreClip = new Rect();
restoreClip.setRect(this.clipRect);
this.setClip(this.dirtyArea);
this.clear();
this.setClip(restoreClip);
this.dirtyArea.makeEmpty();
}
this.drawEvent = null;
};
/**
* Get draw event state for the given event. The draw event state represents
* what parts of the event have been rasterized to this rasterizer's bitmap.
* Assumes that the intention is to rasterize the given event, and clears any
* previous events from the rasterizer.
* @param {PictureEvent} event The event to be rasterized.
* @param {AffineTransform} transform The transform to check to determine whether a
* clear needs to be performed. Does not affect the rasterizer's operation.
* @param {function()} stateConstructor Constructor for creating a new draw
* event state object unless the event already has been rasterized to this
* rasterizer's bitmap.
* @return {Object} Draw event state for the given event.
*/
BaseRasterizer.prototype.getDrawEventState = function(event, transform, stateConstructor) {
if (event !== this.drawEvent || event.generation !== this.drawEventGeneration ||
!this.drawEventClipRect.containsRect(this.clipRect) || transform !== this.drawEventTransform ||
transform.generation !== this.drawEventTransformGeneration) {
this.clearDirty();
this.drawEvent = event;
this.drawEventState = new stateConstructor();
this.drawEventGeneration = event.generation;
this.drawEventTransform = transform;
this.drawEventTransformGeneration = transform.generation;
}
this.drawEventClipRect.setRect(this.clipRect);
return this.drawEventState;
};
/**
* Initialize drawing circles with the given parameters.
* @param {boolean} soft Use soft edged circles.
* @param {number} textureId Id of the brush tip texture to use. 0 means to draw only circles.
*/
BaseRasterizer.prototype.beginCircles = function(soft, textureId) {
this.soft = soft;
this.texturized = textureId > 0 && this.brushTextures !== null;
if (this.texturized) {
this.brushTex = this.brushTextures.getTexture(textureId - 1);
}
this.minRadius = this.soft ? 1.0 : 0.5;
};
/**
* Get the actual radius of the drawn circle when the appearance of the given
* radius is desired. Very small circles get drawn with the minimum radius with
* reduced alpha to avoid aliasing.
* @param {number} radius The radius of the circle.
* @return {number} The actual draw radius to use.
*/
BaseRasterizer.prototype.drawRadius = function(radius) {
return Math.max(radius, this.minRadius);
};
/**
* Get the bounding radius for drawing a circle of the given radius. This covers
* the antialiasing boundaries of the circle.
* @param {number} radius The radius of the circle.
* @return {number} The draw radius for the purposes of antialiasing.
*/
BaseRasterizer.prototype.drawBoundingRadius = function(radius) {
return Math.max(radius, this.minRadius) + 1.0;
};
/**
* Get the alpha multiplier for the drawn circle when the appearance of the given
* radius is desired. Very small circles get drawn with the minimum radius with
* reduced alpha to avoid aliasing.
* @param {number} radius The radius of the circle.
* @return {number} The alpha multiplier to use.
*/
BaseRasterizer.prototype.circleAlpha = function(radius) {
return Math.pow(Math.min(radius / this.minRadius, 1.0), 2.0);
};
/**
* Flush all circle drawing commands that have been given to the bitmap.
*/
BaseRasterizer.prototype.flushCircles = function() {
};
/**
* Clean up any allocated resources. The rasterizer is not usable after this.
*/
BaseRasterizer.prototype.free = function() {
};
/** Minimum width or height for performing the sanity check. */
BaseRasterizer.minSize = 10;
/**
* Do a basic sanity check by drawing things and reading back the pixels,
* checking that they're roughly within the expected boundaries.
* @return {boolean} The test showed expected results.
*/
BaseRasterizer.prototype.checkSanity = function() {
var i, pix;
this.drawEvent = null;
this.resetClip();
this.clear();
this.beginCircles(false, 0);
for (var i = 0; i < 4; ++i) {
this.fillCircle(1.5 + i, 1.5 + i, 2.0, 1.0, 0);
}
this.flushCircles();
for (i = 1; i <= 4; ++i) {
pix = this.getPixel(new Vec2(i, i));
if (this.getPixel(new Vec2(i, i)) < 0.995) {
console.log('Pixel rendered with flow 1.0 was ' + pix);
return false;
}
}
this.clear();
this.beginCircles(false, 0);
for (var i = 0; i < 11; ++i) {
this.fillCircle(i + 3.5, i + 3.5, 2.0, 0.5, 0);
}
this.flushCircles();
var lastPix = -1.0;
for (i = 3; i <= 9; ++i) {
pix = this.getPixel(new Vec2(i, i));
if (pix < 0.6 || pix > 0.95) {
console.log('Pixel rendered with flow 0.5 was ' + pix);
return false;
}
if (pix < lastPix - 0.05) {
console.log('Pixel rendered with flow 0.5 changed from ' +
lastPix + ' to ' + pix +
' when progressing along the brush stroke');
return false;
}
lastPix = pix;
}
this.clear();
return true;
};
/**
* A javascript-based rasterizer.
* @constructor
* @param {number} width Width of the rasterizer bitmap in pixels.
* @param {number} height Height of the rasterizer bitmap in pixels.
* @param {GLBrushTextures} brushTextures Collection of brush tip textures to use. TODO: SW mode textures
* @extends {BaseRasterizer}
*/
var Rasterizer = function(width, height, brushTextures) {
this.initBaseRasterizer(width, height, brushTextures);
this.buffer = new ArrayBuffer(width * height * 4);
this.data = new Float32Array(this.buffer);
this.clear();
};
Rasterizer.prototype = new BaseRasterizer();
/**
* @return {number} The GPU memory usage of this rasterizer in bytes.
*/
Rasterizer.prototype.getMemoryBytes = function() {
return 0;
};
/**
* Draw the rasterizer's contents to the given bitmap.
* @param {ImageData} targetData The buffer to draw to.
* @param {Uint8Array|Array.<number>} color Color to use for drawing. Channel
* values should be 0-255.
* @param {number} opacity Opacity to use when drawing the rasterization result.
* Opacity for each individual pixel is its rasterized opacity times this
* opacity value.
* @param {number} x Left edge of the rasterizer area to copy to targetData. Must be an
* integer.
* @param {number} y Top edge of the rasterizer area to copy to targetData. Must be an
* integer.
* @param {number} w Width of the targetData buffer and the rasterizer area to copy there.
* Must be an integer.
* @param {number} h Height of the targetData buffer and the rasterizer area to copy there.
* Must be an integer.
*/
Rasterizer.prototype.drawWithColor = function(targetData, color, opacity,
x, y, w, h) {
var tData = targetData.data;
for (var yi = 0; yi < h; ++yi) {
var ind = yi * w * 4;
var sind = x + (y + yi) * this.width;
for (var xi = 0; xi < w; ++xi) {
var alphaT = tData[ind + 3] / 255;
var alphaS = this.data[sind] * opacity;
var tMult = alphaT * (1.0 - alphaS);
var alpha = alphaS + tMult;
tData[ind] = (tData[ind] * tMult + color[0] * alphaS) / alpha;
tData[ind + 1] = (tData[ind + 1] * tMult + color[1] * alphaS) /
alpha;
tData[ind + 2] = (tData[ind + 2] * tMult + color[2] * alphaS) /
alpha;
tData[ind + 3] = 255 * alpha;
ind += 4;
++sind;
}
}
};
/**
* Erase the rasterizer's contents from the given bitmap.
* @param {ImageData} targetData The buffer to erase from.
* @param {number} opacity Opacity to use when erasing the rasterization result.
* Opacity for each individual pixel is its rasterized opacity times this
* opacity value.
* @param {number} x Left edge of the area to copy to targetData. Must be an
* integer.
* @param {number} y Top edge of the area to copy to targetData. Must be an
* integer.
* @param {number} w Width of the targetData buffer and the area to copy there.
* Must be an integer.
* @param {number} h Height of the targetData buffer and the area to copy there.
* Must be an integer.
*/
Rasterizer.prototype.erase = function(targetData, opacity, x, y, w, h) {
var tData = targetData.data;
for (var yi = 0; yi < h; ++yi) {
var ind = yi * w * 4;
var sind = x + (y + yi) * this.width;
for (var xi = 0; xi < w; ++xi) {
var alphaT = tData[ind + 3] / 255;
var alphaS = this.data[sind] * opacity;
tData[ind + 3] = 255 * alphaT * (1.0 - alphaS);
ind += 4;
++sind;
}
}
};
/**
* Draw the rasterizer's contents to the given bitmap with given blend function, applied per channel.
* @param {ImageData} targetData The buffer to draw to.
* @param {Uint8Array|Array.<number>} color Color to use for drawing. Channel
* values should be 0-255.
* @param {number} opacity Opacity to use when drawing the rasterization result.
* Opacity for each individual pixel is its rasterized opacity times this
* opacity value.
* @param {number} x Left edge of the area to copy to targetData. Must be an
* integer.
* @param {number} y Top edge of the area to copy to targetData. Must be an
* integer.
* @param {number} w Width of the targetData buffer and the area to copy there.
* Must be an integer.
* @param {number} h Height of the targetData buffer and the area to copy there.
* Must be an integer.
* @param {function()} blendFunction Blend function that takes inputs three inputs; base color, top color and returns
* the resulting color.
*/
Rasterizer.prototype.blendPerChannel = function(targetData, color, opacity, x, y, w, h, blendFunction) {
var tData = targetData.data;
for (var yi = 0; yi < h; ++yi) {
var ind = yi * w * 4;
var sind = x + (y + yi) * this.width;
for (var xi = 0; xi < w; ++xi) {
var alphaT = tData[ind + 3] / 255;
var alphaS = this.data[sind] * opacity;
var alpha = alphaS + alphaT * (1.0 - alphaS);
for (var c = 0; c < 3; c++) {
tData[ind + c] = colorUtil.blendWithFunction(blendFunction, tData[ind + c], color[c], alphaT, alphaS);
}
tData[ind + 3] = 255 * alpha;
ind += 4;
++sind;
}
}
};
/**
* Draw the rasterizer's contents to the given bitmap. The target bitmap must
* be opaque i.e. contain only pixels with alpha 255.
* @param {ImageData} targetData The buffer to draw to.
* @param {Uint8Array|Array.<number>} color Color to use for drawing. Channel
* values should be 0-255.
* @param {number} opacity Opacity to use when drawing the rasterization result.
* Opacity for each individual pixel is its rasterized opacity times this
* opacity value.
* @param {number} x Left edge of the area to copy to targetData. Must be an
* integer.
* @param {number} y Top edge of the area to copy to targetData. Must be an
* integer.
* @param {number} w Width of the targetData buffer and the area to copy there.
* Must be an integer.
* @param {number} h Height of the targetData buffer and the area to copy there.
* Must be an integer.
*/
Rasterizer.prototype.drawWithColorToOpaque = function(targetData, color,
opacity, x, y, w, h) {
var tData = targetData.data;
for (var yi = 0; yi < h; ++yi) {
var ind = yi * w * 4;
var sind = x + (y + yi) * this.width;
for (var xi = 0; xi < w; ++xi) {
var alphaS = this.data[sind] * opacity;
var tMult = 1.0 - alphaS;
tData[ind] = (tData[ind] * tMult + color[0] * alphaS);
tData[ind + 1] = (tData[ind + 1] * tMult + color[1] * alphaS);
tData[ind + 2] = (tData[ind + 2] * tMult + color[2] * alphaS);
ind += 4;
++sind;
}
}
};
/**
* Clear the rasterizer's bitmap to all 0's.
*/
Rasterizer.prototype.clear = function() {
var br = this.clipRect.getXYWHRoundedOut();
for (var y = 0; y < br.h; ++y) {
for (var x = 0; x < br.w; ++x) {
this.data[br.x + x + (br.y + y) * this.width] = 0;
}
}
};
/**
* Return the pixel at the given coordinates.
* @param {Vec2} coords The coordinates to query with.
* @return {number} The pixel value, in the range 0-1.
*/
Rasterizer.prototype.getPixel = function(coords) {
return this.data[Math.floor(coords.x) + Math.floor(coords.y) * this.width];
};
/**
* Fill a circle to the rasterizer's bitmap at the given coordinates. Uses the
* soft, textureId and flowAlpha values set using beginCircles, and clips the circle to
* the current clipping rectangle.
* @param {number} centerX The x coordinate of the center of the circle.
* @param {number} centerY The y coordinate of the center of the circle.
* @param {number} radius The radius of the circle.
* @param {number} flowAlpha The alpha value for rasterizing the circle.
* @param {number} rotation Rotation of the circle texture in radians.
*/
Rasterizer.prototype.fillCircle = function(centerX, centerY, radius, flowAlpha, rotation) {
if (!this.clipRect.mightIntersectCircleRoundedOut(centerX, centerY,
this.drawBoundingRadius(radius))) {
return;
}
var circleRect = Rect.fromCircle(centerX, centerY,
this.drawBoundingRadius(radius));
circleRect.intersectRectRoundedOut(this.clipRect);
this.dirtyArea.unionRect(circleRect);
// integer x and y coordinates that we use here correspond to pixel corners.
// instead of correcting the x and y by 0.5 on each iteration,
// compensate by moving the center.
centerX -= 0.5;
centerY -= 0.5;
if (this.texturized) {
if (rotation !== 0) {
this.fillTexturizedCircleBlendingRotated(circleRect, centerX, centerY,
this.drawRadius(radius), this.circleAlpha(radius) * flowAlpha,
rotation);
} else {
this.fillTexturizedCircleBlending(circleRect, centerX, centerY,
this.drawRadius(radius), this.circleAlpha(radius) * flowAlpha);
}
} else if (this.soft) {
this.fillSoftCircleBlending(circleRect, centerX, centerY,
this.drawRadius(radius), this.circleAlpha(radius) * flowAlpha);
} else {
this.fillCircleBlending(circleRect, centerX, centerY,
this.drawRadius(radius), this.circleAlpha(radius) * flowAlpha);
}
};
/**
* @param {number} radius Radius to draw with.
* @return {number} Suitable lod for sampling the brush texture.
* @protected
*/
Rasterizer.prototype.lodFromRadius = function(radius) {
// 0.3 negative lod bias to improve quality a bit (brush textures are assumed to be slightly blurred)
var lod = Math.round(Math.log(this.brushTex.levelWidths[0] + 1) / Math.log(2) -
Math.log(radius * 2) / Math.log(2) - 0.3);
if (lod <= 0) {
lod = 0;
} else if (lod >= this.brushTex.levels.length - 1) {
lod = this.brushTex.levels.length - 1;
}
return lod;
};
/**
* Helper to rasterize a texturized circle.
* @param {Rect} boundsRect The rect to rasterize to.
* @param {number} centerX The x coordinate of the center of the circle.
* @param {number} centerY The y coordinate of the center of the circle.
* @param {number} radius The radius of the circle.
* @param {number} alpha Alpha to draw with.
* @protected
*/
Rasterizer.prototype.fillTexturizedCircleBlending = function(boundsRect, centerX, centerY, radius, alpha) {
var rad2 = (radius + 1.0) * (radius + 1.0);
var coordMult = 0.5 / radius;
var lod = this.lodFromRadius(radius);
var sIndStep = this.brushTex.getSIndStep(radius * 2, lod);
for (var y = boundsRect.top; y < boundsRect.bottom; ++y) {
var ind = boundsRect.left + y * this.width;
var powy = Math.pow(y - centerY, 2);
var t = (y - centerY) * coordMult + 0.5;
var rowInd = this.brushTex.getRowInd(t, lod);
var rowBelowWeight = this.brushTex.getRowBelowWeight(t, lod);
var sInd = this.brushTex.getSInd((boundsRect.left - centerX) * coordMult + 0.5, lod);
for (var x = boundsRect.left; x < boundsRect.right; ++x) {
var dist2 = Math.pow(x - centerX, 2) + powy;
if (dist2 < rad2) {
// Trilinear interpolation is too expensive, so do bilinear.
var texValue = this.brushTex.sampleUnsafe(sInd, rowInd, rowBelowWeight, lod);
if (dist2 > (radius - 1.0) * (radius - 1.0)) {
// hacky antialias
var mult = (radius + 1.0 - Math.sqrt(dist2)) * 0.5;
this.data[ind] = alpha * mult * texValue + this.data[ind] *
(1.0 - alpha * mult * texValue);
} else {
this.data[ind] = alpha * texValue + this.data[ind] * (1.0 - alpha * texValue);
}
}
++ind;
sInd += sIndStep;
}
}
};
/**
* Helper to rasterize a rotated texturized circle.
* @param {Rect} boundsRect The rect to rasterize to.
* @param {number} centerX The x coordinate of the center of the circle.
* @param {number} centerY The y coordinate of the center of the circle.
* @param {number} radius The radius of the circle.
* @param {number} alpha Alpha to draw with.
* @param {number} rotation Angle in radians to rotate the texture.
* @protected
*/
Rasterizer.prototype.fillTexturizedCircleBlendingRotated = function(boundsRect, centerX, centerY, radius, alpha,
rotation) {
var rad2 = (radius + 1.0) * (radius + 1.0);
var coordMult = 0.5 / radius;
var lod = this.lodFromRadius(radius);
for (var y = boundsRect.top; y < boundsRect.bottom; ++y) {
var ind = boundsRect.left + y * this.width;
var ydiff = y - centerY;
var powy = Math.pow(ydiff, 2);
for (var x = boundsRect.left; x < boundsRect.right; ++x) {
var xdiff = x - centerX;
var dist2 = Math.pow(x - centerX, 2) + powy;
if (dist2 < rad2) {
// Trilinear interpolation is too expensive, so do bilinear.
var s = Math.cos(rotation) * xdiff * coordMult + Math.sin(rotation) * ydiff * coordMult + 0.5;
var t = -Math.sin(rotation) * xdiff * coordMult + Math.cos(rotation) * ydiff * coordMult + 0.5;
var texValue = this.brushTex.sampleFromLevel(s, t, lod);
if (dist2 > (radius - 1.0) * (radius - 1.0)) {
// hacky antialias
var mult = (radius + 1.0 - Math.sqrt(dist2)) * 0.5;
this.data[ind] = alpha * mult * texValue + this.data[ind] *
(1.0 - alpha * mult * texValue);
} else {
this.data[ind] = alpha * texValue + this.data[ind] * (1.0 - alpha * texValue);
}
}
++ind;
}
}
};
/**
* Helper to rasterize a solid circle.
* @param {Rect} boundsRect The rect to rasterize to.
* @param {number} centerX The x coordinate of the center of the circle.
* @param {number} centerY The y coordinate of the center of the circle.
* @param {number} radius The radius of the circle.
* @param {number} alpha Alpha to draw with.
* @protected
*/
Rasterizer.prototype.fillCircleBlending = function(boundsRect, centerX, centerY, radius, alpha) {
var rad2 = (radius + 1.0) * (radius + 1.0);
for (var y = boundsRect.top; y < boundsRect.bottom; ++y) {
var ind = boundsRect.left + y * this.width;
var powy = Math.pow(y - centerY, 2);
for (var x = boundsRect.left; x < boundsRect.right; ++x) {
var dist2 = Math.pow(x - centerX, 2) + powy;
if (dist2 < rad2) {
if (dist2 > (radius - 1.0) * (radius - 1.0)) {
// hacky antialias
var mult = (radius + 1.0 - Math.sqrt(dist2)) * 0.5;
this.data[ind] = alpha * mult + this.data[ind] *
(1.0 - alpha * mult);
} else {
this.data[ind] = alpha + this.data[ind] * (1.0 - alpha);
}
}
++ind;
}
}
};
/**
* Helper to rasterize a soft circle.
* @param {Rect} boundsRect The rect to rasterize to.
* @param {number} centerX The x coordinate of the center of the circle.
* @param {number} centerY The y coordinate of the center of the circle.
* @param {number} radius The radius of the circle.
* @param {number} alpha Alpha to draw with.
* @protected
*/
Rasterizer.prototype.fillSoftCircleBlending = function(boundsRect, centerX, centerY, radius, alpha) {
var rad2 = radius * radius;
for (var y = boundsRect.top; y < boundsRect.bottom; ++y) {
var ind = boundsRect.left + y * this.width;
var powy = Math.pow(y - centerY, 2);
for (var x = boundsRect.left; x < boundsRect.right; ++x) {
var dist2 = Math.pow(x - centerX, 2) + powy;
if (dist2 < rad2) {
var distalpha = (1.0 - Math.sqrt(dist2 / rad2)) * alpha;
if (dist2 > (radius - 1.0) * (radius - 1.0)) {
// hacky antialias
distalpha *= (radius + 1.0 - Math.sqrt(dist2)) * 0.5;
}
this.data[ind] = distalpha + this.data[ind] * (1.0 - distalpha);
}
++ind;
}
}
};
/**
* Draw a linear gradient from coords1 to coords0. The pixel at coords1 will be
* set to 1.0, and the pixel at coords0 will be set to 0.0. If the coordinates
* are the same, does nothing.
* @param {Vec2} coords1 Coordinates for the 1.0 end of the gradient.
* @param {Vec2} coords0 Coordinates for the 0.0 end of the gradient.
*/
Rasterizer.prototype.linearGradient = function(coords1, coords0) {
var br = this.clipRect.getXYWHRoundedOut();
if (coords1.x === coords0.x) {
if (coords1.y === coords0.y) {
return;
}
this.dirtyArea.unionRect(this.clipRect);
// Every horizontal line will be of one color
var top = Math.min(coords1.y, coords0.y);
var bottom = Math.max(coords1.y, coords0.y);
var topFill = (coords0.y < coords1.y) ? 0.0 : 1.0;
var bottomFill = 1.0 - topFill;
var y = br.y;
var ind = y * this.width + br.x;
var right = ind + br.w;
while (y + 0.5 <= top && y < br.y + br.h) {
ind = y * this.width + br.x;
right = ind + br.w;
while (ind < right) {
this.data[ind] = topFill;
++ind;
}
++y;
}
while (y + 0.5 < bottom && y < br.y + br.h) {
// Take the gradient color at the pixel center.
// TODO: Integrate coverage along y instead to anti-alias this.
// TODO: assert(y + 0.5 > top && y + 0.5 < bottom);
ind = y * this.width + br.x;
right = ind + br.w;
var rowFill = (coords0.y < coords1.y ?
(y + 0.5 - top) : (bottom - y - 0.5)) /
(bottom - top);
while (ind < right) {
this.data[ind] = rowFill;
++ind;
}
++y;
}
while (y < br.y + br.h) {
ind = y * this.width + br.x;
right = ind + br.w;
while (ind < right) {
this.data[ind] = bottomFill;
++ind;
}
++y;
}
return;
} else {
this.dirtyArea.unionRect(this.clipRect);
var lineStartCoords = new Vec2(0, 0);
var lineEndCoords = new Vec2(0, 0);
for (var y = br.y; y < br.y + br.h; ++y) {
// TODO: Again, integrating coverage over the pixel would be nice.
lineStartCoords.x = 0.5;
lineStartCoords.y = y + 0.5;
lineEndCoords.x = this.width - 0.5;
lineEndCoords.y = y + 0.5;
lineStartCoords.projectToLine(coords0, coords1);
lineEndCoords.projectToLine(coords0, coords1);
var lineStartValue = (lineStartCoords.x - coords0.x) /
(coords1.x - coords0.x);
var lineEndValue = (lineEndCoords.x - coords0.x) /
(coords1.x - coords0.x);
var x = br.x;
var ind = y * this.width + x;
var right = ind + br.w;
while (ind < right) {
var mult = (x / this.width);
var unclamped = mult * lineEndValue +
(1.0 - mult) * lineStartValue;
this.data[ind] = Math.max(0.0, Math.min(1.0, unclamped));
++ind;
++x;
}
}
}
};
/**
* 'redGreen' uses red and green channels of the UINT8 texture to store the high
* and low bits of the alpha value. 'alpha' uses just the alpha channel, so that
* normal built-in blends can be used.
* @enum {number}
*/
var GLRasterizerFormat = {
redGreen: 0,
alpha: 1
};
/**
* A WebGL rasterizer using two RGB Uint8 buffers as backing for its bitmap.
* Floating point support in the WebGL implementation is not required.
* @constructor
* @extends {BaseRasterizer}
*/
var GLDoubleBufferedRasterizer = function() {};
GLDoubleBufferedRasterizer.prototype = new BaseRasterizer();
/**
* @param {WebGLRenderingContext} gl The rendering context.
* @param {Object} glManager The state manager returned by glStateManager() in
* utilgl.
* @param {number} width Width of the rasterizer bitmap in pixels.
* @param {number} height Height of the rasterizer bitmap in pixels.
* @param {GLBrushTextures} brushTextures Collection of brush tip textures to use.
* @return {GLDoubleBufferedRasterizer}
*/
GLDoubleBufferedRasterizer.create = function(gl, glManager, width, height, brushTextures) {
var rast = new GLDoubleBufferedRasterizer();
rast.init(gl, glManager, width, height, brushTextures);
return rast;
};
/**
* @param {WebGLRenderingContext} gl The rendering context.
* @param {Object} glManager The state manager returned by glStateManager() in
* utilgl.
* @param {number} width Width of the rasterizer bitmap in pixels.
* @param {number} height Height of the rasterizer bitmap in pixels.
* @param {GLBrushTextures} brushTextures Collection of brush tip textures to use.
*/
GLDoubleBufferedRasterizer.prototype.init = function(gl, glManager, width, height, brushTextures) {
this.initBaseRasterizer(width, height, brushTextures);
this.initGLRasterizer(gl, glManager, GLRasterizerFormat.redGreen,
GLDoubleBufferedRasterizer.maxCircles);
// TODO: Move to gl.RG if EXT_texture_RG becomes available in WebGL
this.tex0 = glUtils.createTexture(gl, width, height, gl.RGB);
this.tex1 = glUtils.createTexture(gl, width, height, gl.RGB);
this.tex0Inval = new Rect();
this.tex1Inval = new Rect();
this.currentTex = 0;
if (!GLDoubleBufferedRasterizer.nFillShader) {
// TODO: assert(!GLDoubleBufferedRasterizer.nSoftShader);
// assert(!GLDoubleBufferedRasterizer.nTexShader);
// assert(!GLDoubleBufferedRasterizer.linearGradientShader);
GLDoubleBufferedRasterizer.nFillShader = [];
GLDoubleBufferedRasterizer.nSoftShader = [];
GLDoubleBufferedRasterizer.nTexShader = [];
for (var i = 1; i <= GLDoubleBufferedRasterizer.maxCircles; ++i) {
GLDoubleBufferedRasterizer.nFillShader.push(
new RasterizeShader(GLRasterizerFormat.redGreen, false, false, i, false, true));
GLDoubleBufferedRasterizer.nSoftShader.push(
new RasterizeShader(GLRasterizerFormat.redGreen, true, false, i, false, true));
GLDoubleBufferedRasterizer.nTexShader.push(
new RasterizeShader(GLRasterizerFormat.redGreen, false, true, i, false, true));
}
GLDoubleBufferedRasterizer.linearGradientShader = new GradientShader(GLRasterizerFormat.redGreen);
}
this.generateShaderPrograms(GLDoubleBufferedRasterizer.nFillShader,
GLDoubleBufferedRasterizer.nSoftShader,
GLDoubleBufferedRasterizer.nTexShader);
this.linearGradientProgram = GLDoubleBufferedRasterizer.linearGradientShader.programInstance(this.gl);
this.gradientUniformParameters =
GLDoubleBufferedRasterizer.linearGradientShader.uniformParameters(this.width, this.height);
this.convUniformParameters = new blitShader.ConversionUniformParameters();
this.conversionProgram = this.glManager.shaderProgram(
blitShader.convertRedGreenSrc, blitShader.blitVertSrc,
{'uSrcTex': 'tex2d', 'uColor': '4fv'});
};
/** @const */
GLDoubleBufferedRasterizer.maxCircles = 7;
/**
* RasterizeShaders for drawing filled circles. Amount of circles is determined
* at compile-time, nFillShader[i] draws i+1 circles.
* @protected
*/
GLDoubleBufferedRasterizer.nFillShader = null;
/**
* RasterizeShaders for drawing soft circles. Amount of circles is determined
* at compile-time, nSoftShader[i] draws i+1 circles.
* @protected
*/
GLDoubleBufferedRasterizer.nSoftShader = null;
/**
* RasterizeShaders for drawing texturized circles. Amount of circles is determined
* at compile-time, nTexShader[i] draws i+1 circles.
* @protected
*/
GLDoubleBufferedRasterizer.nTexShader = null;
/**
* @return {number} The GPU memory usage of this rasterizer in bytes.
*/
GLDoubleBufferedRasterizer.prototype.getMemoryBytes = function() {
return this.width * this.height * 6;
};
/**
* Initialize the WebGL-based rasterizer.
* @param {WebGLRenderingContext} gl The rendering context.
* @param {Object} glManager The state manager returned by glStateManager() in
* utilgl.
* @param {GLRasterizerFormat} format Format of the rasterizers texture.
* @param {number} maxCircles The maximum amount of circles to render in one
* pass. Must be an integer > 0.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.initGLRasterizer = function(gl, glManager, format, maxCircles) {
this.gl = gl;
this.glManager = glManager;
this.format = format;
this.paramsStride = 4;
this.maxCircles = maxCircles;
// 4 bytes per float
// 1st params buffer contains x, y, radius and alpha of each circle (set in fillCircle).
var paramBuffer = new ArrayBuffer(this.maxCircles *
this.paramsStride * 4);
this.params = new Float32Array(paramBuffer);
// 2nd params buffer contains angle of each circle (set in fillCircle).
var paramBufferB = new ArrayBuffer(this.maxCircles *
this.paramsStride * 4);
this.paramsB = new Float32Array(paramBufferB);
this.circleRect = new Rect();
this.circleInd = 0;
this.brushTex = null;
};
/**
* Generate shader programs for a WebGL-based rasterizer.
* @param {Array.<RasterizeShader>} nFillShader Filled circle shaders.
* @param {Array.<RasterizeShader>} nSoftShader Soft circle shaders.
* @param {Array.<RasterizeShader>} nTexShader Texturized circle shaders.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.generateShaderPrograms = function(nFillShader, nSoftShader, nTexShader) {
this.nFillCircleProgram = [];
this.nSoftCircleProgram = [];
this.nTexCircleProgram = [];
this.fillUniformParameters = [];
this.texUniformParameters = [];
// TODO: assert(nFillShader.length == nSoftShader.length);
for (var i = 0; i < nFillShader.length; ++i) {
this.nFillCircleProgram.push(nFillShader[i].programInstance(this.gl));
this.nSoftCircleProgram.push(nSoftShader[i].programInstance(this.gl));
this.nTexCircleProgram.push(nTexShader[i].programInstance(this.gl));
// The uniforms are the same for the soft and fill shaders
this.fillUniformParameters.push(nFillShader[i].uniformParameters(this.width, this.height));
this.texUniformParameters.push(nTexShader[i].uniformParameters(this.width, this.height));
}
};
/**
* Clean up any allocated resources. The rasterizer is not usable after this.
*/
GLDoubleBufferedRasterizer.prototype.free = function() {
this.gl.deleteTexture(this.tex0);
this.gl.deleteTexture(this.tex1);
this.tex0 = undefined;
this.tex1 = undefined;
};
/**
* Switch between textures.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.switchTex = function() {
this.currentTex = 1 - this.currentTex;
};
/**
* Get the source texture that contains the most up-to-date contents of the
* rasterizer bitmap.
* @return {WebGLTexture} The source texture.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.getTex = function() {
if (this.currentTex === 0) {
return this.tex0;
} else {
return this.tex1;
}
};
/**
* Draw the rasterizer's contents to the current framebuffer. To be used for testing only.
* @param {Uint8Array|Array.<number>} color Color to use for drawing. Channel
* values should be 0-255.
* @param {number} opacity Opacity to use when drawing the rasterization result.
* Opacity for each individual pixel is its rasterized opacity times this
* opacity value.
*/
GLDoubleBufferedRasterizer.prototype.drawWithColor = function(color, opacity) {
this.convUniformParameters['uSrcTex'] = this.getTex();
for (var i = 0; i < 3; ++i) {
this.convUniformParameters['uColor'][i] = color[i] / 255.0;
}
this.convUniformParameters['uColor'][3] = opacity;
this.glManager.drawFullscreenQuad(this.conversionProgram,
this.convUniformParameters);
};
/**
* Get the target texture for rasterization.
* @return {WebGLTexture} The target texture.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.getTargetTex = function() {
if (this.currentTex === 0) {
return this.tex1;
} else {
return this.tex0;
}
};
/**
* Clear the target texture's invalid area after drawing.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.clearTargetInval = function() {
if (this.currentTex === 0) {
this.tex1Inval.makeEmpty();
} else {
this.tex0Inval.makeEmpty();
}
};
/**
* Clear the rasterizer's bitmap (both textures) to all 0's.
*/
GLDoubleBufferedRasterizer.prototype.clear = function() {
this.gl.viewport(0, 0, this.width, this.height);
this.gl.clearColor(0, 0, 0, 0);
glUtils.updateClip(this.gl, this.clipRect, this.height);
for (var i = 0; i < 2; ++i) {
this.glManager.useFboTex(this.getTargetTex());
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.clearTargetInval();
this.switchTex();
}
};
/**
* Get rectangular bounds for a draw pass.
* @param {Rect} invalRect Rectangle containing the things to draw. This is
* combined with the target texture's invalidated area and clipped by the
* current clip rect. The function is allowed to mutate this Rect.
* @return {Rect} The bounds for the draw pass.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.getDrawRect = function(invalRect) {
var drawRect = (this.currentTex === 0) ? this.tex1Inval : this.tex0Inval;
drawRect.unionRect(invalRect);
drawRect.intersectRectRoundedOut(this.clipRect);
return drawRect;
};
/**
* Set the framebuffer, flow alpha, source texture and brush texture for drawing.
* @param {Object.<string, *>} uniformParameters Map from uniform names to
* uniform values to set drawing parameters to.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.preDraw = function(uniformParameters) {
this.gl.viewport(0, 0, this.width, this.height);
this.glManager.useFboTex(this.getTargetTex());
if (uniformParameters !== null) {
uniformParameters['uSrcTex'] = this.getTex();
if (this.texturized) {
uniformParameters['uBrushTex'] = this.brushTex;
}
}
};
/**
* Invalidate the area of the source texture which has now been updated in the
* target texture, and switch textures.
* @param {Rect} invalRect The area that has been changed in the target texture.
* @protected
*/
GLDoubleBufferedRasterizer.prototype.postDraw = function(invalRect) {
this.clearTargetInval();
if (this.currentTex === 0) {
this.tex0Inval.unionRect(invalRect);