-
Notifications
You must be signed in to change notification settings - Fork 10
/
picture_event.js
1523 lines (1398 loc) · 53.1 KB
/
picture_event.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';
/**
* Draw state for a brush event. Used to resume drawTo() from a point along
* the brush stroke.
* @constructor
* @param {number} coordsInd Index in the coords array. Must be an integer.
*/
var BrushEventState = function(coordsInd) {
if (coordsInd === undefined) {
coordsInd = 0;
}
this.coordsInd = coordsInd;
};
/**
* Draw state for a gradient event. Used to determine whether a gradient is
* already drawn in a rasterizer.
* @constructor
*/
var GradientEventState = function() {
this.drawn = false;
};
/**
* An event that is a part of the picture buffer's state.
* @constructor
* @param {string} eventType A short identifier for the type of the event. May
* not contain spaces.
*/
var PictureEvent = function(eventType) {
// TODO: Assert no spaces in eventType.
this.eventType = eventType;
};
/**
* @param {Object} json Json object to add event information to.
*/
PictureEvent.prototype.serializePictureEvent = function(json) {
json['eventType'] = this.eventType;
json['sid'] = this.sid;
json['sessionEventId'] = this.sessionEventId;
json['undone'] = this.undone;
};
/**
* Parse values shared between different picture event classes from a JS object.
* @param {Object} json JS object to parse values from.
*/
PictureEvent.prototype.pictureEventFromJS = function(json) {
this.sid = json['sid'];
this.sessionEventId = json['sessionEventId'];
this.undone = json['undone'];
};
/**
* Parse a json representation of a PictureEvent from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
* @return {boolean} True if parsing succeeded.
*/
PictureEvent.parseLegacy = function(json, arr, i, version) {
json['eventType'] = arr[i++];
json['sid'] = parseInt(arr[i++]);
json['sessionEventId'] = parseInt(arr[i++]);
json['undone'] = (parseInt(arr[i++]) !== 0);
var eventType = json['eventType'];
if (eventType === 'brush') {
BrushEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'scatter') {
ScatterEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'gradient') {
GradientEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'rasterImport') {
RasterImportEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'bufferMerge') {
BufferMergeEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'bufferAdd') {
BufferAddEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'bufferRemove') {
BufferRemoveEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'bufferMove') {
BufferMoveEvent.parseLegacy(json, arr, i, version);
return true;
} else if (eventType === 'eventHide') {
EventHideEvent.parseLegacy(json, arr, i, version);
return true;
} else {
console.log('Unexpected picture event type ' + eventType);
return false;
}
};
/**
* @param {Object} json JS object to parse values from.
* @return {PictureEvent} The parsed event or null if the event was not recognized.
*/
PictureEvent.fromJS = function(json) {
var eventType = json['eventType'];
if (eventType === 'brush') {
var event = new BrushEvent();
} else if (eventType === 'scatter') {
var event = new ScatterEvent();
} else if (eventType === 'gradient') {
var event = new GradientEvent();
} else if (eventType === 'rasterImport') {
var event = new RasterImportEvent();
} else if (eventType === 'bufferMerge') {
var event = new BufferMergeEvent();
} else if (eventType === 'bufferAdd') {
var event = new BufferAddEvent();
} else if (eventType === 'bufferRemove') {
var event = new BufferRemoveEvent();
} else if (eventType === 'bufferMove') {
var event = new BufferMoveEvent();
} else if (eventType === 'eventHide') {
var event = new EventHideEvent();
} else {
console.log('Unexpected picture event type ' + eventType);
return null;
}
event.pictureEventFromJS(json);
event.fromJS(json);
return event;
};
/**
* Create an identical copy of the given PictureEvent.
* @param {PictureEvent} event Event to copy.
* @return {PictureEvent} A copy of the event.
*/
PictureEvent.copy = function(event) {
var serialization = serializeToString(event);
return PictureEvent.fromJS(JSON.parse(serialization));
};
/**
* Determine whether this event's bounding box intersects with the given
* rectangle.
* @param {Rect} rect The rectangle to intersect with.
* @param {AffineTransform} transform Transform for the event coordinates.
* @return {boolean} Does the event's axis-aligned bounding box intersect the
* given rectangle?
*/
PictureEvent.prototype.boundsIntersectRect = function(rect, transform) {
return this.getBoundingBox(rect, transform).intersectsRectRoundedOut(rect);
};
/**
* @return {boolean} Whether the event is a buffer stack change.
*/
PictureEvent.prototype.isBufferStackChange = function() {
return false;
};
/**
* Scale this event.
* @param {number} scale Scaling factor. Must be larger than 0.
*/
PictureEvent.prototype.scale = function(scale) {};
/**
* @enum {number}
*/
PictureEvent.Mode = {
erase: 0,
normal: 1,
multiply: 2,
screen: 3,
overlay: 4,
hardlight: 5,
softlight: 6,
darken: 7,
lighten: 8,
difference: 9,
exclusion: 10,
colorburn: 11,
linearburn: 12,
vividlight: 13,
linearlight: 14,
pinlight: 15,
colordodge: 16,
lineardodge: 17
};
/**
* A PictureEvent representing a brush stroke.
* @constructor
*/
var BrushEvent = function() {
// True if needs brush tip movement interpolation. Can be set to false in inheriting objects.
this.needsTipMovers = true;
};
BrushEvent.prototype = new PictureEvent('brush');
/**
* @param {number} sid Session identifier. Must be an integer.
* @param {number} sessionEventId An event/session specific identifier. The idea
* is that the sid/sessionEventId pair is unique for this event, and that newer
* events will have greater sessionEventIds. Must be an integer.
* @param {boolean} undone Whether this event is undone.
* @param {Uint8Array|Array.<number>} color The RGB color of the stroke. Channel
* values are between 0-255.
* @param {number} flow Alpha value controlling blending individual brush
* samples (circles) to each other in the rasterizer. Range 0 to 1. Normalized
* to represent the resulting maximum alpha value in the rasterizer's bitmap in
* case of a straight stroke and the maximum pressure.
* @param {number} opacity Alpha value controlling blending the rasterizer
* stroke to the target buffer. Range 0 to 1.
* @param {number} radius The stroke radius in pixels.
* @param {number} textureId Id of the brush tip shape texture. 0 is a circle, others are bitmap textures.
* @param {number} softness Value controlling the softness. Range 0 to 1.
* @param {PictureEvent.Mode} mode Blending mode to use.
*/
BrushEvent.prototype.init = function(sid, sessionEventId, undone, color, flow, opacity, radius, textureId, softness,
mode) {
if (sid !== undefined) {
// TODO: assert(color.length == 3);
this.sid = sid;
this.sessionEventId = sessionEventId;
this.undone = undone;
this.color = color;
this.flow = flow;
this.opacity = opacity;
this.radius = radius;
this.textureId = textureId; // Id 0 is a circle, others are bitmap textures.
this.soft = softness > 0.5;
this.mode = mode;
}
this.coords = []; // holding x,y,pressure triplets
this.boundingBoxRasterizer = new BrushEvent.BBRasterizer();
this.hideCount = 0;
this.generation = 0;
if (this.needsTipMovers) {
this.bbTip = new BrushTipMover(true);
this.brushTip = new BrushTipMover(true);
}
};
/**
* @param {Object} json JS object to parse values from.
*/
BrushEvent.prototype.fromJS = function(json) {
this.init();
this.color = json['color'];
this.flow = json['flow'];
this.opacity = json['opacity'];
this.radius = json['radius'];
this.textureId = json['textureId']; // Id 0 is a circle, others are bitmap textures.
this.soft = json['softness'] > 0.5;
this.mode = json['mode'];
var coords = json['coordinates'];
for (var i = 0; i < coords.length; ++i) {
this.coords.push(coords[i]);
}
};
/**
* @const
* @protected
*/
BrushEvent.coordsStride = 3; // x, y and pressure coordinates belong together
/**
* @param {Object} json JS object to serialize the event data to, that can then be stringified.
*/
BrushEvent.prototype.serialize = function(json) {
this.serializePictureEvent(json);
json['color'] = colorUtil.serializeRGB(this.color);
json['flow'] = this.flow;
json['opacity'] = this.opacity;
json['radius'] = this.radius;
json['textureId'] = this.textureId;
json['softness'] = this.soft ? 1.0 : 0.0;
json['mode'] = this.mode;
var coords = [];
var i = 0;
while (i < this.coords.length) {
coords.push(this.coords[i++]);
}
json['coordinates'] = coords;
};
/**
* Parse event attributes conforming to a legacy brush event format.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
* @return {number} Index to continue parsing the brush event coordinates from.
*/
BrushEvent.parseLegacyAttributes = function(json, arr, i, version) {
var color = [];
color[0] = parseInt(arr[i++]);
color[1] = parseInt(arr[i++]);
color[2] = parseInt(arr[i++]);
json['color'] = color;
json['flow'] = parseFloat(arr[i++]);
json['opacity'] = parseFloat(arr[i++]);
json['radius'] = parseFloat(arr[i++]);
json['textureId'] = 0;
if (version > 1) {
json['textureId'] = parseInt(arr[i++]);
}
json['softness'] = parseFloat(arr[i++]);
json['mode'] = parseInt(arr[i++]);
return i;
};
/**
* Parse a BrushEvent from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
*/
BrushEvent.parseLegacy = function(json, arr, i, version) {
i = BrushEvent.parseLegacyAttributes(json, arr, i, version);
BrushEvent.parseLegacyCoords(json, arr, i, version);
};
/**
* Parse BrushEvent coordinates from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
*/
BrushEvent.parseLegacyCoords = function(json, arr, i, version) {
var coords = [];
while (i <= arr.length - BrushEvent.coordsStride) {
coords.push(parseFloat(arr[i++]));
coords.push(parseFloat(arr[i++]));
coords.push(parseFloat(arr[i++]));
}
json['coordinates'] = coords;
};
/**
* Add a triplet of coordinates to the brush stroke. The stroke will travel
* through this control point.
* @param {number} x The x coordinate of the stroke control point.
* @param {number} y The y coordinate of the stroke control point.
* @param {number} pressure Used as a multiplier for stroke radius at this
* point. Must be larger than zero.
*/
BrushEvent.prototype.pushCoordTriplet = function(x, y, pressure) {
// Limit pressure to 5 decimals to cut on file size a bit. This rounding
// method should be okay as long as pressure stays within reasonable bounds.
pressure = Math.round(pressure * 100000) / 100000;
if (this.coords.length > 0) {
if (x === this.coords[this.coords.length - BrushEvent.coordsStride] &&
y === this.coords[this.coords.length - BrushEvent.coordsStride - 1]) {
return;
// TODO: Possible to do something smarter if only pressure changes?
// Drawing small strokes in place would benefit from that.
// Also needs changes in drawing.
}
}
this.coords.push(x);
this.coords.push(y);
this.coords.push(pressure);
};
/**
* Scale this event. This will change the coordinates of the stroke.
* @param {number} scale Scaling factor. Must be larger than 0.
*/
BrushEvent.prototype.scale = function(scale) {
//TODO: assert(scale > 0)
this.radius *= scale;
for (var i = 0; i < this.coords.length; ++i) {
if (i % BrushEvent.coordsStride < 2) {
this.coords[i] *= scale;
}
}
++this.generation; // This invalidates any rasterizers (including BBRasterizer) which have this event cached.
};
/**
* Translate this event. This will change the coordinates of the stroke.
* @param {Vec2} offset The vector to translate with.
*/
BrushEvent.prototype.translate = function(offset) {
for (var i = 0; i < this.coords.length; ++i) {
if (i % BrushEvent.coordsStride === 0) {
this.coords[i] += offset.x;
} else if (i % BrushEvent.coordsStride === 1) {
this.coords[i] += offset.y;
}
}
++this.generation; // This invalidates any rasterizers (including BBRasterizer) which have this event cached.
};
/**
* Normalize pressure to the range 0 to 1. Adjusts the radius accordingly.
*/
BrushEvent.prototype.normalizePressure = function() {
var i;
var maxPressure = 0;
for (i = 0; i < this.coords.length; i += BrushEvent.coordsStride) {
if (this.coords[i + 2] > maxPressure) {
maxPressure = this.coords[i + 2];
}
}
if (maxPressure <= 1.0) {
return;
}
for (i = 0; i < this.coords.length; i += BrushEvent.coordsStride) {
this.coords[i + 2] = Math.round(this.coords[i + 2] / maxPressure * 100000) / 100000;
}
this.scaleRadiusPreservingFlow(maxPressure);
++this.generation;
};
/**
* Scale radius while preserving the stroke's appearance.
* @param {number} radiusScale Multiplier for radius.
*/
BrushEvent.prototype.scaleRadiusPreservingFlow = function(radiusScale) {
var nBlends = Math.ceil(this.radius * 2);
var drawAlpha = colorUtil.alphaForNBlends(this.flow, nBlends);
this.radius *= radiusScale;
nBlends = Math.ceil(this.radius * 2);
this.flow = colorUtil.nBlends(drawAlpha, nBlends);
};
/**
* A rasterizer that does not rasterize, but computes bounding boxes for a brush
* event. Only implements functions necessary for drawing a brush event.
* @constructor
* @extends {BaseRasterizer}
*/
BrushEvent.BBRasterizer = function() {
this.state = null;
this.boundingBox = null;
this.generation = -1;
this.transform = null;
this.transformGeneration = 0;
};
/**
* Clear the bounding box.
*/
BrushEvent.BBRasterizer.prototype.clearDirty = function() {
this.state = null;
this.boundingBox = null;
};
/**
* Get draw event state for the given event.
* @param {BrushEvent} 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.
*/
BrushEvent.BBRasterizer.prototype.getDrawEventState = function(event, transform, stateConstructor) {
if (this.boundingBox === null || event.generation !== this.generation || transform !== this.transform ||
transform.generation !== this.transformGeneration) {
this.state = new stateConstructor();
this.boundingBox = new Rect();
this.generation = event.generation;
this.transform = transform;
this.transformGeneration = transform.generation;
}
return this.state;
};
/**
* Do nothing.
*/
BrushEvent.BBRasterizer.prototype.beginCircles = function() {};
/**
* Add a circle to the bounding box.
* @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 flow alpha. Unused.
* @param {number} rotation Rotation of the circle texture in radians. Unused.
*/
BrushEvent.BBRasterizer.prototype.fillCircle = function(centerX, centerY, radius, flowAlpha, rotation) {
this.boundingBox.unionCircle(centerX, centerY, Math.max(radius, 1.0) + 1.0);
};
/**
* Do nothing.
*/
BrushEvent.BBRasterizer.prototype.flushCircles = function() {};
/**
* Draw the brush event to the given rasterizer's bitmap.
* @param {BaseRasterizer} rasterizer The rasterizer to use.
* @param {AffineTransform} transform Transform for the event coordinates.
* @param {number} untilCoord Maximum coordinate index to draw + 1.
*/
BrushEvent.prototype.drawTo = function(rasterizer, transform, untilCoord) {
var drawState = rasterizer.getDrawEventState(this, transform, BrushEventState);
// Use different tips for BB and normal drawing to avoid clearing the rasterizer all the time while drawing
var brushTip = rasterizer === this.boundingBoxRasterizer ? this.bbTip : this.brushTip;
if (untilCoord === undefined) {
untilCoord = this.coords.length;
}
// TODO: Reset also if transform has changed
if (drawState.coordsInd > untilCoord || brushTip.target !== rasterizer) {
rasterizer.clearDirty();
drawState = rasterizer.getDrawEventState(this, transform, BrushEventState);
}
// TODO: assert(this.coords.length % BrushEvent.coordsStride === 0);
// TODO: assert(untilCoord % BrushEvent.coordsStride === 0);
var i = drawState.coordsInd;
if (i === 0) {
rasterizer.beginCircles(this.soft, this.textureId);
var x = this.coords[i++];
var y = this.coords[i++];
var pressure = this.coords[i++];
brushTip.reset(rasterizer, transform, x, y, pressure, this.radius, this.flow, 0, 1, false,
BrushTipMover.Rotation.off);
}
while (i + BrushEvent.coordsStride <= untilCoord) {
var x = this.coords[i++];
var y = this.coords[i++];
var pressure = this.coords[i++];
brushTip.move(x, y, pressure);
}
drawState.coordsInd = i;
rasterizer.flushCircles();
};
/**
* @param {Rect} clipRect Canvas bounds that can be used to intersect the
* bounding box against, though this is not mandatory.
* @param {AffineTransform} transform Transform for the event coordinates.
* @return {Rect} The event's bounding box. This function is not allowed to
* change its earlier return values as a side effect.
*/
BrushEvent.prototype.getBoundingBox = function(clipRect, transform) {
this.drawTo(this.boundingBoxRasterizer, transform);
return this.boundingBoxRasterizer.boundingBox;
};
/**
* @return {boolean} Is the event drawn using a rasterizer?
*/
BrushEvent.prototype.isRasterized = function() {
return true;
};
/**
* A PictureEvent representing a bunch of individually positioned circles.
* @constructor
*/
var ScatterEvent = function() {
this.eventType = 'scatter';
this.needsTipMovers = false;
};
/**
* @const
* @protected
*/
ScatterEvent.coordsStride = 5; // x, y, radius, flow and rotation coordinates belong together
ScatterEvent.prototype = new BrushEvent();
/**
* Parse a ScatterEvent from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
*/
ScatterEvent.parseLegacy = function(json, arr, i, version) {
i = BrushEvent.parseLegacyAttributes(json, arr, i, version);
ScatterEvent.parseLegacyCoords(json, arr, i, version);
};
/**
* Parse ScatterEvent coordinates from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
*/
ScatterEvent.parseLegacyCoords = function(json, arr, i, version) {
var coords = [];
var eventRadius = json['radius'];
var eventFlow = json['flow'];
while (i < arr.length) {
coords.push(parseFloat(arr[i++]));
coords.push(parseFloat(arr[i++]));
var pressure = parseFloat(arr[i++]);
if (version >= 4) {
coords.push(pressure); // interpreted as radius
coords.push(parseFloat(arr[i++]));
coords.push(parseFloat(arr[i++]));
} else {
coords.push(pressure * eventRadius);
coords.push(eventFlow);
coords.push(0);
}
}
json['coordinates'] = coords;
};
/**
* Scale this event. This will change the coordinates of the stroke.
* @param {number} scale Scaling factor. Must be larger than 0.
*/
ScatterEvent.prototype.scale = function(scale) {
//TODO: assert(scale > 0)
this.radius *= scale;
for (var i = 0; i < this.coords.length; ++i) {
if (i % ScatterEvent.coordsStride < 3) {
this.coords[i] *= scale;
}
}
++this.generation; // This invalidates any rasterizers (including BBRasterizer) which have this event cached.
};
/**
* Translate this event. This will change the coordinates of the stroke.
* @param {Vec2} offset The vector to translate with.
*/
ScatterEvent.prototype.translate = function(offset) {
for (var i = 0; i < this.coords.length; ++i) {
if (i % ScatterEvent.coordsStride === 0) {
this.coords[i] += offset.x;
} else if (i % ScatterEvent.coordsStride === 1) {
this.coords[i] += offset.y;
}
}
++this.generation; // This invalidates any rasterizers (including BBRasterizer) which have this event cached.
};
/**
* Normalize pressure (does not apply to scatter event).
*/
ScatterEvent.prototype.normalizePressure = function() {};
/**
* @param {Rect} clipRect Canvas bounds that can be used to intersect the
* bounding box against, though this is not mandatory.
* @param {AffineTransform} transform Transform for the event coordinates.
* @return {Rect} The event's bounding box. This function is not allowed to
* change its earlier return values as a side effect.
*/
ScatterEvent.prototype.getBoundingBox = function(clipRect, transform) {
this.drawTo(this.boundingBoxRasterizer, transform);
return this.boundingBoxRasterizer.boundingBox;
};
/**
* Draw the brush event to the given rasterizer's bitmap.
* @param {BaseRasterizer} rasterizer The rasterizer to use.
* @param {AffineTransform} transform Transform for the event coordinates.
* @param {number} untilCoord Maximum coordinate index to draw + 1.
*/
ScatterEvent.prototype.drawTo = function(rasterizer, transform, untilCoord) {
var drawState = rasterizer.getDrawEventState(this, transform, BrushEventState);
if (untilCoord === undefined) {
untilCoord = this.coords.length;
} else {
if (drawState.coordsInd > untilCoord) {
rasterizer.clearDirty();
drawState = rasterizer.getDrawEventState(this, transform, BrushEventState);
}
}
var i = drawState.coordsInd;
if (i === 0) {
rasterizer.beginCircles(this.soft, this.textureId);
}
while (i + ScatterEvent.coordsStride <= untilCoord) {
var x = this.coords[i++];
var y = this.coords[i++];
var radius = this.coords[i++];
var flow = this.coords[i++];
var rotation = this.coords[i++];
rasterizer.fillCircle(transform.transformX(x, y),
transform.transformY(x, y),
transform.scaleValue(radius),
flow, rotation);
}
drawState.coordsInd = i;
rasterizer.flushCircles();
};
/**
* @return {boolean} Is the event drawn using a rasterizer?
*/
ScatterEvent.prototype.isRasterized = function() {
return true;
};
/**
* Add coordinates for a circle.
* @param {number} x The x center of the circle.
* @param {number} y The y center of the circle.
* @param {number} radius Radius of the circle.
* @param {number} flow Alpha value for the circle.
* @param {number} rotation Rotation of the circle texture in radians.
*/
ScatterEvent.prototype.fillCircle = function(x, y, radius, flow, rotation) {
this.coords.push(x);
this.coords.push(y);
this.coords.push(radius);
this.coords.push(flow);
this.coords.push(rotation);
};
/**
* A PictureEvent representing a gradient.
* @constructor
* @param {number} sid Session identifier. Must be an integer.
* @param {number} sessionEventId An event/session specific identifier. The idea
* is that the sid/sessionEventId pair is unique for this event, and that newer
* events will have greater sessionEventIds. Must be an integer.
* @param {boolean} undone Whether this event is undone.
* @param {Uint8Array|Array.<number>} color The RGB color of the gradient.
* Channel values are between 0-255.
* @param {number} opacity Alpha value controlling blending the rasterizer
* stroke to the target buffer. Range 0 to 1.
* @param {PictureEvent.Mode} mode Blending mode to use.
*/
var GradientEvent = function(sid, sessionEventId, undone, color, opacity,
mode) {
// TODO: assert(color.length == 3);
if (sid !== undefined) {
this.sid = sid;
this.sessionEventId = sessionEventId;
this.undone = undone;
this.color = color;
this.opacity = opacity;
this.coords0 = new Vec2(0, 0);
this.coords1 = new Vec2(1, 1);
this.mode = mode;
}
this.hideCount = 0;
this.generation = 0;
};
GradientEvent.prototype = new PictureEvent('gradient');
/**
* @param {Object} json JS object to parse values from.
*/
GradientEvent.prototype.fromJS = function(json) {
this.color = json['color'];
this.opacity = json['opacity'];
this.coords0 = new Vec2(json['x0'], json['y0']);
this.coords1 = new Vec2(json['x1'], json['y1']);
this.mode = json['mode'];
};
/**
* Parse a GradientEvent from a tokenized serialization.
* @param {Object} json JS object corresponding to the event to add parsed information to.
* @param {Array.<string>} arr Array containing the tokens, split at spaces from
* the original serialization.
* @param {number} i Index of the first token to deserialize.
* @param {number} version Version number of the serialization format.
*/
GradientEvent.parseLegacy = function(json, arr, i, version) {
var color = [];
color[0] = parseInt(arr[i++]);
color[1] = parseInt(arr[i++]);
color[2] = parseInt(arr[i++]);
json['color'] = color;
json['opacity'] = parseFloat(arr[i++]);
json['mode'] = parseInt(arr[i++]);
json['x0'] = parseFloat(arr[i++]);
json['y0'] = parseFloat(arr[i++]);
json['x1'] = parseFloat(arr[i++]);
json['y1'] = parseFloat(arr[i++]);
};
/**
* @param {Object} json JS object to serialize the event data to, that can then be stringified.
*/
GradientEvent.prototype.serialize = function(json) {
this.serializePictureEvent(json);
json['color'] = colorUtil.serializeRGB(this.color);
json['opacity'] = this.opacity;
json['mode'] = this.mode;
json['x0'] = this.coords0.x;
json['y0'] = this.coords0.y;
json['x1'] = this.coords1.x;
json['y1'] = this.coords1.y;
};
/**
* Scale this event. This will change the coordinates of the gradient.
* @param {number} scale Scaling factor. Must be larger than 0.
*/
GradientEvent.prototype.scale = function(scale) {
//TODO: assert(scale > 0)
this.coords0.x *= scale;
this.coords0.y *= scale;
this.coords1.x *= scale;
this.coords1.y *= scale;
++this.generation; // This invalidates any rasterizers which have this event cached.
};
/**
* Translate this event. This will change the coordinates of the gradient.
* @param {Vec2} offset The vector to translate with.
*/
GradientEvent.prototype.translate = function(offset) {
this.coords0.x += offset.x;
this.coords0.y += offset.y;
this.coords1.x += offset.x;
this.coords1.y += offset.y;
++this.generation; // This invalidates any rasterizers which have this event cached.
};
/**
* @param {Rect} clipRect Canvas bounds that can be used to intersect the
* bounding box against, though this is not mandatory.
* @param {AffineTransform} transform Transform for the event coordinates.
* @return {Rect} The event's bounding box. This function is not allowed to
* change its earlier return values as a side effect.
*/
GradientEvent.prototype.getBoundingBox = function(clipRect, transform) {
var boundingBox = new Rect(clipRect.left, clipRect.right,
clipRect.top, clipRect.bottom);
var coords0 = new Vec2();
var coords1 = new Vec2();
coords0.setVec2(this.coords0);
coords1.setVec2(this.coords1);
transform.transform(coords0);
transform.transform(coords1);
if (coords0.y === coords1.y) {
if (coords1.x > coords0.x) {
boundingBox.limitLeft(coords0.x - 1);
} else if (coords1.x < coords0.x) {
boundingBox.limitRight(coords0.x + 1);
} else {
boundingBox.makeEmpty();
}
} else {
// y = slope * x + b
var normalSlope = -1.0 / coords0.slope(coords1);
var normalB = coords0.y - normalSlope * coords0.x;
if (normalSlope === 0.0) {
if (coords0.y < coords1.y) {
boundingBox.limitTop(coords0.y - 1);
} else {
boundingBox.limitBottom(coords0.y + 1);
}
} else if (normalSlope < 0 && coords1.y < coords0.y) {
// the covered area is in the top left corner
// intersection with left edge
boundingBox.limitBottom(normalSlope * boundingBox.left +
normalB + 1);
// intersection with top edge
boundingBox.limitRight((boundingBox.top - normalB) /
normalSlope + 1);
} else if (normalSlope > 0 && coords1.y < coords0.y) {
// the covered area is in the top right corner
// intersection with right edge
boundingBox.limitBottom(normalSlope * boundingBox.right +
normalB + 1);
// intersection with top edge
boundingBox.limitLeft((boundingBox.top - normalB) /
normalSlope - 1);
} else if (normalSlope < 0 && coords1.y > coords0.y) {
// the covered area is in the bottom right corner
// intersection with right edge
boundingBox.limitTop(normalSlope * boundingBox.right + normalB - 1);
// intersection with bottom edge
boundingBox.limitLeft((boundingBox.bottom - normalB) /
normalSlope - 1);
} else {
// TODO: assert(normalSlope > 0 && coords1.y > coords0.y);
// the covered area is in the bottom left corner
// intersection with left edge
boundingBox.limitTop(normalSlope * boundingBox.left + normalB - 1);
// intersection with bottom edge
boundingBox.limitRight((boundingBox.bottom - normalB) /
normalSlope + 1);
}
}
return boundingBox;
};
/**
* Draw the GradientEvent to the given rasterizer's bitmap.
* @param {BaseRasterizer} rasterizer The rasterizer to use.
* @param {AffineTransform} transform Transform for the event coordinates.
*/
GradientEvent.prototype.drawTo = function(rasterizer, transform) {
var drawState = rasterizer.getDrawEventState(this, transform, GradientEventState);
if (drawState.drawn) {
return;
}
var coords0 = new Vec2();
var coords1 = new Vec2();
coords0.setVec2(this.coords0);
coords1.setVec2(this.coords1);
transform.transform(coords0);
transform.transform(coords1);
rasterizer.linearGradient(coords1, coords0);
drawState.drawn = true;
};
/**
* @return {boolean} Is the event drawn using a rasterizer?
*/
GradientEvent.prototype.isRasterized = function() {
return true;
};
/**
* Event that adds an imported raster image into a buffer.
* @constructor
* @param {number} sid Session identifier. Must be an integer.
* @param {number} sessionEventId An event/session specific identifier. The idea
* is that the sid/sessionEventId pair is unique for this event, and that newer
* events will have greater sessionEventIds. Must be an integer.
* @param {boolean} undone Whether this event is undone.
* @param {HTMLImageElement} importedImage The imported image.
* @param {Rect} rect Rectangle defining the position and scale of the imported image in the buffer.
*/
var RasterImportEvent = function(sid, sessionEventId, undone, importedImage, rect) {
if (sid !== undefined) {
this.sid = sid;
this.sessionEventId = sessionEventId;
this.undone = undone;
this.rect = rect;
this.loadImg(importedImage);
}
};
RasterImportEvent.prototype = new PictureEvent('rasterImport');
/**
* Load an image element. this.loaded will be set to true once loading is complete.
* @param {HTMLImageElement} importedImage Image to load.
*/
RasterImportEvent.prototype.loadImg = function(importedImage) {
this.importedImage = document.createElement('img');
this.loaded = false;
var that = this;
this.importedImage.onload = function() {
that.loaded = true;
};
if (importedImage.src.substring(0, 4) === 'data') {
this.importedImage.src = importedImage.src;
} else {
var c = document.createElement('canvas');
c.width = importedImage.width;
c.height = importedImage.height;
var ctx = c.getContext('2d');
ctx.drawImage(importedImage, 0, 0);
this.importedImage.src = c.toDataURL();
}
};
/**
* @param {Object} json JS object to parse values from.
*/
RasterImportEvent.prototype.fromJS = function(json) {
this.rect = new Rect();
this.rect.left = json['left'];
this.rect.right = json['right'];
this.rect.top = json['top'];
this.rect.bottom = json['bottom'];
var img = document.createElement('img');
img.src = json['src'];