๐Ÿ“ฆ aquaticcalf / samcan

๐Ÿ“„ webglrenderer.ts ยท 1334 lines
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334import earcut from "earcut"
import type { Color } from "../math/color"
import { Matrix } from "../math/matrix"
import type { Paint } from "../math/paint"
import type { Path } from "../math/path"
import { Rectangle } from "../math/rectangle"
import type { Vector2 } from "../math/vector2"
import type {
    Font,
    ImageAsset,
    Renderer,
    RendererBackend,
    RendererCapabilities,
} from "./renderer"
import { BatchManager, type DrawOperation } from "./batchmanager"
import { RendererError } from "../error/renderererror"

/**
 * Vertex data for path rendering
 */
interface PathVertex {
    x: number
    y: number
}

/**
 * Tessellated path data ready for GPU rendering
 */
interface TessellatedPath {
    vertices: Float32Array
    indices: Uint16Array
    vertexCount: number
    indexCount: number
}

/**
 * WebGL texture wrapper
 */
interface WebGLTexture2D {
    texture: WebGLTexture
    width: number
    height: number
}

/**
 * WebGL renderer implementation
 * Provides hardware-accelerated rendering using WebGL
 */
export class WebGLRenderer implements Renderer {
    private _canvas: HTMLCanvasElement | null = null
    private _gl: WebGLRenderingContext | null = null
    private _isInitialized = false
    private _width = 0
    private _height = 0

    // Shader programs
    private _pathProgram: WebGLProgram | null = null
    private _imageProgram: WebGLProgram | null = null
    private _textProgram: WebGLProgram | null = null

    // Buffers
    private _pathVertexBuffer: WebGLBuffer | null = null
    private _pathIndexBuffer: WebGLBuffer | null = null
    private _imageVertexBuffer: WebGLBuffer | null = null

    // Texture cache
    private _textureCache = new Map<ImageAsset, WebGLTexture2D>()

    // Transform stack
    private _transformStack: Matrix[] = []
    private _currentTransform: Matrix = new Matrix()

    // Opacity stack
    private _opacityStack: number[] = []
    private _currentOpacity = 1.0

    // Batching
    private _batchManager = new BatchManager()
    private _batchingEnabled = true

    readonly backend: RendererBackend = "webgl"

    readonly capabilities: RendererCapabilities = {
        maxTextureSize: 2048, // Will be updated during initialization
        supportsBlendModes: true,
        supportsFilters: false,
        supportsAdvancedPaths: false,
        supportsHardwareAcceleration: true,
    }

    get isInitialized(): boolean {
        return this._isInitialized
    }

    get width(): number {
        return this._width
    }

    get height(): number {
        return this._height
    }

    /**
     * Initialize the renderer with a canvas element
     */
    async initialize(canvas: HTMLCanvasElement): Promise<void> {
        this._canvas = canvas

        // Get WebGL context
        const gl = canvas.getContext("webgl", {
            alpha: true,
            antialias: true,
            premultipliedAlpha: true,
        }) as WebGLRenderingContext | null

        if (!gl) {
            // Try experimental WebGL
            const experimentalGl = canvas.getContext("experimental-webgl", {
                alpha: true,
                antialias: true,
                premultipliedAlpha: true,
            }) as WebGLRenderingContext | null

            if (!experimentalGl) {
                throw RendererError.initFailed(
                    "webgl",
                    "Failed to get WebGL rendering context from canvas. WebGL may not be supported in this environment.",
                )
            }

            this._gl = experimentalGl
        } else {
            this._gl = gl
        }
        this._width = canvas.width
        this._height = canvas.height

        // Update capabilities
        const maxTextureSize = this._gl.getParameter(
            this._gl.MAX_TEXTURE_SIZE,
        ) as number
        ;(this.capabilities as { maxTextureSize: number }).maxTextureSize =
            maxTextureSize

        // Initialize shaders and buffers
        try {
            await this._initializeShaders()
            this._initializeBuffers()
        } catch (error) {
            throw RendererError.initFailed(
                "webgl",
                `Failed to initialize WebGL shaders or buffers: ${error instanceof Error ? error.message : String(error)}`,
                error instanceof Error ? error : undefined,
            )
        }

        // Set up initial GL state
        this._gl.viewport(0, 0, this._width, this._height)
        this._gl.enable(this._gl.BLEND)
        this._gl.blendFunc(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA)

        this._isInitialized = true
    }

    /**
     * Resize the renderer viewport
     */
    resize(width: number, height: number): void {
        if (!this._canvas || !this._gl) {
            throw new Error("Renderer not initialized")
        }

        this._canvas.width = width
        this._canvas.height = height
        this._width = width
        this._height = height

        this._gl.viewport(0, 0, width, height)
    }

    /**
     * Begin a new frame
     */
    beginFrame(): void {
        // Reset transform and opacity stacks
        this._transformStack = []
        this._currentTransform = new Matrix()
        this._opacityStack = []
        this._currentOpacity = 1.0

        // Clear any pending batches from previous frame
        this._batchManager.clear()
    }

    /**
     * End the current frame
     */
    endFrame(): void {
        if (!this._gl) {
            throw new Error("Renderer not initialized")
        }

        // Flush any remaining batched operations
        this._flushBatches()

        // Flush any pending GPU operations
        this._gl.flush()
    }

    /**
     * Clear the canvas with an optional color
     */
    clear(color?: Color): void {
        if (!this._gl) {
            throw new Error("Renderer not initialized")
        }

        const gl = this._gl

        if (color) {
            gl.clearColor(color.r, color.g, color.b, color.a)
        } else {
            gl.clearColor(0, 0, 0, 0)
        }

        gl.clear(gl.COLOR_BUFFER_BIT)
    }

    /**
     * Clear a specific region of the canvas
     */
    clearRegion(region: Rectangle, color?: Color): void {
        if (!this._gl) {
            throw new Error("Renderer not initialized")
        }

        const gl = this._gl

        // Enable scissor test to limit clearing to the region
        gl.enable(gl.SCISSOR_TEST)
        gl.scissor(
            Math.floor(region.x),
            Math.floor(this._height - region.y - region.height),
            Math.ceil(region.width),
            Math.ceil(region.height),
        )

        if (color) {
            gl.clearColor(color.r, color.g, color.b, color.a)
        } else {
            gl.clearColor(0, 0, 0, 0)
        }

        gl.clear(gl.COLOR_BUFFER_BIT)

        // Disable scissor test
        gl.disable(gl.SCISSOR_TEST)
    }

    /**
     * Draw a path with the specified paint
     */
    drawPath(path: Path, paint: Paint): void {
        if (!this._gl || !this._pathProgram) {
            throw new Error("Renderer not initialized")
        }

        if (path.isEmpty()) {
            return
        }

        // If batching is enabled, add to batch queue
        if (this._batchingEnabled && this._batchManager.isEnabled) {
            this._batchManager.addOperation({
                type: "path",
                path,
                paint,
                transform: this._currentTransform.clone(),
                opacity: this._currentOpacity,
            })
            return
        }

        // Otherwise, draw immediately
        this._drawPathImmediate(path, paint)
    }

    /**
     * Draw a path immediately without batching
     */
    private _drawPathImmediate(path: Path, paint: Paint): void {
        if (!this._gl || !this._pathProgram) {
            return
        }

        const gl = this._gl

        // Tessellate the path
        const tessellated = this._tessellatePath(path)

        if (tessellated.indexCount === 0) {
            return
        }

        // Use path shader program
        gl.useProgram(this._pathProgram)

        // Upload vertex data
        gl.bindBuffer(gl.ARRAY_BUFFER, this._pathVertexBuffer)
        gl.bufferData(gl.ARRAY_BUFFER, tessellated.vertices, gl.DYNAMIC_DRAW)

        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._pathIndexBuffer)
        gl.bufferData(
            gl.ELEMENT_ARRAY_BUFFER,
            tessellated.indices,
            gl.DYNAMIC_DRAW,
        )

        // Set up vertex attributes
        const positionLoc = gl.getAttribLocation(
            this._pathProgram,
            "a_position",
        )
        gl.enableVertexAttribArray(positionLoc)
        gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0)

        // Set uniforms
        this._setPathUniforms(paint)

        // Set blend mode
        this._setBlendMode(paint.blendMode)

        // Draw
        gl.drawElements(
            gl.TRIANGLES,
            tessellated.indexCount,
            gl.UNSIGNED_SHORT,
            0,
        )

        // Reset blend mode
        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
    }

    /**
     * Draw a path stroke with the specified paint and width
     * Tessellates the stroke path with proper miter joins and butt caps
     */
    drawStroke(path: Path, paint: Paint, strokeWidth: number): void {
        if (!this._gl || !this._pathProgram) {
            throw new Error("Renderer not initialized")
        }

        if (path.isEmpty() || strokeWidth <= 0) {
            return
        }

        // If batching is enabled, add to batch queue
        if (this._batchingEnabled && this._batchManager.isEnabled) {
            this._batchManager.addOperation({
                type: "stroke",
                path,
                paint,
                transform: this._currentTransform.clone(),
                opacity: this._currentOpacity,
                strokeWidth,
            })
            return
        }

        // Otherwise, draw immediately
        this._drawStrokeImmediate(path, paint, strokeWidth)
    }

    /**
     * Draw a stroke immediately without batching
     */
    private _drawStrokeImmediate(
        path: Path,
        paint: Paint,
        strokeWidth: number,
    ): void {
        if (!this._gl || !this._pathProgram) {
            return
        }

        // For simplicity, we'll tessellate the stroke path
        // In production, use a proper stroke tessellation library
        const strokePath = this._tessellateStroke(path, strokeWidth)

        if (strokePath.indexCount === 0) {
            return
        }

        const gl = this._gl

        // Use path shader program
        gl.useProgram(this._pathProgram)

        // Upload vertex data
        gl.bindBuffer(gl.ARRAY_BUFFER, this._pathVertexBuffer)
        gl.bufferData(gl.ARRAY_BUFFER, strokePath.vertices, gl.DYNAMIC_DRAW)

        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._pathIndexBuffer)
        gl.bufferData(
            gl.ELEMENT_ARRAY_BUFFER,
            strokePath.indices,
            gl.DYNAMIC_DRAW,
        )

        // Set up vertex attributes
        const positionLoc = gl.getAttribLocation(
            this._pathProgram,
            "a_position",
        )
        gl.enableVertexAttribArray(positionLoc)
        gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0)

        // Set uniforms
        this._setPathUniforms(paint)

        // Set blend mode
        this._setBlendMode(paint.blendMode)

        // Draw
        gl.drawElements(
            gl.TRIANGLES,
            strokePath.indexCount,
            gl.UNSIGNED_SHORT,
            0,
        )

        // Reset blend mode
        gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
    }

    /**
     * Draw an image with the specified transformation
     */
    drawImage(image: ImageAsset, transform: Matrix): void {
        if (!this._gl || !this._imageProgram) {
            throw new Error("Renderer not initialized")
        }

        const gl = this._gl

        // Get or create texture
        let texture = this._textureCache.get(image)
        if (!texture) {
            texture = this._createTexture(image)
            this._textureCache.set(image, texture)
        }

        // Use image shader program
        gl.useProgram(this._imageProgram)

        // Create quad vertices with transformation
        const vertices = this._createImageQuad(image, transform)

        // Upload vertex data
        gl.bindBuffer(gl.ARRAY_BUFFER, this._imageVertexBuffer)
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW)

        // Set up vertex attributes
        const positionLoc = gl.getAttribLocation(
            this._imageProgram,
            "a_position",
        )
        const texCoordLoc = gl.getAttribLocation(
            this._imageProgram,
            "a_texCoord",
        )

        gl.enableVertexAttribArray(positionLoc)
        gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 16, 0)

        gl.enableVertexAttribArray(texCoordLoc)
        gl.vertexAttribPointer(texCoordLoc, 2, gl.FLOAT, false, 16, 8)

        // Bind texture
        gl.activeTexture(gl.TEXTURE0)
        gl.bindTexture(gl.TEXTURE_2D, texture.texture)

        // Set uniforms
        this._setImageUniforms()

        // Draw
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
    }

    /**
     * Draw text at the specified position
     */
    drawText(text: string, font: Font, position: Vector2, paint: Paint): void {
        // WebGL text rendering is complex and typically done via texture atlas
        // For now, we'll throw an error indicating it's not implemented
        // In a full implementation, this would render text to a texture and draw that
        throw new Error("Text rendering not yet implemented in WebGL renderer")
    }

    /**
     * Save the current rendering state
     */
    save(): void {
        this._transformStack.push(this._currentTransform.clone())
        this._opacityStack.push(this._currentOpacity)
    }

    /**
     * Restore the previous rendering state
     */
    restore(): void {
        const transform = this._transformStack.pop()
        if (transform) {
            this._currentTransform = transform
        }

        const opacity = this._opacityStack.pop()
        if (opacity !== undefined) {
            this._currentOpacity = opacity
        }
    }

    /**
     * Apply a transformation matrix to the current rendering context
     */
    transform(matrix: Matrix): void {
        // Multiply current transform by the new matrix
        this._currentTransform = this._currentTransform.multiply(matrix)
    }

    /**
     * Set the global opacity for subsequent draw operations
     */
    setOpacity(opacity: number): void {
        this._currentOpacity = Math.max(0, Math.min(1, opacity))
    }

    /**
     * Initialize shader programs
     */
    private async _initializeShaders(): Promise<void> {
        if (!this._gl) {
            throw new Error("WebGL context not available")
        }

        const gl = this._gl

        // Create path shader program
        this._pathProgram = this._createProgram(
            PATH_VERTEX_SHADER,
            PATH_FRAGMENT_SHADER,
        )

        // Create image shader program
        this._imageProgram = this._createProgram(
            IMAGE_VERTEX_SHADER,
            IMAGE_FRAGMENT_SHADER,
        )
    }

    /**
     * Initialize buffers
     */
    private _initializeBuffers(): void {
        if (!this._gl) {
            throw new Error("WebGL context not available")
        }

        const gl = this._gl

        this._pathVertexBuffer = gl.createBuffer()
        this._pathIndexBuffer = gl.createBuffer()
        this._imageVertexBuffer = gl.createBuffer()

        if (
            !this._pathVertexBuffer ||
            !this._pathIndexBuffer ||
            !this._imageVertexBuffer
        ) {
            throw new Error("Failed to create WebGL buffers")
        }
    }

    /**
     * Create a shader program from vertex and fragment shader source
     */
    private _createProgram(
        vertexSource: string,
        fragmentSource: string,
    ): WebGLProgram {
        if (!this._gl) {
            throw new Error("WebGL context not available")
        }

        const gl = this._gl

        const vertexShader = this._compileShader(gl.VERTEX_SHADER, vertexSource)
        const fragmentShader = this._compileShader(
            gl.FRAGMENT_SHADER,
            fragmentSource,
        )

        const program = gl.createProgram()
        if (!program) {
            throw new Error("Failed to create shader program")
        }

        gl.attachShader(program, vertexShader)
        gl.attachShader(program, fragmentShader)
        gl.linkProgram(program)

        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            const info = gl.getProgramInfoLog(program)
            throw new Error(`Failed to link shader program: ${info}`)
        }

        return program
    }

    /**
     * Compile a shader
     */
    private _compileShader(type: number, source: string): WebGLShader {
        if (!this._gl) {
            throw new Error("WebGL context not available")
        }

        const gl = this._gl
        const shader = gl.createShader(type)

        if (!shader) {
            throw new Error("Failed to create shader")
        }

        gl.shaderSource(shader, source)
        gl.compileShader(shader)

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            const info = gl.getShaderInfoLog(shader)
            throw new Error(`Failed to compile shader: ${info}`)
        }

        return shader
    }

    /**
     * Tessellate a path into triangles for GPU rendering
     * Uses earcut library for robust polygon triangulation
     */
    private _tessellatePath(path: Path): TessellatedPath {
        const pathPoints: number[] = []
        let currentX = 0
        let currentY = 0
        let startX = 0
        let startY = 0

        // Convert path commands to flat coordinate array
        for (const cmd of path.commands) {
            switch (cmd.type) {
                case "M":
                    currentX = cmd.x
                    currentY = cmd.y
                    startX = cmd.x
                    startY = cmd.y
                    pathPoints.push(currentX, currentY)
                    break
                case "L":
                    currentX = cmd.x
                    currentY = cmd.y
                    pathPoints.push(currentX, currentY)
                    break
                case "C":
                    // Approximate cubic bezier with line segments
                    // Using 10 segments for smooth curves
                    {
                        const steps = 10
                        const x0 = currentX
                        const y0 = currentY
                        for (let i = 1; i <= steps; i++) {
                            const t = i / steps
                            const mt = 1 - t
                            const mt2 = mt * mt
                            const mt3 = mt2 * mt
                            const t2 = t * t
                            const t3 = t2 * t
                            const x =
                                mt3 * x0 +
                                3 * mt2 * t * cmd.cp1x +
                                3 * mt * t2 * cmd.cp2x +
                                t3 * cmd.x
                            const y =
                                mt3 * y0 +
                                3 * mt2 * t * cmd.cp1y +
                                3 * mt * t2 * cmd.cp2y +
                                t3 * cmd.y
                            pathPoints.push(x, y)
                        }
                        currentX = cmd.x
                        currentY = cmd.y
                    }
                    break
                case "Q":
                    // Approximate quadratic bezier with line segments
                    {
                        const steps = 10
                        const x0 = currentX
                        const y0 = currentY
                        for (let i = 1; i <= steps; i++) {
                            const t = i / steps
                            const mt = 1 - t
                            const x =
                                mt * mt * x0 +
                                2 * mt * t * cmd.cpx +
                                t * t * cmd.x
                            const y =
                                mt * mt * y0 +
                                2 * mt * t * cmd.cpy +
                                t * t * cmd.y
                            pathPoints.push(x, y)
                        }
                        currentX = cmd.x
                        currentY = cmd.y
                    }
                    break
                case "Z":
                    // Close path if not already at start
                    if (
                        Math.abs(currentX - startX) > 0.001 ||
                        Math.abs(currentY - startY) > 0.001
                    ) {
                        pathPoints.push(startX, startY)
                    }
                    currentX = startX
                    currentY = startY
                    break
            }
        }

        // Need at least 3 points (6 coordinates) to form a triangle
        if (pathPoints.length < 6) {
            return {
                vertices: new Float32Array(0),
                indices: new Uint16Array(0),
                vertexCount: 0,
                indexCount: 0,
            }
        }

        // Use earcut to triangulate the polygon
        const indices = earcut(pathPoints)

        return {
            vertices: new Float32Array(pathPoints),
            indices: new Uint16Array(indices),
            vertexCount: pathPoints.length / 2,
            indexCount: indices.length,
        }
    }

    /**
     * Tessellate a stroke path into triangles for GPU rendering
     * Implements proper stroke expansion with miter joins and butt caps
     */
    private _tessellateStroke(
        path: Path,
        strokeWidth: number,
    ): TessellatedPath {
        const halfWidth = strokeWidth / 2
        const pathPoints: { x: number; y: number }[] = []
        let currentX = 0
        let currentY = 0
        let startX = 0
        let startY = 0

        // Extract path points with curve approximation
        for (const cmd of path.commands) {
            switch (cmd.type) {
                case "M":
                    currentX = cmd.x
                    currentY = cmd.y
                    startX = cmd.x
                    startY = cmd.y
                    pathPoints.push({ x: currentX, y: currentY })
                    break
                case "L":
                    currentX = cmd.x
                    currentY = cmd.y
                    pathPoints.push({ x: currentX, y: currentY })
                    break
                case "C":
                    // Approximate cubic bezier
                    {
                        const steps = 10
                        const x0 = currentX
                        const y0 = currentY
                        for (let i = 1; i <= steps; i++) {
                            const t = i / steps
                            const mt = 1 - t
                            const mt2 = mt * mt
                            const mt3 = mt2 * mt
                            const t2 = t * t
                            const t3 = t2 * t
                            const x =
                                mt3 * x0 +
                                3 * mt2 * t * cmd.cp1x +
                                3 * mt * t2 * cmd.cp2x +
                                t3 * cmd.x
                            const y =
                                mt3 * y0 +
                                3 * mt2 * t * cmd.cp1y +
                                3 * mt * t2 * cmd.cp2y +
                                t3 * cmd.y
                            pathPoints.push({ x, y })
                        }
                        currentX = cmd.x
                        currentY = cmd.y
                    }
                    break
                case "Q":
                    // Approximate quadratic bezier
                    {
                        const steps = 10
                        const x0 = currentX
                        const y0 = currentY
                        for (let i = 1; i <= steps; i++) {
                            const t = i / steps
                            const mt = 1 - t
                            const x =
                                mt * mt * x0 +
                                2 * mt * t * cmd.cpx +
                                t * t * cmd.x
                            const y =
                                mt * mt * y0 +
                                2 * mt * t * cmd.cpy +
                                t * t * cmd.y
                            pathPoints.push({ x, y })
                        }
                        currentX = cmd.x
                        currentY = cmd.y
                    }
                    break
                case "Z":
                    // Close path
                    if (
                        pathPoints.length > 0 &&
                        pathPoints[0] &&
                        (Math.abs(currentX - startX) > 0.001 ||
                            Math.abs(currentY - startY) > 0.001)
                    ) {
                        pathPoints.push({ x: startX, y: startY })
                    }
                    currentX = startX
                    currentY = startY
                    break
            }
        }

        if (pathPoints.length < 2) {
            return {
                vertices: new Float32Array(0),
                indices: new Uint16Array(0),
                vertexCount: 0,
                indexCount: 0,
            }
        }

        // Generate stroke geometry with proper joins
        const vertices: number[] = []
        const indices: number[] = []

        for (let i = 0; i < pathPoints.length; i++) {
            const current = pathPoints[i]
            if (!current) continue

            const prev = pathPoints[i - 1]
            const next = pathPoints[i + 1]

            // Calculate tangent vectors
            let tangentX = 0
            let tangentY = 0

            if (i === 0) {
                // First point - use forward direction
                if (next) {
                    tangentX = next.x - current.x
                    tangentY = next.y - current.y
                }
            } else if (i === pathPoints.length - 1) {
                // Last point - use backward direction
                if (prev) {
                    tangentX = current.x - prev.x
                    tangentY = current.y - prev.y
                }
            } else {
                // Middle point - use average of forward and backward directions
                if (prev && next) {
                    const dx1 = current.x - prev.x
                    const dy1 = current.y - prev.y
                    const dx2 = next.x - current.x
                    const dy2 = next.y - current.y

                    // Normalize both directions
                    const len1 = Math.sqrt(dx1 * dx1 + dy1 * dy1)
                    const len2 = Math.sqrt(dx2 * dx2 + dy2 * dy2)

                    if (len1 > 0 && len2 > 0) {
                        tangentX = dx1 / len1 + dx2 / len2
                        tangentY = dy1 / len1 + dy2 / len2
                    }
                }
            }

            // Normalize tangent
            const tangentLen = Math.sqrt(
                tangentX * tangentX + tangentY * tangentY,
            )
            if (tangentLen > 0) {
                tangentX /= tangentLen
                tangentY /= tangentLen
            }

            // Calculate perpendicular (normal) direction
            const normalX = -tangentY
            const normalY = tangentX

            // Add vertices on both sides of the stroke
            const baseIndex = vertices.length / 2

            vertices.push(
                current.x + normalX * halfWidth,
                current.y + normalY * halfWidth,
            )
            vertices.push(
                current.x - normalX * halfWidth,
                current.y - normalY * halfWidth,
            )

            // Create triangles for the stroke segment
            if (i > 0) {
                indices.push(baseIndex - 2, baseIndex - 1, baseIndex)
                indices.push(baseIndex - 1, baseIndex + 1, baseIndex)
            }
        }

        return {
            vertices: new Float32Array(vertices),
            indices: new Uint16Array(indices),
            vertexCount: vertices.length / 2,
            indexCount: indices.length,
        }
    }

    /**
     * Set uniforms for path rendering
     */
    private _setPathUniforms(paint: Paint): void {
        if (!this._gl || !this._pathProgram) {
            return
        }

        const gl = this._gl

        // Projection matrix (orthographic)
        const projectionLoc = gl.getUniformLocation(
            this._pathProgram,
            "u_projection",
        )
        const projection = this._createProjectionMatrix()
        gl.uniformMatrix3fv(projectionLoc, false, projection)

        // Transform matrix
        const transformLoc = gl.getUniformLocation(
            this._pathProgram,
            "u_transform",
        )
        const transform = this._matrixToArray(this._currentTransform)
        gl.uniformMatrix3fv(transformLoc, false, transform)

        // Color
        const colorLoc = gl.getUniformLocation(this._pathProgram, "u_color")
        if (paint.type === "solid" && paint.color) {
            gl.uniform4f(
                colorLoc,
                paint.color.r,
                paint.color.g,
                paint.color.b,
                paint.color.a * this._currentOpacity,
            )
        } else {
            gl.uniform4f(colorLoc, 1, 1, 1, this._currentOpacity)
        }
    }

    /**
     * Set uniforms for image rendering
     */
    private _setImageUniforms(): void {
        if (!this._gl || !this._imageProgram) {
            return
        }

        const gl = this._gl

        // Projection matrix
        const projectionLoc = gl.getUniformLocation(
            this._imageProgram,
            "u_projection",
        )
        const projection = this._createProjectionMatrix()
        gl.uniformMatrix3fv(projectionLoc, false, projection)

        // Texture sampler
        const textureLoc = gl.getUniformLocation(
            this._imageProgram,
            "u_texture",
        )
        gl.uniform1i(textureLoc, 0)

        // Opacity
        const opacityLoc = gl.getUniformLocation(
            this._imageProgram,
            "u_opacity",
        )
        gl.uniform1f(opacityLoc, this._currentOpacity)
    }

    /**
     * Create orthographic projection matrix
     */
    private _createProjectionMatrix(): Float32Array {
        // Orthographic projection for 2D rendering
        const left = 0
        const right = this._width
        const bottom = this._height
        const top = 0

        return new Float32Array([
            2 / (right - left),
            0,
            0,
            0,
            2 / (top - bottom),
            0,
            (right + left) / (left - right),
            (top + bottom) / (bottom - top),
            1,
        ])
    }

    /**
     * Convert Matrix to Float32Array for WebGL
     */
    private _matrixToArray(matrix: Matrix): Float32Array {
        return new Float32Array([
            matrix.a,
            matrix.b,
            0,
            matrix.c,
            matrix.d,
            0,
            matrix.tx,
            matrix.ty,
            1,
        ])
    }

    /**
     * Create a WebGL texture from an image asset
     */
    private _createTexture(image: ImageAsset): WebGLTexture2D {
        if (!this._gl) {
            throw new Error("WebGL context not available")
        }

        const gl = this._gl
        const texture = gl.createTexture()

        if (!texture) {
            throw new Error("Failed to create texture")
        }

        gl.bindTexture(gl.TEXTURE_2D, texture)
        gl.texImage2D(
            gl.TEXTURE_2D,
            0,
            gl.RGBA,
            gl.RGBA,
            gl.UNSIGNED_BYTE,
            image.data,
        )

        // Set texture parameters
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)

        return {
            texture,
            width: image.width,
            height: image.height,
        }
    }

    /**
     * Create vertex data for an image quad
     */
    private _createImageQuad(
        image: ImageAsset,
        transform: Matrix,
    ): Float32Array {
        // Create a quad with position and texture coordinates
        // Format: [x, y, u, v] per vertex
        const w = image.width
        const h = image.height

        // Apply transform to corners
        const corners = [
            this._transformPoint(0, 0, transform),
            this._transformPoint(w, 0, transform),
            this._transformPoint(0, h, transform),
            this._transformPoint(w, h, transform),
        ]

        const c0 = corners[0]
        const c1 = corners[1]
        const c2 = corners[2]
        const c3 = corners[3]

        if (!c0 || !c1 || !c2 || !c3) {
            throw new Error("Failed to transform image corners")
        }

        return new Float32Array([
            c0.x,
            c0.y,
            0,
            0, // Top-left
            c1.x,
            c1.y,
            1,
            0, // Top-right
            c2.x,
            c2.y,
            0,
            1, // Bottom-left
            c3.x,
            c3.y,
            1,
            1, // Bottom-right
        ])
    }

    /**
     * Transform a point by a matrix
     */
    private _transformPoint(
        x: number,
        y: number,
        matrix: Matrix,
    ): { x: number; y: number } {
        return {
            x: matrix.a * x + matrix.c * y + matrix.tx,
            y: matrix.b * x + matrix.d * y + matrix.ty,
        }
    }

    /**
     * Set blend mode
     */
    private _setBlendMode(blendMode: Paint["blendMode"]): void {
        if (!this._gl) {
            return
        }

        const gl = this._gl

        switch (blendMode) {
            case "normal":
                gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
                break
            case "multiply":
                gl.blendFunc(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA)
                break
            case "screen":
                gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR)
                break
            case "lighten":
                gl.blendFunc(gl.SRC_ALPHA, gl.ONE)
                break
            default:
                gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
        }
    }

    /**
     * Get the current viewport bounds in world coordinates
     * For WebGL, this is the canvas dimensions
     */
    getViewportBounds(): Rectangle {
        if (!this._gl) {
            throw new Error("Renderer not initialized")
        }

        // Return the canvas bounds in screen space
        // This assumes the renderer is rendering in screen space coordinates
        return new Rectangle(0, 0, this._width, this._height)
    }

    /**
     * Flush all batched draw operations
     * Groups operations by paint to minimize state changes
     */
    private _flushBatches(): void {
        if (!this._gl) {
            return
        }

        const batches = this._batchManager.flush()

        // Process each batch
        for (const batch of batches) {
            // Process all operations in this batch
            for (const op of batch.operations) {
                // Save current transform and opacity
                const savedTransform = this._currentTransform
                const savedOpacity = this._currentOpacity

                // Set transform and opacity for this operation
                this._currentTransform = op.transform
                this._currentOpacity = op.opacity

                // Draw the operation
                if (op.type === "path") {
                    this._drawPathImmediate(op.path, op.paint)
                } else if (
                    op.type === "stroke" &&
                    op.strokeWidth !== undefined
                ) {
                    this._drawStrokeImmediate(op.path, op.paint, op.strokeWidth)
                }

                // Restore transform and opacity
                this._currentTransform = savedTransform
                this._currentOpacity = savedOpacity
            }
        }
    }

    /**
     * Enable or disable draw call batching
     */
    setBatchingEnabled(enabled: boolean): void {
        this._batchingEnabled = enabled
        this._batchManager.setEnabled(enabled)

        // If disabling, flush any pending batches
        if (!enabled) {
            this._flushBatches()
        }
    }

    /**
     * Check if batching is enabled
     */
    get isBatchingEnabled(): boolean {
        return this._batchingEnabled
    }

    /**
     * Get batching statistics
     */
    getBatchStats(): { batchCount: number; operationCount: number } {
        return {
            batchCount: this._batchManager.batchCount,
            operationCount: this._batchManager.operationCount,
        }
    }
}

// Shader source code

const PATH_VERTEX_SHADER = `
attribute vec2 a_position;

uniform mat3 u_projection;
uniform mat3 u_transform;

void main() {
    vec3 pos = u_projection * u_transform * vec3(a_position, 1.0);
    gl_Position = vec4(pos.xy, 0.0, 1.0);
}
`

const PATH_FRAGMENT_SHADER = `
precision mediump float;

uniform vec4 u_color;

void main() {
    gl_FragColor = u_color;
}
`

const IMAGE_VERTEX_SHADER = `
attribute vec2 a_position;
attribute vec2 a_texCoord;

uniform mat3 u_projection;

varying vec2 v_texCoord;

void main() {
    vec3 pos = u_projection * vec3(a_position, 1.0);
    gl_Position = vec4(pos.xy, 0.0, 1.0);
    v_texCoord = a_texCoord;
}
`

const IMAGE_FRAGMENT_SHADER = `
precision mediump float;

uniform sampler2D u_texture;
uniform float u_opacity;

varying vec2 v_texCoord;

void main() {
    vec4 color = texture2D(u_texture, v_texCoord);
    gl_FragColor = vec4(color.rgb, color.a * u_opacity);
}
`