Repository navigation
Expand file tree
/
Copy pathgraphic.js
More file actions
7089 lines (6723 loc) · 349 KB
/
Copy pathgraphic.js
File metadata and controls
7089 lines (6723 loc) · 349 KB
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
//==============================================================================
// 포함 모듈 목록.
//==============================================================================
const System = globalThis;
import { Object } from "../base/object.js";
import { Node } from "../base/node.js";
import { Rect } from "../base/rect.js";
import { Vector2 } from "../base/vector2.js";
import { Engine } from "./engine.js";
import { Color } from "../base/color.js";
import { TransformNode } from "./node/transformnode.js";
import { TransformMatrix } from "../base/transformmatrix.js";
import { ShaderProgram, reportShaderBuildFailure } from "./graphic/shaderprogram.js";
import { ImageTextureCache } from "./graphic/imagetexturecache.js";
import { DecodedImageStore } from "./graphic/decodedimagestore.js";
import { TextStringTextureCache } from "./graphic/textstringtexturecache.js";
import { WebGLStateCache } from "./graphic/webglstatecache.js";
import { GpuMemoryTracker } from "./graphic/gpumemorytracker.js";
import { ColorSpace, readColorSpace } from "./graphic/colorspace.js";
import * as Math from "../base/math.js";
//==============================================================================
// 전역 상수 목록.
//==============================================================================
// 버텍스 셰이더. (픽셀 좌표 → 클립 좌표)
const VERTEXSHADER_SOURCE = `#version 300 es
in vec2 vertexPosition;
in vec2 vertexTextureCoordinate;
uniform mat3 projectionMatrix;
uniform mat3 modelMatrix;
out vec2 fragmentTextureCoordinate;
void main() {
vec3 transformedPosition = projectionMatrix * (modelMatrix * vec3(vertexPosition, 1.0));
gl_Position = vec4(transformedPosition.xy, 0.0, 1.0);
fragmentTextureCoordinate = vertexTextureCoordinate;
}
`;
// 프래그먼트 셰이더. (프리멀티플라이드 알파 출력)
// - 단색 도형은 1x1 흰색 텍스처를 바인드해 같은 경로로 처리한다.
// - tintColor 는 이미지 실루엣(알파) 안쪽에만 색을 덮는 틴트. (alpha 0 이면 비활성)
// - textureLodBias 는 밉맵 단계를 고를 때 더하는 값. (setImageMipmapBias, 음수면 더 큰 단계를 골라 또렷해진다)
const FRAGMENTSHADER_SOURCE = `#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
uniform sampler2D mainTexture;
uniform vec4 mainColor;
uniform vec4 tintColor;
uniform float globalAlpha;
uniform float textureLodBias;
out vec4 outputColor;
void main() {
vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate, textureLodBias);
vec3 tintedColor = mix(textureColor.rgb, tintColor.rgb * textureColor.a, tintColor.a);
float finalAlpha = textureColor.a * mainColor.a * globalAlpha;
vec3 finalColor = tintedColor * mainColor.rgb * mainColor.a * globalAlpha;
outputColor = vec4(finalColor, finalAlpha);
}
`;
// 버텍스 1개당 float 수. (x, y, u, v)
// 파티클 배치 버텍스 셰이더. (정점마다 색을 실어 한 번의 드로우로 수백 개를 그린다)
const PARTICLE_VERTEXSHADER_SOURCE = `#version 300 es
in vec2 vertexPosition;
in vec2 vertexTextureCoordinate;
in vec4 vertexColor;
uniform mat3 projectionMatrix;
uniform mat3 modelMatrix;
out vec2 fragmentTextureCoordinate;
out vec4 fragmentColor;
void main() {
vec3 transformedPosition = projectionMatrix * (modelMatrix * vec3(vertexPosition, 1.0));
gl_Position = vec4(transformedPosition.xy, 0.0, 1.0);
fragmentTextureCoordinate = vertexTextureCoordinate;
fragmentColor = vertexColor;
}
`;
// 파티클 배치 프래그먼트 셰이더. (프리멀티플라이드 알파 출력)
const PARTICLE_FRAGMENTSHADER_SOURCE = `#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
in vec4 fragmentColor;
uniform sampler2D mainTexture;
uniform float globalAlpha;
uniform float textureLodBias;
out vec4 outputColor;
void main() {
vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate, textureLodBias);
float finalAlpha = textureColor.a * fragmentColor.a * globalAlpha;
vec3 finalColor = textureColor.rgb * fragmentColor.rgb * fragmentColor.a * globalAlpha;
outputColor = vec4(finalColor, finalAlpha);
}
`;
// 하위 트리 그리기 경계를 읽어 두는 칸. (drawNode 가 읽은 바로 뒤에 견주고 버린다)
const subtreeCullRect = new Rect();
// 스프라이트 묶어 그리기의 자르기 사각형 표 칸 수. (0 번은 자르지 않는 칸, 차면 그때까지 쌓인 것을 그린다)
const BATCH_CLIP_SLOT_CAPACITY = 32;
// 스프라이트 묶어 그리기의 텍스처 칸 수 상한. (기기의 MAX_TEXTURE_IMAGE_UNITS 와 이 값 가운데 작은 것, PixiJS 와 같은 16)
const BATCH_TEXTURE_SLOT_LIMIT = 16;
// 자르지 않는 칸의 사각형 끝. (디바이스 픽셀, float 로 정확한 2^24)
const BATCH_UNCLIPPED_EXTENT = 16777216;
// 셰이더 자르기 경계가 화소 경계(또는 화소 가운데)에 놓였다고 보는 차이. (디바이스 픽셀, 변환 셈의 float 오차만 받는다)
const CLIP_EDGE_EPSILON = 1 / 256;
// 노드의 하위 트리가 보이는 사각형(화면과 걸린 자르기)과 놓인 꼴. (그리기 순회의 화면 밖 거르기)
const NODE_VISIBILITY_UNKNOWN = 0; // 모른다, 또는 걸친다. (자손을 저마다 본다)
const NODE_VISIBILITY_OUTSIDE = 1; // 다 밖이다. (건너뛴다)
const NODE_VISIBILITY_INSIDE = 2; // 다 안이다. (그 아래 자손은 견주지 않고 그린다)
//==============================================================================
// 자르기 경계가 화소 가운데(정수 + 0.5)에 걸쳤는지. (래스터 동점 규칙이 기기마다 다를 수 있는 자리)
//==============================================================================
function isClipEdgeOnPixelCenter(edge) {
const fraction = edge - System.Math.floor(edge);
return System.Math.abs(fraction - 0.5) < CLIP_EDGE_EPSILON;
}
// 스프라이트 묶어 그리기 버텍스 셰이더. (정점은 쌓을 때 이미 디바이스 픽셀 좌표로 바꿔 둔다)
// - vertexSlot.x 는 텍스처 칸 번호, vertexSlot.y 는 자르기 사각형 표의 칸 번호다. (텍스처와 축에 맞는 자르기가 바뀌어도 묶음이 이어진다)
const BATCH_VERTEXSHADER_SOURCE = `#version 300 es
in vec2 vertexPosition;
in vec2 vertexTextureCoordinate;
in vec4 vertexColor;
in vec4 vertexTintColor;
in vec2 vertexSlot;
uniform mat3 projectionMatrix;
uniform vec4 clipRectList[${BATCH_CLIP_SLOT_CAPACITY}];
out vec2 fragmentTextureCoordinate;
out vec4 fragmentColor;
out vec4 fragmentTintColor;
flat out int fragmentTextureSlot;
flat out vec4 fragmentClipRect;
flat out float fragmentParticleAlpha;
void main() {
vec3 transformedPosition = projectionMatrix * vec3(vertexPosition, 1.0);
gl_Position = vec4(transformedPosition.xy, 0.0, 1.0);
fragmentTextureCoordinate = vertexTextureCoordinate;
fragmentColor = vertexColor;
fragmentTintColor = vertexTintColor;
fragmentTextureSlot = int(vertexSlot.x + 0.5);
fragmentClipRect = clipRectList[int(vertexSlot.y + 0.5)];
fragmentParticleAlpha = vertexTintColor.a < 0.0 ? vertexTintColor.r : -1.0;
}
`;
//==============================================================================
// 스프라이트 묶어 그리기 프래그먼트 셰이더 글 짓기. (기본 셰이더와 같은 셈. 정점 색은 mainColor.rgb * mainColor.a * globalAlpha 와 mainColor.a * globalAlpha)
// - 텍스처는 칸 수만큼의 샘플러 배열에 묶고 칸 번호로 고른다. (GLSL ES 3.00 은 샘플러 배열을 상수로만 짚을 수 있어 칸마다 갈래를 둔다, PixiJS 와 같은 꼴)
// - 자르기는 화소 가운데(gl_FragCoord)를 디바이스 픽셀로 옮겨 사각형 [왼쪽, 오른쪽) x [위, 아래) 밖이면 버린다. (스텐실에 사각형을 그려 자른 것과 화소까지 같다)
// - 틴트 알파가 음수인 정점은 정점 색 쿼드(drawColoredQuads)다. 정점 색은 곱하지 않은 색 그대로, 틴트 빨강 칸에 전역 알파를 싣고 파티클 셰이더와 같은 식으로 셈한다.
//==============================================================================
function createBatchFragmentShaderSource(textureSlotCount) {
let textureSampleSource = "";
for (let slotIndex = 0; slotIndex < textureSlotCount; ++slotIndex) {
let branchSource = `else if (fragmentTextureSlot == ${slotIndex})`;
if (slotIndex === 0) {
branchSource = `if (fragmentTextureSlot == ${slotIndex})`;
}
if (slotIndex > 0 && slotIndex === textureSlotCount - 1) {
branchSource = "else";
}
textureSampleSource += ` ${branchSource} {\n textureColor = texture(mainTextureList[${slotIndex}], fragmentTextureCoordinate, textureLodBias);\n }\n`;
}
return `#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
in vec4 fragmentColor;
in vec4 fragmentTintColor;
flat in int fragmentTextureSlot;
flat in vec4 fragmentClipRect;
flat in float fragmentParticleAlpha;
uniform sampler2D mainTextureList[${textureSlotCount}];
uniform float textureLodBias;
uniform float framebufferHeight;
out vec4 outputColor;
void main() {
vec2 devicePosition = vec2(gl_FragCoord.x, framebufferHeight - gl_FragCoord.y);
if (devicePosition.x < fragmentClipRect.x || devicePosition.y < fragmentClipRect.y || devicePosition.x >= fragmentClipRect.z || devicePosition.y >= fragmentClipRect.w) {
discard;
}
vec4 textureColor = vec4(0.0);
${textureSampleSource} if (fragmentParticleAlpha >= 0.0) {
float finalAlpha = textureColor.a * fragmentColor.a * fragmentParticleAlpha;
vec3 finalColor = textureColor.rgb * fragmentColor.rgb * fragmentColor.a * fragmentParticleAlpha;
outputColor = vec4(finalColor, finalAlpha);
return;
}
vec3 tintedColor = mix(textureColor.rgb, fragmentTintColor.rgb * textureColor.a, fragmentTintColor.a);
outputColor = vec4(tintedColor * fragmentColor.rgb, textureColor.a * fragmentColor.a);
}
`;
}
// 셰이더 섞기 함수. (고정 블렌딩으로 안 되는 블렌드 모드에서 그릴 영역 아래와 섞는다, 러스트 판과 같은 글)
// - backdropTexture 는 그리기 직전에 지금 프레임버퍼에서 그릴 영역만 떠 온 것이다. (프레임버퍼와 같은 크기와 형식, 프리멀티플라이드)
// - 공식은 W3C Compositing and Blending Level 1 (https://www.w3.org/TR/compositing-1/, 2024-03-21 후보 권고안) 그대로다.
// 10.1 분리 섞기: multiply = Cb x Cs, overlay = HardLight(Cs, Cb), darken = min, lighten = max, color-dodge, color-burn, hard-light, soft-light (D(Cb) 포함), difference, exclusion.
// 10.2 비분리 섞기: hue, saturation, color, luminosity. (Lum = 0.3 R + 0.59 G + 0.11 B, ClipColor, SetLum, Sat, SetSat)
// 섞은 색은 범위로 자른다. (10 장 "The result of the mixing formula must be clamped")
// - 6 장 일반식대로 Cs' = (1 - αb) x Cs + αb x B(Cb, Cs) 로 섞은 색을 (Cs' x αs, αs) 로 내보내고,
// 그 뒤 source-over 합성 co = cs' + cb x (1 - αs) 는 고정 블렌딩(ONE, ONE_MINUS_SRC_ALPHA)이 한다.
// - blendModeIndex 는 SHADER_BLEND_MODE_INDEX_TABLE 의 번호다. multiply 는 렌더 타겟에 그릴 때만 MULTIPLY_SHADER_BLEND_MODE_INDEX 로 섞는다.
const BLEND_FUNCTION_SOURCE = `uniform highp sampler2D backdropTexture;
uniform int blendModeIndex;
float blendColorDodge(float backdropValue, float sourceValue) {
if (backdropValue == 0.0) {
return 0.0;
}
if (sourceValue == 1.0) {
return 1.0;
}
return min(1.0, backdropValue / (1.0 - sourceValue));
}
float blendColorBurn(float backdropValue, float sourceValue) {
if (backdropValue == 1.0) {
return 1.0;
}
if (sourceValue == 0.0) {
return 0.0;
}
return 1.0 - min(1.0, (1.0 - backdropValue) / sourceValue);
}
float blendHardLight(float backdropValue, float sourceValue) {
if (sourceValue <= 0.5) {
return backdropValue * 2.0 * sourceValue;
}
float screenValue = 2.0 * sourceValue - 1.0;
return backdropValue + screenValue - backdropValue * screenValue;
}
float blendSoftLight(float backdropValue, float sourceValue) {
if (sourceValue <= 0.5) {
return backdropValue - (1.0 - 2.0 * sourceValue) * backdropValue * (1.0 - backdropValue);
}
float darkenedValue = sqrt(backdropValue);
if (backdropValue <= 0.25) {
darkenedValue = ((16.0 * backdropValue - 12.0) * backdropValue + 4.0) * backdropValue;
}
return backdropValue + (2.0 * sourceValue - 1.0) * (darkenedValue - backdropValue);
}
float getLuminosity(vec3 color) {
return 0.3 * color.r + 0.59 * color.g + 0.11 * color.b;
}
vec3 clipColor(vec3 color) {
float luminosity = getLuminosity(color);
float minimumValue = min(min(color.r, color.g), color.b);
float maximumValue = max(max(color.r, color.g), color.b);
vec3 clippedColor = color;
if (minimumValue < 0.0) {
clippedColor = luminosity + (clippedColor - luminosity) * luminosity / (luminosity - minimumValue);
}
if (maximumValue > 1.0) {
clippedColor = luminosity + (clippedColor - luminosity) * (1.0 - luminosity) / (maximumValue - luminosity);
}
return clippedColor;
}
vec3 setLuminosity(vec3 color, float luminosity) {
float luminosityDelta = luminosity - getLuminosity(color);
return clipColor(color + luminosityDelta);
}
float getSaturation(vec3 color) {
return max(max(color.r, color.g), color.b) - min(min(color.r, color.g), color.b);
}
vec3 setSaturation(vec3 color, float saturation) {
float minimumValue = min(min(color.r, color.g), color.b);
float maximumValue = max(max(color.r, color.g), color.b);
if (maximumValue > minimumValue) {
return (color - minimumValue) * saturation / (maximumValue - minimumValue);
}
return vec3(0.0);
}
vec3 blendColors(vec3 backdropColor, vec3 sourceColor) {
if (blendModeIndex == 1) {
return min(backdropColor, sourceColor);
}
if (blendModeIndex == 2) {
return max(backdropColor, sourceColor);
}
if (blendModeIndex == 3) {
return vec3(blendHardLight(sourceColor.r, backdropColor.r), blendHardLight(sourceColor.g, backdropColor.g), blendHardLight(sourceColor.b, backdropColor.b));
}
if (blendModeIndex == 4) {
return vec3(blendColorDodge(backdropColor.r, sourceColor.r), blendColorDodge(backdropColor.g, sourceColor.g), blendColorDodge(backdropColor.b, sourceColor.b));
}
if (blendModeIndex == 5) {
return vec3(blendColorBurn(backdropColor.r, sourceColor.r), blendColorBurn(backdropColor.g, sourceColor.g), blendColorBurn(backdropColor.b, sourceColor.b));
}
if (blendModeIndex == 6) {
return vec3(blendHardLight(backdropColor.r, sourceColor.r), blendHardLight(backdropColor.g, sourceColor.g), blendHardLight(backdropColor.b, sourceColor.b));
}
if (blendModeIndex == 7) {
return vec3(blendSoftLight(backdropColor.r, sourceColor.r), blendSoftLight(backdropColor.g, sourceColor.g), blendSoftLight(backdropColor.b, sourceColor.b));
}
if (blendModeIndex == 8) {
return abs(backdropColor - sourceColor);
}
if (blendModeIndex == 9) {
return backdropColor + sourceColor - 2.0 * backdropColor * sourceColor;
}
if (blendModeIndex == 10) {
return setLuminosity(setSaturation(sourceColor, getSaturation(backdropColor)), getLuminosity(backdropColor));
}
if (blendModeIndex == 11) {
return setLuminosity(setSaturation(backdropColor, getSaturation(sourceColor)), getLuminosity(backdropColor));
}
if (blendModeIndex == 12) {
return setLuminosity(sourceColor, getLuminosity(backdropColor));
}
if (blendModeIndex == 13) {
return setLuminosity(backdropColor, getLuminosity(sourceColor));
}
if (blendModeIndex == 14) {
return backdropColor * sourceColor;
}
return sourceColor;
}
vec4 blendWithBackdrop(vec4 sourceColor) {
vec4 backdropColor = texelFetch(backdropTexture, ivec2(gl_FragCoord.xy), 0);
float sourceAlpha = clamp(sourceColor.a, 0.0, 1.0);
float backdropAlpha = clamp(backdropColor.a, 0.0, 1.0);
vec3 straightSourceColor = vec3(0.0);
if (sourceAlpha > 0.0) {
straightSourceColor = clamp(sourceColor.rgb / sourceAlpha, 0.0, 1.0);
}
vec3 straightBackdropColor = vec3(0.0);
if (backdropAlpha > 0.0) {
straightBackdropColor = clamp(backdropColor.rgb / backdropAlpha, 0.0, 1.0);
}
vec3 mixedColor = clamp(blendColors(straightBackdropColor, straightSourceColor), 0.0, 1.0);
vec3 blendedColor = (1.0 - backdropAlpha) * straightSourceColor + backdropAlpha * mixedColor;
return vec4(blendedColor * sourceAlpha, sourceAlpha);
}
`;
// 셰이더 섞기 프래그먼트 셰이더. (기본 셰이더와 같은 색 셈 뒤 그릴 영역 아래와 섞는다)
const BLEND_FRAGMENTSHADER_SOURCE = `#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
uniform sampler2D mainTexture;
uniform vec4 mainColor;
uniform vec4 tintColor;
uniform float globalAlpha;
uniform float textureLodBias;
out vec4 outputColor;
${BLEND_FUNCTION_SOURCE}
void main() {
vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate, textureLodBias);
vec3 tintedColor = mix(textureColor.rgb, tintColor.rgb * textureColor.a, tintColor.a);
float finalAlpha = textureColor.a * mainColor.a * globalAlpha;
vec3 finalColor = tintedColor * mainColor.rgb * mainColor.a * globalAlpha;
outputColor = blendWithBackdrop(vec4(finalColor, finalAlpha));
}
`;
// 파티클 셰이더 섞기 프래그먼트 셰이더. (파티클 셰이더와 같은 색 셈 뒤 그릴 영역 아래와 섞는다)
const PARTICLE_BLEND_FRAGMENTSHADER_SOURCE = `#version 300 es
precision highp float;
in vec2 fragmentTextureCoordinate;
in vec4 fragmentColor;
uniform sampler2D mainTexture;
uniform float globalAlpha;
uniform float textureLodBias;
out vec4 outputColor;
${BLEND_FUNCTION_SOURCE}
void main() {
vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate, textureLodBias);
float finalAlpha = textureColor.a * fragmentColor.a * globalAlpha;
vec3 finalColor = textureColor.rgb * fragmentColor.rgb * fragmentColor.a * globalAlpha;
outputColor = blendWithBackdrop(vec4(finalColor, finalAlpha));
}
`;
// 셰이더로 섞는 블렌드 모드와 그 번호. (BLEND_FUNCTION_SOURCE 의 blendModeIndex, 0 은 고정 블렌딩)
// - darken, lighten 도 셰이더로 섞는다. blendEquation MIN / MAX 는 계수 없이 min(cs, cb), max(cs, cb) 를 내는데,
// W3C 식을 프리멀티플라이드로 풀면 darken 은 cs + cb - max(cs x αb, cb x αs), lighten 은 cs + cb - min(cs x αb, cb x αs) 라서 소스나 바탕이 반투명이면 같지 않다.
// (불투명한 바탕 cb = 0.2 에 검정을 알파 0.5 로 그리면 W3C darken 은 0.1, MIN 은 0. 흰색을 알파 0.5 로 그리면 W3C lighten 은 0.6, MAX 는 0.5)
const SHADER_BLEND_MODE_INDEX_TABLE = new Map([
["darken", 1],
["lighten", 2],
["overlay", 3],
["color-dodge", 4],
["color-burn", 5],
["hard-light", 6],
["soft-light", 7],
["difference", 8],
["exclusion", 9],
["hue", 10],
["saturation", 11],
["color", 12],
["luminosity", 13],
]);
// multiply 를 셰이더로 섞을 때의 번호. (BLEND_FUNCTION_SOURCE 의 blendModeIndex)
// - multiply 는 고정 블렌딩(DST_COLOR, ONE_MINUS_SRC_ALPHA)이 바탕이 불투명할 때만 W3C 식과 같다. 바탕 알파가 1 보다 작으면 cs x (1 - αb) 항이 빠지고
// 알파가 바탕 알파로 남는다. 기본 프레임버퍼(alpha: false)는 바탕 알파가 늘 1 이라 고정 블렌딩으로 그리고, 렌더 타겟에 그릴 때만 이 번호로 셰이더로 섞는다.
const MULTIPLY_SHADER_BLEND_MODE_INDEX = 14;
// 덧그림 칸을 비우는 색. (투명한 검정)
const TRANSPARENT_CLEAR_VALUE_LIST = new Float32Array([0, 0, 0, 0]);
// 셰이더 섞기로 파티클을 그릴 때 한 번에 그리는 쿼드 수 상한. (서로 겹치지 않는 쿼드끼리 한 번 떠 와 함께 그린다, 겹침을 따질 때 견주는 수)
const SHADER_BLEND_PARTICLE_GROUP_CAPACITY = 32;
const FLOATS_PER_VERTEX = 4;
const PARTICLE_FLOATS_PER_VERTEX = 8; // x, y, u, v, r, g, b, a
const PARTICLE_VERTEX_CAPACITY = 8192;
const BATCH_FLOATS_PER_VERTEX = 14; // x, y, u, v, r, g, b, a, tintR, tintG, tintB, tintA, textureSlot, clipSlot
const GEOMETRY_COMMAND_SPRITE = 0; // 기하 캐시 명령: 스크래치 정점을 묶음에 넣은 것. (지역 정점, 색, 틴트)
const GEOMETRY_COMMAND_TEXT = 1; // 기하 캐시 명령: 글 배치 엔트리를 그린 것. (엔트리, 자리, 색, 정렬)
const GEOMETRY_COPY_LOOP_VERTEX_COUNT = 12; // 기하 캐시가 이 수 이하의 정점은 하나씩, 넘으면 TypedArray.set 으로 옮긴다. (사각형 둘까지)
const BATCH_VERTEX_CAPACITY = 6 * 8192; // 한 묶음의 정점 수 한도, 사각형 8192 개. (러스트 판과 같은 값)
const BATCH_INITIAL_VERTEX_CAPACITY = 6 * 512; // 묶음 배열을 처음 지을 때의 정점 수, 사각형 512 개. (모자라면 한도까지 두 배씩 늘린다)
const BATCH_RETAINED_FLUSH_CAPACITY = 32; // 묶음을 GPU 버퍼에 남겨 두는 프레임당 그리기 차례 수. (넘는 차례는 남기지 않고 늘 올린다)
const BATCH_RETAINED_MERGE_GAP_VERTEX_COUNT = 256; // 남긴 묶음에서 바뀐 범위 사이가 이 정점 수 이하면 한 범위로 합쳐 올린다.
const BATCH_RETAINED_RANGE_LIMIT = 4; // 남긴 묶음 하나를 고쳐 올리는 bufferSubData 수 한도. (넘으면 첫 범위부터 끝 범위까지 한 번에 올린다)
// 스크래치 버텍스 버퍼 용량. (버텍스 수)
const VERTEX_CAPACITY = 4096;
// 라운드 사각형 / 원의 코너 아크 분할 수.
const CORNER_SEGMENT_COUNT = 8;
// 라운드 사각형 경로의 점 수. (코너 4개, 코너마다 분할 수 + 1)
const ROUND_RECT_POSITION_COUNT = 4 * (CORNER_SEGMENT_COUNT + 1);
// 라운드 사각형 경로의 점마다 단위 원의 cos / sin. (우상 → 우하 → 좌하 → 좌상 코너, 각도가 늘 같으므로 처음에 한 번만 구한다)
const ROUND_RECT_COSINE_TABLE = new System.Float64Array(ROUND_RECT_POSITION_COUNT);
const ROUND_RECT_SINE_TABLE = new System.Float64Array(ROUND_RECT_POSITION_COUNT);
const ROUND_RECT_CORNER_START_RADIAN_LIST = [-Math.PI / 2, 0, Math.PI / 2, Math.PI];
for (let cornerIndex = 0; cornerIndex < 4; ++cornerIndex) {
const startRadian = ROUND_RECT_CORNER_START_RADIAN_LIST[cornerIndex];
for (let segmentIndex = 0; segmentIndex <= CORNER_SEGMENT_COUNT; ++segmentIndex) {
const positionIndex = cornerIndex * (CORNER_SEGMENT_COUNT + 1) + segmentIndex;
const radian = startRadian + (Math.PI / 2) * (segmentIndex / CORNER_SEGMENT_COUNT);
ROUND_RECT_COSINE_TABLE[positionIndex] = Math.cos(radian);
ROUND_RECT_SINE_TABLE[positionIndex] = Math.sin(radian);
}
}
// 라운드 사각형 경로 좌표를 적어 두고 고쳐 쓰는 칸. (x, y 차례)
const ROUND_RECT_POSITION_DATA = new System.Float64Array(ROUND_RECT_POSITION_COUNT * 2);
// 텍스트 베이크 스케일 상한. (과도한 확대 굽기 방지)
const MAXIMUM_TEXT_BAKE_SCALE = 8;
const DEFAULT_TEXT_BAKE_SCALE_STEP = 0.25;
// 오른쪽에서 왼쪽으로 쓰는 글자. (히브리, 아랍, 시리아, 타나, 은코, 사마리아, 만다 문자와 표시형, 보조 평면의 오른쪽에서 왼쪽 문자)
const RIGHT_TO_LEFT_CHARACTER_PATTERN = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
// 방향이 강한 글자. (글자 갈래의 문자, 방향 표시 문자 LRM / RLM / ALM)
const STRONG_DIRECTION_CHARACTER_PATTERN = /[\p{L}\u200E\u200F\u061C]/u;
//==============================================================================
// 글의 첫 강한 방향. ("ltr" 또는 "rtl", 글자 갈래 문자와 LRM, RLM, ALM 가운데 처음 것, 없으면 "ltr". setTextDirection("auto") 가 쓴다)
//==============================================================================
/**
* @param { string } text 볼 글. (비었으면 "ltr")
* @returns { string } "ltr" 또는 "rtl".
*/
export function detectTextDirection(text) {
if (!text) {
return "ltr";
}
for (const character of text) {
if (!STRONG_DIRECTION_CHARACTER_PATTERN.test(character)) {
continue;
}
if (character === "\u200E") {
return "ltr";
}
const isRightToLeft = RIGHT_TO_LEFT_CHARACTER_PATTERN.test(character) || character === "\u200F" || character === "\u061C";
return isRightToLeft ? "rtl" : "ltr";
}
return "ltr";
}
//==============================================================================
// 색상 값을 Color 인스턴스로 변환.
// - Color / "#rrggbb(aa)" / "rgb(a)(...)" 지원. 그 외는 흰색.
//==============================================================================
/**
* @param { Color | string } colorValue
* @returns { Color }
*/
function parseColorValue(colorValue) {
if (colorValue instanceof Color) {
return colorValue.clone();
}
if (typeof colorValue === "string") {
// 같은 문자열은 풀어 둔 색을 나눠 쓴다. (Graphic 은 받은 색을 고치지 않는다)
return Color.fromCache(colorValue);
}
return Color.white();
}
//==============================================================================
// 빈 기하 캐시 만들기. (Graphic.drawComponent 가 컴포넌트마다 하나 둔다)
//==============================================================================
/**
* @returns { object } 기하 캐시.
*/
function createGeometryCache() {
return {
key: new GeometryKey(),
isValid: false,
isBroken: false,
isTranslatable: true,
isWorldVertexStale: false,
generation: -1,
matrixA: 0,
matrixB: 0,
matrixC: 0,
matrixD: 0,
matrixE: 0,
matrixF: 0,
globalAlpha: 0,
blendMode: "",
textDirection: "",
isTextBakeScaleMoving: false,
hasTint: false,
tintRed: 0,
tintGreen: 0,
tintBlue: 0,
tintAlpha: 0,
commandList: [],
commandCount: 0,
endFillColor: null,
endStrokeColor: null,
endImageTintColor: null,
endFontString: "",
endTextAlign: "",
endTextBaseline: "",
endTextDirection: "",
};
}
//==============================================================================
// 기하 캐시의 다음 명령 칸 받기. (지난번 칸을 다시 쓴다)
//==============================================================================
/**
* @param { object } geometryCache 명령을 더할 캐시.
* @param { number } commandType GEOMETRY_COMMAND_SPRITE 또는 GEOMETRY_COMMAND_TEXT.
* @returns { object } 명령.
*/
function acquireGeometryCommand(geometryCache, commandType) {
const commandList = geometryCache.commandList;
const commandIndex = geometryCache.commandCount;
let geometryCommand = commandList[commandIndex];
if (geometryCommand === undefined) {
geometryCommand = {
type: commandType,
texture: null,
vertexCount: 0,
localVertexData: null,
linearPositionData: null,
isLinearPositionValid: false,
color: null,
tintColor: null,
entry: null,
positionX: 0,
positionY: 0,
textDirection: "",
textAlign: "",
textBaseline: "",
subAppendList: [],
subAppendCount: 0,
};
commandList.push(geometryCommand);
}
geometryCommand.type = commandType;
geometryCommand.entry = null;
geometryCommand.subAppendCount = 0;
geometryCache.commandCount = commandIndex + 1;
return geometryCommand;
}
//==============================================================================
// 기하 캐시 열쇠. (Component.writeGeometryKey 가 그리기 입력을 적는 곳)
// - add 로 적은 값을 지난번에 적은 값과 차례대로 === 로 견준다. 하나라도 다르거나 수가 다르면 바뀐 것으로 본다.
// - 견주며 바로 덮어 적으므로 프레임마다 배열을 새로 만들지 않는다.
//==============================================================================
/**
* @example <caption>그리기 입력을 적고 바뀌었는지 보기</caption>
* import { GeometryKey } from "./build/vanilla.js";
*
* const geometryKey = new GeometryKey();
* geometryKey.begin();
* geometryKey.add(10);
* geometryKey.add("#ff0000");
* console.log(geometryKey.end());
* geometryKey.begin();
* geometryKey.add(10);
* geometryKey.add("#ff0000");
* console.log(geometryKey.end());
* geometryKey.begin();
* geometryKey.add(12);
* geometryKey.add("#ff0000");
* console.log(geometryKey.end());
*/
export class GeometryKey extends Object {
//==============================================================================
// 멤버 변수 목록.
//==============================================================================
/** @private @type { Array } */ #valueList; // 지난번에 적은 값.
/** @private @type { number } */ #valueCount; // 이번에 적은 값 수.
/** @private @type { boolean } */ #isChanged; // 이번에 적은 값이 지난번과 다른지.
//==============================================================================
// 생성.
//==============================================================================
/**
* @constructor
*/
constructor() {
super();
this.#valueList = [];
this.#valueCount = 0;
this.#isChanged = true;
}
//==============================================================================
// 적기 시작. (Graphic 이 writeGeometryKey 앞에 부른다)
//==============================================================================
begin() {
this.#valueCount = 0;
this.#isChanged = false;
}
//==============================================================================
// 값 하나 적기. (숫자, 문자열, 참거짓, 객체 참조, null)
//==============================================================================
/**
* @param { * } value 그리기가 읽는 값. (객체는 참조로 견주므로, 안의 값이 바뀔 수 있는 Color 같은 것은 칸을 따로 적는다)
*/
add(value) {
const valueIndex = this.#valueCount;
const valueList = this.#valueList;
if (valueIndex >= valueList.length) {
valueList.push(value);
this.#isChanged = true;
}
else if (valueList[valueIndex] !== value) {
valueList[valueIndex] = value;
this.#isChanged = true;
}
this.#valueCount = valueIndex + 1;
}
//==============================================================================
// 적기 끝. (지난번과 같으면 true)
//==============================================================================
/**
* @returns { boolean } 이번에 적은 값이 지난번과 모두 같으면 참. (처음 적은 때는 거짓)
*/
end() {
const valueList = this.#valueList;
if (valueList.length !== this.#valueCount) {
valueList.length = this.#valueCount;
this.#isChanged = true;
}
return !this.#isChanged;
}
}
//==============================================================================
// 그래픽.
// - Canvas 의 WebGL2 렌더링 컨텍스트를 통해 출력하는 렌더러.
// - Canvas2D 시절의 좌표계(좌상 원점, 픽셀 단위)와 상태 모델(변환/알파 스택)을
// 그대로 재현한다. 모든 드로우는 drawVertices() 한 지점으로 수렴한다.
//==============================================================================
/**
* @example <caption>씬의 draw 에서 도형과 글 그리기</caption>
* import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
*
* class MainScene extends Scene {
* draw(graphic) {
* super.draw(graphic);
* graphic.setFillColor("#203040");
* graphic.drawRoundRect(Rect.create(40, 40, 260, 160), 16);
* graphic.setStrokeColor("#ffcc00");
* graphic.drawStrokeCircle(Vector2.create(460, 120), 60, 4);
* graphic.setFillColor("#ffffff");
* graphic.setFontString("24px sans-serif");
* graphic.setTextAlign("center");
* graphic.setTextBaseline("middle");
* graphic.drawFillText("Graphic", 170, 120);
* }
* }
*
* const engineConfiguration = new EngineConfiguration();
* engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
* const engine = new Engine(engineConfiguration);
* engine.run(new MainScene());
*/
export class Graphic extends Object {
//==============================================================================
// 멤버 변수 목록.
//==============================================================================
/** @private @type { HTMLCanvasElement } */ #canvas;
/** @private @type { WebGL2RenderingContext } */ #webGL2RenderingContext;
/** @private @type { boolean } */ #isForceGizmosVisible;
/** @private @type { boolean } */ #isImageSmoothingEnabled;
/** @private @type { boolean } */ #isImageMipmapEnabled;
/** @private @type { number } */ #imageMipmapBias;
/** @private @type { string } */ #imageSmoothingQuality;
/** @private @type { boolean } */ #isContextLost; // WebGL 컨텍스트를 잃은 동안 참. (webglcontextlost 로 세우고 되살려 다시 지은 뒤 내린다, 엔진이 이 동안 그리지 않는다)
/** @private @type { ((event: string) => void) | null } */ #contextEventCallback; // 잃음과 되살림을 알리는 함수. (엔진이 건다, "lost" 와 "restored")
/** @private @type { GpuMemoryTracker | null } */ #gpuMemoryTracker; // GPU 메모리 셈. (텍스처, 렌더버퍼, 버퍼, 켜기 전에는 null 이라 GL 짓기 호출을 가로채지 않는다)
/** @private @type { ShaderProgram } */ #shaderProgram;
/** @private @type { Map<string, ShaderProgram | null> } */ #resolvedShaderProgramTable = new System.Map(); // resolveShaderProgram 이 담아 둔 프로그램. ("묶음\u0000이름" → 프로그램, 실패는 null)
/** @private @type { ShaderProgram | null } */ #shaderProgramOverride; // 드로우에 잠시 바꿔 끼우는 프로그램. (ShaderSprite 등)
/** @private @type { WebGLVertexArrayObject } */ #vertexArray;
/** @private @type { WebGLBuffer } */ #vertexBuffer;
/** @private @type { Float32Array } */ #vertexData;
/** @private @type { WebGLTexture } */ #whiteTexture;
/** @private @type { ShaderProgram | null } */ #particleShaderProgram; // 파티클 배치 전용. (지연 생성)
/** @private @type { WebGLVertexArrayObject | null } */ #particleVertexArray;
/** @private @type { WebGLBuffer | null } */ #particleVertexBuffer;
/** @private @type { Float32Array | null } */ #particleVertexData;
/** @private @type { WebGLTexture | null } */ #softDiscTexture; // 부드러운 원 스프라이트. (지연 생성)
/** @private @type { boolean } */ #isBatchingEnabled; // 같은 텍스처의 연이은 드로우를 한 번에 그릴지.
/** @private @type { ShaderProgram | null } */ #batchShaderProgram; // 묶어 그리기 전용. (지연 생성)
/** @private @type { WebGLVertexArrayObject | null } */ #batchVertexArray;
/** @private @type { WebGLBuffer | null } */ #batchVertexBuffer;
/** @private @type { Float32Array | null } */ #batchVertexData;
/** @private @type { number } */ #batchVertexCount; // 쌓여서 아직 그리지 않은 정점 수.
/** @private @type { boolean } */ #isBatchFlushScheduled; // 이 작업이 끝날 때 남은 묶음을 그리는 마이크로태스크를 걸었는지.
/** @private @type { function(): void } */ #scheduledBatchFlush; // 걸어 둔 마이크로태스크가 부르는 함수.
/** @private @type { (WebGLTexture | null)[] } */ #batchTextureList; // 쌓인 정점이 쓰는 텍스처. (칸 번호 차례)
/** @private @type { number } */ #batchTextureCount; // 쌓인 정점이 쓰는 텍스처 수.
/** @private @type { number } */ #batchTextureSlotCount; // 텍스처 칸 수. (기기의 MAX_TEXTURE_IMAGE_UNITS 와 BATCH_TEXTURE_SLOT_LIMIT 가운데 작은 것)
/** @private @type { Float32Array | null } */ #batchClipRectData; // 자르기 사각형 표. (칸마다 왼쪽, 위, 오른쪽, 아래 디바이스 픽셀)
/** @private @type { number } */ #batchClipRectCount; // 표에 적은 칸 수. (0 번 자르지 않는 칸 포함)
/** @private @type { number } */ #batchGeneration; // 묶음을 그릴 때마다 늘어나는 번호. (자르기 칸 번호가 지금 묶음 것인지 견준다)
/** @private @type { boolean } */ #isShaderClipActive; // 축에 맞는 자르기(셰이더로 자르기)가 걸렸는지.
/** @private @type { Float32Array } */ #shaderClipRect; // 걸린 셰이더 자르기를 모두 겹친 사각형. (디바이스 픽셀, 왼쪽, 위, 오른쪽, 아래)
/** @private @type { number } */ #shaderClipSlot; // 지금 셰이더 자르기의 표 칸 번호. (#shaderClipSlotGeneration 이 지금 묶음이 아니면 다시 적는다)
/** @private @type { number } */ #shaderClipSlotGeneration;
/** @private @type { number } */ #stencilClipDepth; // 스텐실에 적은 자르기 수. (돌아간 자르기, 둥근 자르기)
/** @private @type { boolean } */ #isClipScissorEnabled; // 묶지 않는 그리기에 셰이더 자르기를 가위로 걸어 두었는지.
/** @private @type { number } */ #framebufferSampleState; // 기본 프레임버퍼가 멀티샘플인지. (-1 모름, 0 아님, 1 멀티샘플)
/** @private @type { ImageTextureCache } */ #imageTextureCache;
/** @private @type { TextStringTextureCache } */ #textStringTextureCache;
/** @private @type { TransformMatrix } */ #transformMatrix;
/** @private @type { object[] } */ #stateStack;
/** @private @type { object[] } */ #stateSnapshotPool; // 상태 저장 칸. (스택 깊이마다 하나씩 만들어 두고 고쳐 쓴다)
/** @private @type { number } */ #globalAlpha;
/** @private @type { string } */ #blendMode;
/** @private @type { Map<string, number[]> } */ #blendFunctionTable;
/** @private @type { Set<string> } */ #warnedBlendModes;
/** @private @type { number } */ #shaderBlendModeIndex; // 지금 블렌드 모드의 셰이더 섞기 번호. (0 이면 고정 블렌딩)
/** @private @type { ShaderProgram | null } */ #blendShaderProgram; // 셰이더 섞기 전용. (지연 생성)
/** @private @type { ShaderProgram | null } */ #particleBlendShaderProgram; // 파티클 셰이더 섞기 전용. (지연 생성)
/** @private @type { Map<number, object> } */ #backdropTargetTable; // 그릴 영역 아래를 떠 올 칸. (텍스처 형식 → { texture, framebuffer, width, height })
/** @private @type { Map<WebGLFramebuffer | null, number> } */ #framebufferFormatTable; // 프레임버퍼마다 색 텍스처 형식. (프레임마다 잊는다)
/** @private @type { object | null } */ #layerTarget; // 바꿔 끼운 셰이더로 먼저 그려 둘 칸. ({ texture, framebuffer, width, height }, 지연 생성)
/** @private @type { object[] } */ #opacityLayerStack; // 열린 투명도 층. ({ target, previousFramebuffer, globalAlpha }, beginOpacityLayer 가 쌓는다)
/** @private @type { object[] } */ #opacityLayerTargetPool; // 다 쓴 투명도 층 칸. ({ texture, framebuffer, stencilRenderbuffer, width, height }, 다시 쓴다)
/** @private @type { object } */ #backdropRect; // 떠 올 영역. ({ x, y, width, height } GL 픽셀, 왼쪽 아래 원점, 고쳐 쓴다)
/** @private @type { boolean } */ #isStencilRecording; // 스텐실에 자르기 영역을 적는 중인지. (색을 쓰지 않으므로 섞지 않는다)
/** @private @type { TransformMatrix } */ #identityTransformMatrix; // 덧그림 칸을 옮겨 그릴 때 쓰는 단위 행렬.
/** @private @type { object[] } */ #particleGroupRectList; // 셰이더 섞기로 함께 그릴 파티클 쿼드의 영역. (SHADER_BLEND_PARTICLE_GROUP_CAPACITY 칸, 고쳐 쓴다)
/** @private @type { Color } */ #fillColor;
/** @private @type { Color } */ #strokeColor;
/** @private @type { Color } */ #whiteColor;
/** @private @type { Color | null } */ #imageTintColor;
/** @private @type { string } */ #fontString;
/** @private @type { string } */ #textAlign;
/** @private @type { string } */ #textBaseline;
/** @private @type { string } */ #textDirection;
/** @private @type { object[] } */ #clipStack;
/** @private @type { object[] } */ #clipEntryPool; // 클립 영역 칸. (클립 깊이마다 하나씩 만들어 두고 고쳐 쓴다)
/** @private @type { Float32Array } */ #projectionMatrixArray;
/** @private @type { Float32Array } */ #modelMatrixArray;
/** @private @type { ShaderProgram | null } */ #uniformLocationProgram; // 아래 유니폼 자리를 찾아 둔 셰이더 프로그램.
/** @private @type { WebGLUniformLocation | null } */ #modelMatrixLocation;
/** @private @type { WebGLUniformLocation | null } */ #mainColorLocation;
/** @private @type { WebGLUniformLocation | null } */ #tintColorLocation;
/** @private @type { WebGLUniformLocation | null } */ #globalAlphaLocation;
/** @private @type { boolean } */ #isUploadedUniformKnown; // 기본 프로그램에 마지막으로 올린 틴트와 전역 투명도를 알고 있는지.
/** @private @type { number[] } */ #uploadedTintColorValueList; // 기본 프로그램에 마지막으로 올린 틴트. (r, g, b, a)
/** @private @type { number } */ #uploadedGlobalAlpha; // 기본 프로그램에 마지막으로 올린 전역 투명도.
/** @private @type { number } */ #appliedViewportWidth;
/** @private @type { number } */ #appliedViewportHeight;
/** @private @type { number } */ #textBakeScaleStep; // 텍스트 베이크 스케일 양자화 단위. (0 이면 양자화하지 않음)
/** @private @type { number } */ #textBakeMotionScaleStep; // 배율이 움직이는 노드의 텍스트 베이크 스케일 양자화 단위. (textBakeScaleStep 이 0 일 때만 쓴다)
/** @private @type { boolean } */ #isTextBakeScaleMoving; // 지금 그리는 노드의 배율이 지난 프레임과 달라 움직이는 중인지.
/** @private @type { boolean } */ #isTextPixelSnapEnabled; // 텍스트 쿼드를 디바이스 픽셀 격자에 맞출지.
/** @private @type { number } */ #drawCallCount; // 이번 프레임의 드로우 콜 수.
/** @private @type { number } */ #drawVertexCount; // 이번 프레임에 그린 정점 수.
/** @private @type { number } */ #lastFrameDrawCallCount; // 지난 프레임의 드로우 콜 수.
/** @private @type { number } */ #lastFrameDrawVertexCount; // 지난 프레임에 그린 정점 수.
/** @private @type { boolean } */ #isCullingEnabled; // 화면 밖 노드의 컴포넌트 그리기를 건너뛸지.
/** @private @type { number } */ #culledNodeCount; // 이번 프레임에 화면 밖이라 컴포넌트를 건너뛴 노드 수.
/** @private @type { number } */ #lastFrameCulledNodeCount; // 지난 프레임에 화면 밖이라 컴포넌트를 건너뛴 노드 수.
/** @private @type { number } */ #drawFrameNumber; // 그리기 프레임 번호. (beginFrameStatistics 마다 하나씩 오른다, 노드가 지난 프레임에 그려졌는지 본다)
/** @private @type { boolean } */ #isSubtreeCullingEnabled; // 화면 밖 하위 트리의 그리기 순회를 통째로 건너뛸지. (화면 밖 거르기가 켜졌을 때만, 기본 켜짐)
/** @private @type { number } */ #culledSubtreeCount; // 이번 프레임에 화면 밖이라 그리기를 통째로 건너뛴 하위 트리 수.
/** @private @type { number } */ #lastFrameCulledSubtreeCount; // 지난 프레임에 그 수.
/** @private @type { Float64Array } */ #localVisibleKeyList; // 지역 좌표의 보이는 사각형을 셈한 때의 변환(a, b, c, d, e, f)과 보이는 디바이스 사각형(왼쪽, 위, 오른쪽, 아래). (같으면 다시 셈하지 않는다)
/** @private @type { boolean } */ #isLocalVisibleBoundsKnown; // 지역 좌표의 보이는 사각형을 셈할 수 있었는지. (변환을 거꾸로 걸 수 없으면 거짓)
/** @private @type { number } */ #localVisibleMinimumX; // 지금 변환의 지역 좌표로 옮긴 보이는 사각형의 경계 상자. (화면과 걸린 자르기, 한 디바이스 픽셀 넉넉히)
/** @private @type { number } */ #localVisibleMinimumY;
/** @private @type { number } */ #localVisibleMaximumX;
/** @private @type { number } */ #localVisibleMaximumY;
/** @private @type { boolean } */ #isLocalInnerBoundsKnown; // 지역 좌표의 보이는 사각형 안쪽 사각형을 셈했는지. (변환이 축에 맞을 때만, 돌림이나 기울임이 있으면 거짓)
/** @private @type { number } */ #localInnerMinimumX; // 보이는 사각형을 한 디바이스 픽셀 좁혀 지금 변환의 지역 좌표로 옮긴 사각형. (이 안에 다 든 것은 보이는 사각형 안에 다 든다)
/** @private @type { number } */ #localInnerMinimumY;
/** @private @type { number } */ #localInnerMaximumX;
/** @private @type { number } */ #localInnerMaximumY;
/** @private @type { number } */ #clipStateSerial; // 지금 자르기 상태의 번호. (자르기를 걸면 새 번호, 풀면 걸기 전 번호로 돌아간다, 자르기가 없으면 0)
/** @private @type { number } */ #clipStateSerialCounter; // 자르기를 걸 때마다 하나씩 오르는 수.
/** @private @type { number } */ #insideVisibleClipStateSerial; // 하위 트리가 보이는 사각형 안에 다 든 노드를 그리는 동안 그 때의 자르기 상태 번호. (-1 이면 없음)
/** @private @type { number } */ #insideVisibleViewportWidth; // 그 때의 뷰포트 너비.
/** @private @type { number } */ #insideVisibleViewportHeight; // 그 때의 뷰포트 높이.
/** @private @type { boolean } */ #isGeometryCachingEnabled; // 컴포넌트가 그린 정점을 캐시해 두고 바뀐 것만 다시 셈할지. (기본 켜짐)
/** @private @type { WeakMap<Component, object> } */ #geometryCacheMap; // 컴포넌트마다의 기하 캐시.
/** @private @type { object | null } */ #geometryActiveCache; // 지금 적거나 다시 옮기는 기하 캐시.
/** @private @type { object | null } */ #geometryCaptureTarget; // 묶음에 넣은 정점을 받아 적을 명령. (null 이면 새 명령을 만든다)
/** @private @type { number } */ #geometryVersionCounter; // 캐시 조각의 디바이스 정점을 고쳐 쓸 때마다 올리는 수.
/** @private @type { Array<object> } */ #batchRetainedFlushList; // 프레임 안 그리기 차례마다 GPU 버퍼에 남겨 둔 묶음. (캐시 조각과 바로 쓴 구간의 차례를 적어 둔다)
/** @private @type { object | null } */ #batchRetainedFlush; // 지금 묶음이 채우는 남김 칸. (null 이면 정점을 묶음 배열에 바로 쓰고 남기지 않는다)
/** @private @type { number } */ #batchFlushIndex; // 이번 프레임에 그린 묶음 수. (남김 칸 번호)
/** @private @type { number } */ #batchSegmentCount; // 지금 묶음에 적은 조각 수. (캐시 조각과 바로 쓴 구간)
/** @private @type { number } */ #batchDeferredSegmentCount; // 그 가운데 정점을 묶음 배열에 아직 옮기지 않은 조각 수.
/** @private @type { number[] } */ #batchDirtyRangeList; // 남긴 묶음에서 고쳐 올릴 정점 범위. ([시작, 끝, 시작, 끝, ...], 묶음을 그릴 때마다 다시 쓴다)
/** @private @type { boolean } */ #isBatchSegmentDeferring; // 캐시 조각의 정점을 묶음 배열에 옮기지 않고 미루는지. (지난 프레임 같은 차례가 조각만으로 찼을 때만)
/** @private @type { number } */ #retainedBatchCount; // 이번 프레임에 정점을 올리지 않고 남긴 버퍼로 그린 묶음 수.
/** @private @type { number } */ #lastFrameRetainedBatchCount; // 지난 프레임의 그 수.
/** @private @type { number } */ #geometryCacheGeneration; // 정점 셈을 바꾸는 설정이 바뀔 때마다 늘린다. (다르면 캐시를 다시 적는다)
/** @private @type { number } */ #geometryCacheHitCount; // 이번 프레임에 캐시로 그린 컴포넌트 수.
/** @private @type { number } */ #geometryRebuildCount; // 이번 프레임에 draw 를 불러 다시 셈한 컴포넌트 수. (캐시하는 컴포넌트만)
/** @private @type { number } */ #lastFrameGeometryCacheHitCount; // 지난 프레임에 캐시로 그린 컴포넌트 수.
/** @private @type { number } */ #lastFrameGeometryRebuildCount; // 지난 프레임에 다시 셈한 컴포넌트 수.
/** @private @type { WebGLStateCache } */ #webGLStateCache; // 컨텍스트의 GL 상태 기억. (getParameter, isEnabled 를 GL 에 묻지 않고 답한다, Graphic 은 묶음과 상태를 따로 기억하지 않고 이것에 견준다)
/** @private @type { string } */ #colorSpace; // 3D 색 공간. (ColorSpace, 생성 때 정함, 2D 묶음은 어느 값이든 감마 공간에서 합성한다)
//==============================================================================
// 생성.
//==============================================================================
/**
* @constructor
* @param { HTMLCanvasElement } canvas 그릴 캔버스. (WebGL2 컨텍스트를 얻지 못하면 오류를 던진다)
* @param { boolean } preserveDrawingBuffer 프레임이 끝난 뒤에도 그린 것을 캔버스에 남길지. (true 일 때만 남긴다)
* @param { boolean } [antialias] 캔버스의 멀티샘플 안티에일리어싱을 켤지. (기본 true, false 일 때만 끈다)
* @param { string } [colorSpace] 3D 색 공간. (ColorSpace, 기본 ColorSpace.gamma, 엔진은 EngineConfiguration.colorSpace 를 넘긴다)
* @param { boolean } [trackGpuMemory] GPU 메모리 셈을 처음부터 켤지. (기본 false, 엔진은 EngineConfiguration.trackGpuMemory 를 넘긴다)
*/
constructor(canvas, preserveDrawingBuffer, antialias = true, colorSpace = ColorSpace.gamma, trackGpuMemory = false) {
super();
this.#colorSpace = readColorSpace(colorSpace);
// preserveDrawingBuffer 를 켜면 프레임이 끝난 뒤에도 그린 것이 캔버스에 남는다.
// 캔버스 위에 후처리를 얹는 프로젝트가 그 그림을 읽어 쓴다. (엔진 설정에서 켠다)
// antialias 를 끄면 캔버스의 멀티샘플을 쓰지 않는다. (엔진 설정에서 끈다, 고해상도 모바일에서 리졸브 비용을 아낀다)
const webGL2RenderingContext = canvas.getContext("webgl2", {
alpha: false,
stencil: true,
antialias: antialias !== false,
premultipliedAlpha: true,
preserveDrawingBuffer: preserveDrawingBuffer === true,
}); // WebGL2RenderingContext
if (!webGL2RenderingContext) {
throw new Error("WebGL2 Not Supported.");
}
this.#canvas = canvas;
this.#webGL2RenderingContext = webGL2RenderingContext;
// 그리는 중에 GL 상태를 읽지 않게 컨텍스트의 상태 함수를 가로채 기억한다. (다른 GL 호출보다 먼저 건다)
this.#webGLStateCache = WebGLStateCache.attach(webGL2RenderingContext);
// GPU 메모리 셈. (개발용이라 기본은 꺼 둔다, 켜면 텍스처, 렌더버퍼, 버퍼를 짓고 크기를 정하는 함수를 가로챈다, 엔진 자원을 짓기 전에 걸어야 엔진 자원도 센다)
this.#gpuMemoryTracker = trackGpuMemory === true ? GpuMemoryTracker.attach(webGL2RenderingContext) : null;
this.#isContextLost = false;
this.#contextEventCallback = null;
// 컨텍스트를 잃으면 preventDefault 로 되살림을 받고, 그리기를 멈추고, 기하 캐시와 남긴 묶음을 잊는다. (GL 묶음 기억은 상태 캐시가 스스로 잊는다)
// 되살아나면 엔진이 짓는 기본 자원(셰이더 프로그램, 버텍스 어레이, 흰 텍스처, 묶어 그리기, 파티클, 섞기 프로그램, 그림 텍스처, 글자 아틀라스)을 다시 짓고 그리기를 잇는다.
// 게임이 지은 GL 객체(자기 셰이더 프로그램, 렌더 타겟, 3D 렌더러와 메시)는 잃은 컨텍스트의 객체라 엔진이 다시 짓지 못한다. 엔진이 알리는 "restored" 에서 게임이 다시 짓는다.
const forgetGeometry = () => {
this.#geometryCacheGeneration += 1;
for (const retainedFlush of this.#batchRetainedFlushList) {
retainedFlush.vertexArray = null;
retainedFlush.vertexBuffer = null;
retainedFlush.bufferVertexCount = 0;
retainedFlush.isValid = false;
}
};
canvas.addEventListener("webglcontextlost", (event) => {
event.preventDefault();
this.#isContextLost = true;
this.#batchVertexCount = 0;
this.#batchTextureCount = 0;
this.#isBatchSegmentDeferring = false;
forgetGeometry();
this.notifyContextEvent("lost");
});
canvas.addEventListener("webglcontextrestored", () => {
forgetGeometry();
try {
this.restoreContextResources(webGL2RenderingContext);
}
catch (error) {
console.error(error);
console.error("Graphic: WebGL2 context restored, but the engine failed to rebuild its resources. Drawing stays stopped.");
return;
}
this.#isContextLost = false;
this.notifyContextEvent("restored");
});
this.#isForceGizmosVisible = false;
this.#isImageSmoothingEnabled = true;
this.#isImageMipmapEnabled = false;
this.#imageMipmapBias = 0;
this.#imageSmoothingQuality = "high";
// 셰이더 프로그램, 버텍스 어레이와 버퍼, 흰 텍스처. (컨텍스트를 되살릴 때 같은 길로 다시 짓는다)
this.createCoreResources(webGL2RenderingContext);
const shaderProgram = this.getShaderProgram();
// 파티클 배치 자원. (처음 쓸 때 만든다)
this.#particleShaderProgram = null;
this.#particleVertexArray = null;
this.#particleVertexBuffer = null;
this.#particleVertexData = null;
this.#softDiscTexture = null;
// 묶어 그리기 자원. (켤 때 만든다)
this.#isBatchingEnabled = false;
this.#batchShaderProgram = null;
this.#batchVertexArray = null;
this.#batchVertexBuffer = null;
this.#batchVertexData = null;
this.#batchVertexCount = 0;
this.#isBatchFlushScheduled = false;
this.#scheduledBatchFlush = () => {
this.#isBatchFlushScheduled = false;
this.flushBatch();
};
this.#batchTextureList = [];
this.#batchTextureCount = 0;
this.#batchTextureSlotCount = 1;
this.#batchClipRectData = null;
this.#batchClipRectCount = 1;
this.#batchGeneration = 0;
this.#isShaderClipActive = false;
this.#shaderClipRect = new Float32Array(4);
this.#shaderClipSlot = 0;
this.#shaderClipSlotGeneration = -1;
this.#stencilClipDepth = 0;
this.#isClipScissorEnabled = false;
this.#framebufferSampleState = -1;
// 캐시. (캐시가 텍스처를 묶을 때도 이 Graphic 이 묶은 텍스처를 기억하게 묶는 함수를 넘긴다)
const textureBinder = (texture) => {
this.bindTexture(texture);
};
this.#imageTextureCache = new ImageTextureCache(webGL2RenderingContext, textureBinder);
// 미리 푼 그림 보관소에 이 컨텍스트를 그림 주인으로 알린다. (주인을 모르는 그림을 미리 올릴지 가를 때 주인 수를 센다)
DecodedImageStore.addOwner(webGL2RenderingContext);
// 글리프 아틀라스 장을 비워 덮어쓰기 전에 쌓아 둔 묶음을 먼저 그린다. (묶음에 그 장을 쓰는 글자가 있을 수 있다)
const beforeTextureOverwrite = () => {
this.flushBatch();
};
this.#textStringTextureCache = new TextStringTextureCache(webGL2RenderingContext, textureBinder, beforeTextureOverwrite);
// 상태.
this.#transformMatrix = new TransformMatrix();
this.#stateStack = [];
this.#stateSnapshotPool = [];
this.#globalAlpha = 1.0;
this.#blendMode = "source-over";
this.#warnedBlendModes = new Set();
this.#shaderBlendModeIndex = 0;
this.#blendShaderProgram = null;
this.#particleBlendShaderProgram = null;
this.#backdropTargetTable = new Map();
this.#framebufferFormatTable = new Map();
this.#layerTarget = null;
this.#opacityLayerStack = [];
this.#opacityLayerTargetPool = [];
this.#backdropRect = { x: 0, y: 0, width: 0, height: 0 };
this.#isStencilRecording = false;
this.#identityTransformMatrix = new TransformMatrix();