Line data Source code
1 : export interface SharedGLHandle {
2 : canvas: OffscreenCanvas
3 : gl: WebGL2RenderingContext
4 : release: () => void
5 : }
6 :
7 : interface SharedGL {
8 : canvas: OffscreenCanvas
9 : gl: WebGL2RenderingContext
10 : refs: number
11 : }
12 :
13 2355 : let current: SharedGL | null = null
14 :
15 0 : function loseContext(gl: WebGL2RenderingContext): void {
16 0 : gl.getExtension('WEBGL_lose_context')?.loseContext()
17 : }
18 :
19 14 : function createSharedGL(): SharedGL | null {
20 14 : const canvas = new OffscreenCanvas(1, 1)
21 14 : const gl = canvas.getContext('webgl2', {
22 : alpha: true,
23 : premultipliedAlpha: false,
24 : preserveDrawingBuffer: true
25 : })
26 14 : if (!gl) return null
27 :
28 14 : if (!gl.getExtension('EXT_color_buffer_float')) {
29 0 : loseContext(gl)
30 0 : return null
31 : }
32 :
33 14 : gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
34 14 : return { canvas, gl, refs: 0 }
35 : }
36 :
37 14 : export function acquireSharedGL(): SharedGLHandle | null {
38 14 : if (current?.gl.isContextLost()) current = null
39 :
40 14 : current ??= createSharedGL()
41 14 : if (!current) return null
42 :
43 14 : const entry = current
44 14 : entry.refs++
45 14 : let released = false
46 14 : return {
47 : canvas: entry.canvas,
48 : gl: entry.gl,
49 : release() {
50 0 : if (released) return
51 0 : released = true
52 0 : entry.refs--
53 0 : if (entry.refs > 0) return
54 0 : if (current === entry) current = null
55 0 : loseContext(entry.gl)
56 : }
57 : }
58 : }
|