pixi-silk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # pixi-silk
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#16](https://github.com/schmooky/pixi-silk/pull/16) [`5b6a88d`](https://github.com/schmooky/pixi-silk/commit/5b6a88df440cb281eb4c3249f0c327675e84c014) Thanks [@igaming-bulochka](https://github.com/igaming-bulochka)! - WebGL1 support as an opt-in: `enableWebGL1` from the new `pixi-silk/webgl1` entry point, or `createSilkApp({ webgl1: enableWebGL1 })`. When Pixi falls back to a WebGL1 context, SilkGraphics, SilkText and Glass draw with GLSL ES 1.00 shaders built from the WebGL2 sources. Apps without the import do not ship them. On WebGL1 nothing batches, and paths past 4096 edges draw in part with a warning. Without the opt-in, `createSilkApp` now logs an error on WebGL1 instead of failing to compile the shader. `enableWebGL1` returns `false` with an error on a device without `OES_texture_float`, `OES_texture_half_float`, `OES_standard_derivatives` or fragment `highp`, where the shaders cannot run. Without `OES_texture_half_float_linear` the gradient ramps filter nearest and the shaders blend them, so gradients look the same. The renderers guide lists the costs and limits of WebGL1.
8
+
3
9
  ## 1.1.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -45,6 +45,7 @@ imports.
45
45
  | `pixi-silk/layout`, `pixi-silk/ui/layout` | A flex layout engine and the Pixi containers built on it |
46
46
  | `pixi-silk/glass`, `pixi-silk/glow` | Glass and glow filters |
47
47
  | `pixi-silk/webgpu` | The WGSL shader, for WebGPU in your own Pixi app |
48
+ | `pixi-silk/webgl1` | Opt-in shaders for Pixi's WebGL1 fallback |
48
49
  | `pixi-silk/ui/*` | Buttons, radial menus, counters and the editor kit |
49
50
 
50
51
  [Choose an entry point](https://pixi-silk.schmooky.dev/docs/choose-an-entry-point/) lists every
@@ -57,6 +58,7 @@ may change in a minor release.
57
58
  - WebGL2 or WebGPU. WebGL2 is the default. For WebGPU, pass `preference: 'webgpu'` to
58
59
  `createSilkApp`, or call `enableWebGPU()` from `pixi-silk/webgpu` before the first
59
60
  `SilkGraphics` in your own Pixi app
61
+ - WebGL1 is opt-in: pass `webgl1: enableWebGL1` from `pixi-silk/webgl1` to `createSilkApp`
60
62
 
61
63
  It does not do texture fills or SVG documents. The [FAQ](https://pixi-silk.schmooky.dev/faq/) lists the other limits.
62
64
 
@@ -166,7 +166,8 @@ export declare class SilkGeometry extends Geometry {
166
166
  * object is one instanced draw call, and `enableSilkBatching()` merges neighbours further.
167
167
  *
168
168
  * It renders on WebGL2. For WebGPU, call `enableWebGPU()` from `pixi-silk/webgpu` before the first
169
- * SilkGraphics, or create the app with `createSilkApp({ preference: 'webgpu' })`.
169
+ * SilkGraphics, or create the app with `createSilkApp({ preference: 'webgpu' })`. For Pixi's WebGL1
170
+ * fallback, use `enableWebGL1()` from `pixi-silk/webgl1`.
170
171
  *
171
172
  * Shapes go on the active path and are painted by {@link SilkGraphics.fill | fill()} or
172
173
  * {@link SilkGraphics.stroke | stroke()}. `stroke()` right after `fill()` paints the same shapes.
@@ -6,6 +6,7 @@ import { Gradient } from "./gradient.js";
6
6
  import { joinPolygon, nearWindows } from "./stroke.js";
7
7
  import { hitTest } from "./hit.js";
8
8
  import { drawPath, parseSvgPath } from "./path.js";
9
+ import { silkGl1 } from "./shader-slot.js";
9
10
  import { createSilkShader } from "./shader.js";
10
11
  import { Bounds, Buffer, BufferImageSource, BufferUsage, Color, Geometry, Mesh } from "pixi.js";
11
12
  //#region src/SilkGraphics.ts
@@ -322,7 +323,8 @@ var SilkGeometry = class extends Geometry {
322
323
  * object is one instanced draw call, and `enableSilkBatching()` merges neighbours further.
323
324
  *
324
325
  * It renders on WebGL2. For WebGPU, call `enableWebGPU()` from `pixi-silk/webgpu` before the first
325
- * SilkGraphics, or create the app with `createSilkApp({ preference: 'webgpu' })`.
326
+ * SilkGraphics, or create the app with `createSilkApp({ preference: 'webgpu' })`. For Pixi's WebGL1
327
+ * fallback, use `enableWebGL1()` from `pixi-silk/webgl1`.
326
328
  *
327
329
  * Shapes go on the active path and are painted by {@link SilkGraphics.fill | fill()} or
328
330
  * {@link SilkGraphics.stroke | stroke()}. `stroke()` right after `fill()` paints the same shapes.
@@ -404,6 +406,7 @@ var SilkGraphics = class SilkGraphics extends Mesh {
404
406
  });
405
407
  this.renderPipeId = options.batch === false ? "mesh" : SilkGraphics._pipeId;
406
408
  this._polySource = polys;
409
+ if (shader.resources.uInstances) silkGl1.hooks?.attach(geometry);
407
410
  this._f = geometry.instanceBuffer.data;
408
411
  this._uniforms = shader.resources.silkUniforms;
409
412
  this._silk = this._uniforms.uniforms.uSilk;
@@ -1100,6 +1103,7 @@ var SilkGraphics = class SilkGraphics extends Mesh {
1100
1103
  const shader = this.shader;
1101
1104
  super.destroy(options);
1102
1105
  geometry.destroy(true);
1106
+ if (shader) silkGl1.hooks?.release(shader);
1103
1107
  shader?.destroy();
1104
1108
  this._polySource.destroy();
1105
1109
  }
@@ -1154,6 +1158,7 @@ var SilkGraphics = class SilkGraphics extends Mesh {
1154
1158
  }
1155
1159
  src.update();
1156
1160
  }
1161
+ if (this.shader?.resources.uInstances) silkGl1.hooks?.commit(geometry, this.shader, this._f, this._count);
1157
1162
  }
1158
1163
  /** Appends the edges of every subpath of a filled path (each closed). Returns the first texel. */
1159
1164
  _pushEdges(subpaths) {
package/dist/app.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Application, ApplicationOptions } from "pixi.js";
1
+ import { Application, ApplicationOptions, Renderer } from "pixi.js";
2
2
  //#region src/app.d.ts
3
3
  /** Options of {@link createSilkApp}: Pixi application options plus the element to fill, DPR limits and touch behaviour. */
4
4
  export interface SilkAppOptions extends Partial<ApplicationOptions> {
@@ -29,6 +29,13 @@ export interface SilkAppOptions extends Partial<ApplicationOptions> {
29
29
  * the WGSL shader from `pixi-silk/webgpu` before it resolves, so SilkGraphics render on either.
30
30
  */
31
31
  preference?: ApplicationOptions["preference"];
32
+ /**
33
+ * Opt-in WebGL1 support: pass `enableWebGL1` from `pixi-silk/webgl1`. Pixi falls back to a
34
+ * WebGL1 context when the browser has no WebGL2, and the app then calls this function before
35
+ * it resolves. Without it, silk shapes draw nothing on WebGL1 and the app logs an error. The
36
+ * option takes the function rather than a flag, so apps that leave it out do not ship the code.
37
+ */
38
+ webgl1?: (renderer: Renderer) => unknown;
32
39
  }
33
40
  /** What {@link createSilkApp} returns: the Pixi application, its CSS size and resolution, and helpers to change or destroy it. */
34
41
  export interface SilkApp {
package/dist/app.js CHANGED
@@ -19,7 +19,7 @@ import { Application, Filter } from "pixi.js";
19
19
  * ```
20
20
  */
21
21
  async function createSilkApp(options) {
22
- const { parent, maxResolution = 3, fixedResolution, onResize, inheritFilterResolution = true, touchAction = "pan-y pinch-zoom", ...rest } = options;
22
+ const { parent, maxResolution = 3, fixedResolution, onResize, inheritFilterResolution = true, touchAction = "pan-y pinch-zoom", webgl1, ...rest } = options;
23
23
  if (inheritFilterResolution) Filter.defaultOptions.resolution = "inherit";
24
24
  let forced = fixedResolution ?? null;
25
25
  const dpr = () => Math.min(forced ?? window.devicePixelRatio ?? 1, forced ? 16 : maxResolution);
@@ -50,6 +50,10 @@ async function createSilkApp(options) {
50
50
  });
51
51
  }
52
52
  if (app.renderer.name === "webgpu") (await import("./webgpu.js")).enableWebGPU();
53
+ else if (app.renderer.context.webGLVersion === 1) {
54
+ if (webgl1) webgl1(app.renderer);
55
+ else console.error("pixi-silk: Pixi started WebGL1. Pass { webgl1: enableWebGL1 } from 'pixi-silk/webgl1' to draw on it.");
56
+ }
53
57
  const canvas = app.canvas;
54
58
  canvas.style.touchAction = touchAction;
55
59
  canvas.style.display = "block";
package/dist/batch.d.ts CHANGED
@@ -21,7 +21,8 @@ export declare class SilkPipe implements RenderPipe<SilkGraphics> {
21
21
  constructor(renderer: Renderer);
22
22
  /**
23
23
  * Whether this renderer batches. WebGPU needs the WGSL program (`enableWebGPU()`), or the batch
24
- * would have no program to draw with: without it, objects go to the mesh pipe as before.
24
+ * would have no program to draw with: without it, objects go to the mesh pipe as before. The
25
+ * WebGL1 program (`enableWebGL1()`) cannot batch, so WebGL draws one call per object then.
25
26
  */
26
27
  private get _batching();
27
28
  /** Adds `g` to the current run when it can share its draw, or starts a new run. */
package/dist/batch.js CHANGED
@@ -1,4 +1,4 @@
1
- import { silkGpu } from "./shader-slot.js";
1
+ import { silkGl1, silkGpu } from "./shader-slot.js";
2
2
  import { createSilkShader } from "./shader.js";
3
3
  import { SilkGeometry, SilkGraphics } from "./SilkGraphics.js";
4
4
  import { BindGroup, BufferImageSource, ExtensionType, Matrix, RendererType, State, UniformGroup } from "pixi.js";
@@ -165,10 +165,11 @@ var SilkPipe = class {
165
165
  }
166
166
  /**
167
167
  * Whether this renderer batches. WebGPU needs the WGSL program (`enableWebGPU()`), or the batch
168
- * would have no program to draw with: without it, objects go to the mesh pipe as before.
168
+ * would have no program to draw with: without it, objects go to the mesh pipe as before. The
169
+ * WebGL1 program (`enableWebGL1()`) cannot batch, so WebGL draws one call per object then.
169
170
  */
170
171
  get _batching() {
171
- return this._renderer.type === RendererType.WEBGL || silkGpu.program !== null;
172
+ return this._renderer.type === RendererType.WEBGL ? silkGl1.hooks === null : silkGpu.program !== null;
172
173
  }
173
174
  /** Adds `g` to the current run when it can share its draw, or starts a new run. */
174
175
  addRenderable(g, set) {
@@ -1,3 +1,4 @@
1
+ import { silkGl1 } from "../shader-slot.js";
1
2
  import { glassWgsl } from "./glass-wgsl.js";
2
3
  import { Filter, GlProgram, GpuProgram, Texture, UniformGroup } from "pixi.js";
3
4
  //#region src/glass/GlassFilter.ts
@@ -210,7 +211,7 @@ var GlassFilter = class extends Filter {
210
211
  }
211
212
  });
212
213
  super({
213
- glProgram: program,
214
+ glProgram: silkGl1.hooks?.program("silk-glass", glassVertex, glassFragment) ?? program,
214
215
  gpuProgram,
215
216
  resources: {
216
217
  glassUniforms: u,
@@ -5,5 +5,7 @@
5
5
  * `createSilkShader` reads the slot when a SilkGraphics is created.
6
6
  */
7
7
  const silkGpu = { program: null };
8
+ /** @internal Set by `enableWebGL1()` from `pixi-silk/webgl1`. */
9
+ const silkGl1 = { hooks: null };
8
10
  //#endregion
9
- export { silkGpu };
11
+ export { silkGl1, silkGpu };
package/dist/shader.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { GradientAtlas } from "./atlas.js";
2
- import { silkGpu } from "./shader-slot.js";
2
+ import { silkGl1, silkGpu } from "./shader-slot.js";
3
3
  import { BufferImageSource, GlProgram, Shader, UniformGroup } from "pixi.js";
4
4
  //#region src/shader.ts
5
5
  /** @internal Vertex stage of the uber program (GLSL ES 3.00). */
@@ -911,6 +911,7 @@ function emptyBatchTable() {
911
911
  * batched draw: 3 texels per object (matrix a b c d, then tx ty and path texel base, then tint).
912
912
  */
913
913
  function createSilkShader(settings, polys, batch = emptyBatchTable()) {
914
+ const gl1 = silkGl1.hooks;
914
915
  program ??= GlProgram.from({
915
916
  vertex,
916
917
  fragment,
@@ -919,9 +920,10 @@ function createSilkShader(settings, polys, batch = emptyBatchTable()) {
919
920
  preferredFragmentPrecision: "highp"
920
921
  });
921
922
  return new Shader({
922
- glProgram: program,
923
+ glProgram: gl1 ? gl1.program("silk-sdf", vertex, fragment) : program,
923
924
  gpuProgram: silkGpu.program ?? void 0,
924
925
  resources: {
926
+ ...gl1?.resources("silk-sdf"),
925
927
  uGradients: GradientAtlas.shared.source,
926
928
  uPolys: polys,
927
929
  uBatch: batch,
@@ -1,3 +1,4 @@
1
+ import { silkGl1 } from "../shader-slot.js";
1
2
  import { sdfFromAlpha } from "./edt.js";
2
3
  import { BufferImageSource, DOMAdapter } from "pixi.js";
3
4
  //#region src/text/atlas.ts
@@ -138,6 +139,7 @@ var SdfAtlas = class SdfAtlas {
138
139
  shader.resources.uAtlasSampler = this._source.style;
139
140
  shader.resources.uColorAtlas = this._cSource;
140
141
  shader.resources.uColorSampler = this._cSource.style;
142
+ silkGl1.hooks?.syncSizes(shader);
141
143
  }
142
144
  /** @internal Stops updating a shader passed to {@link SdfAtlas.track}. */
143
145
  untrack(shader) {
@@ -224,6 +226,7 @@ var SdfAtlas = class SdfAtlas {
224
226
  for (const shader of this._shaders) {
225
227
  shader.resources.uColorAtlas = this._cSource;
226
228
  shader.resources.uColorSampler = this._cSource.style;
229
+ silkGl1.hooks?.syncSizes(shader);
227
230
  }
228
231
  setTimeout(() => old.destroy(), 0);
229
232
  } else this._cSource.update();
@@ -236,6 +239,7 @@ var SdfAtlas = class SdfAtlas {
236
239
  for (const shader of this._shaders) {
237
240
  shader.resources.uAtlas = this._source;
238
241
  shader.resources.uAtlasSampler = this._source.style;
242
+ silkGl1.hooks?.syncSizes(shader);
239
243
  }
240
244
  setTimeout(() => old.destroy(), 0);
241
245
  return;
@@ -1,4 +1,5 @@
1
1
  import { GradientAtlas } from "../atlas.js";
2
+ import { silkGl1 } from "../shader-slot.js";
2
3
  import { GlProgram, GpuProgram, Shader, UniformGroup } from "pixi.js";
3
4
  //#region src/text/shader.ts
4
5
  /** @internal Vertex stage (GLSL ES 3.00). */
@@ -349,15 +350,17 @@ function createTextShader(atlas, colors = atlas) {
349
350
  entryPoint: "mainFragment"
350
351
  }
351
352
  });
353
+ const gl1 = silkGl1.hooks;
352
354
  const gradients = GradientAtlas.shared.source;
353
355
  const v4 = () => ({
354
356
  value: /* @__PURE__ */ new Float32Array(4),
355
357
  type: "vec4<f32>"
356
358
  });
357
- return new Shader({
358
- glProgram,
359
+ const shader = new Shader({
360
+ glProgram: gl1 ? gl1.program("silk-text", textVertex, textFragment) : glProgram,
359
361
  gpuProgram,
360
362
  resources: {
363
+ ...gl1?.resources("silk-text"),
361
364
  textUniforms: new UniformGroup({
362
365
  uFill: v4(),
363
366
  uOutline: v4(),
@@ -375,6 +378,8 @@ function createTextShader(atlas, colors = atlas) {
375
378
  uColorSampler: colors.style
376
379
  }
377
380
  });
381
+ gl1?.syncSizes(shader);
382
+ return shader;
378
383
  }
379
384
  //#endregion
380
385
  export { createTextShader, textFragment, textVertex, textWgsl };
@@ -0,0 +1,123 @@
1
+ //#region src/webgl1/glsl100.ts
2
+ /**
3
+ * @internal Replaces every call `name(...)` with `fn(args)`. Arguments are split at the commas of
4
+ * the call itself, so nested calls and constructors stay whole.
5
+ */
6
+ function rewriteCalls(src, name, fn) {
7
+ const re = new RegExp(`\\b${name}\\(`, "g");
8
+ let out = "";
9
+ let at = 0;
10
+ for (let m = re.exec(src); m !== null; m = re.exec(src)) {
11
+ const args = [];
12
+ let depth = 1;
13
+ let start = m.index + m[0].length;
14
+ let j = start;
15
+ for (; j < src.length && depth > 0; j++) {
16
+ const c = src[j];
17
+ if (c === "(") depth++;
18
+ else if (c === ")") {
19
+ depth--;
20
+ if (depth === 0) args.push(src.slice(start, j).trim());
21
+ } else if (c === "," && depth === 1) {
22
+ args.push(src.slice(start, j).trim());
23
+ start = j + 1;
24
+ }
25
+ }
26
+ if (depth !== 0) throw new Error(`pixi-silk/webgl1: unclosed call to ${name}`);
27
+ out += src.slice(at, m.index) + fn(args);
28
+ at = j;
29
+ re.lastIndex = j;
30
+ }
31
+ return out + src.slice(at);
32
+ }
33
+ /**
34
+ * @internal The build's shader minifier (`build/glsl.ts`): no comments, no indentation, one
35
+ * statement per line as written. The published sources come out of it, the sources in a test or a
36
+ * dev server do not, so the conversion runs both through it and patches never see the difference.
37
+ */
38
+ function normalizeGlsl(source) {
39
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/[^\n]*/g, "").split("\n").map((line) => line.trim().replace(/\s+/g, " ")).filter(Boolean).join("\n");
40
+ }
41
+ function applyPatch(src, patch) {
42
+ const replace = patch.replace;
43
+ const find = typeof patch.find === "string" ? normalizeGlsl(patch.find) : patch.find;
44
+ if (!(typeof find === "string" ? src.includes(find) : src.search(find) >= 0)) throw new Error(`pixi-silk/webgl1: shader patch no longer matches: ${String(find).slice(0, 80)}`);
45
+ if (typeof find === "string") return src.split(find).join(replace);
46
+ if (find.global) find.lastIndex = 0;
47
+ return src.replace(find, replace);
48
+ }
49
+ const isConstant = (s) => /^-?\d+$/.test(s.trim());
50
+ /** @internal Rewrites a GLSL ES 3.00 stage as GLSL ES 1.00. Throws when something is left that 1.00 lacks. */
51
+ function toGlsl100(src, stage, options = {}) {
52
+ src = normalizeGlsl(src);
53
+ for (const patch of options.patches ?? []) src = applyPatch(src, patch);
54
+ src = src.replace(/^#version 300 es\n/, "");
55
+ src = src.replace(/\((\w+) >> (\d+)\) & (\d+)/g, (_, v, s, m) => `bitsAt(${v}, ${2 ** Number(s)}.0, ${Number(m) + 1}.0)`);
56
+ src = src.replace(/\((\w+) & (\d+)\) (!=|==) 0/g, (_, v, b, op) => `${op === "==" ? "!" : ""}bitSet(${v}, ${b}.0)`);
57
+ src = src.replace(/\(((?:[^()]|\([^()]*\))*)\) % (\w+)/g, (_, a, b) => `imod(${a}, ${b})`);
58
+ src = src.replace(/(\w+) % (\w+)/g, (_, a, b) => `imod(${a}, ${b})`);
59
+ const caps = options.caps ?? {};
60
+ const used = /* @__PURE__ */ new Set();
61
+ src = src.replace(/for \(int (\w+) = ([^;]+); \1 < ([^;]+); \1\+\+\)(\s*)\{/g, (all, v, from, to, ws) => {
62
+ if (isConstant(from) && isConstant(to)) return all;
63
+ const cap = caps[to.trim()];
64
+ if (cap === void 0) throw new Error(`pixi-silk/webgl1: loop bound '${to}' has no cap`);
65
+ used.add(to.trim());
66
+ const i = `${v}_gl1`;
67
+ const inner = ws;
68
+ return `for (int ${i} = 0; ${i} < ${cap}; ${i}++)${ws}{${inner}int ${v} = ${from} + ${i};${inner}if (${v} >= ${to}) break;`;
69
+ });
70
+ for (const key of Object.keys(caps)) if (!used.has(key)) throw new Error(`pixi-silk/webgl1: cap for loop bound '${key}' matches no loop`);
71
+ src = src.replace(/\bflat /g, "");
72
+ if (stage === "vertex") src = src.replace(/^in /gm, "attribute ").replace(/^out /gm, "varying ");
73
+ else {
74
+ src = src.replace(/^in /gm, "varying ").replace(/^out vec4 finalColor;\n/m, "");
75
+ src = src.replace(/\bfinalColor\b/g, "gl_FragColor");
76
+ }
77
+ const sized = /* @__PURE__ */ new Set();
78
+ src = rewriteCalls(src, "textureLod", ([s, uv, lod]) => {
79
+ if (lod !== "0.0") throw new Error("pixi-silk/webgl1: textureLod with a level other than 0");
80
+ return `texture2D(${s}, ${uv})`;
81
+ });
82
+ src = rewriteCalls(src, "texelFetch", ([s, c]) => {
83
+ sized.add(s);
84
+ return `texel_${s}(${c})`;
85
+ });
86
+ src = rewriteCalls(src, "textureSize", ([s]) => {
87
+ sized.add(s);
88
+ return `ivec2(${s}Size)`;
89
+ });
90
+ src = src.replace(/\btexture\(/g, "texture2D(");
91
+ const helpers = [];
92
+ for (const s of sized) {
93
+ helpers.push(`uniform vec2 ${s}Size;`);
94
+ if (src.includes(`texel_${s}(`)) helpers.push(`vec4 texel_${s}(ivec2 c) { return texture2D(${s}, (vec2(c) + 0.5) / ${s}Size); }`);
95
+ }
96
+ if (src.includes("bitSet(")) helpers.push("bool bitSet(int f, float b) { return mod(floor(float(f) / b), 2.0) >= 1.0; }");
97
+ if (src.includes("bitsAt(")) helpers.push("int bitsAt(int f, float s, float m) { return int(mod(floor(float(f) / s), m)); }");
98
+ if (src.includes("imin(")) helpers.push("int imin(int a, int b) { return a < b ? a : b; }");
99
+ if (src.includes("imax(")) helpers.push("int imax(int a, int b) { return a > b ? a : b; }");
100
+ if (src.includes("imod(")) helpers.push("int imod(int a, int b) { int q = int(floor((float(a) + 0.5) / float(b))); return a - q * b; }");
101
+ if (helpers.length > 0) {
102
+ const lines = src.split("\n");
103
+ let last = -1;
104
+ lines.forEach((line, i) => {
105
+ if (/^uniform /.test(line)) last = i;
106
+ });
107
+ if (last < 0) throw new Error("pixi-silk/webgl1: no uniform to place the helpers after");
108
+ lines.splice(last + 1, 0, "", ...helpers);
109
+ src = lines.join("\n");
110
+ }
111
+ if (stage === "fragment" && /\b(dFdx|dFdy|fwidth)\(/.test(src)) {
112
+ src = src.replace(/^precision highp float;\n/m, "");
113
+ src = `precision highp float;\n#extension GL_OES_standard_derivatives : enable\n${src}`;
114
+ }
115
+ const left = src.match(/#version|\btexelFetch\(|\btextureSize\(|\btextureLod\(|\bflat\b|\s%\s|>>|<<|(?<!&)&(?!&)|^(in|out) /m);
116
+ if (left) throw new Error(`pixi-silk/webgl1: '${left[0].trim()}' has no GLSL ES 1.00 rewrite`);
117
+ return {
118
+ source: src,
119
+ sized: [...sized]
120
+ };
121
+ }
122
+ //#endregion
123
+ export { normalizeGlsl, rewriteCalls, toGlsl100 };
@@ -0,0 +1,137 @@
1
+ import { INSTANCE_ATTRIBUTES, Prim } from "../constants.js";
2
+ import { silkGpu } from "../shader-slot.js";
3
+ import { GL1_MAX_EDGES, GL1_VERTEX_ATTRIBUTES, INSTANCE_TEXTURE_WIDTH, gl1Sources } from "./programs.js";
4
+ import { Buffer, BufferImageSource, BufferUsage, GlProgram, UniformGroup } from "pixi.js";
5
+ //#region src/webgl1/hooks.ts
6
+ const SHAPE0 = 4;
7
+ const META = 16;
8
+ function dataTexture(label) {
9
+ return new BufferImageSource({
10
+ resource: new Float32Array(INSTANCE_TEXTURE_WIDTH * 4),
11
+ width: INSTANCE_TEXTURE_WIDTH,
12
+ height: 1,
13
+ format: "rgba32float",
14
+ alphaMode: "premultiplied-alpha",
15
+ scaleMode: "nearest",
16
+ autoGenerateMipmaps: false,
17
+ label
18
+ });
19
+ }
20
+ function ascending(n) {
21
+ const a = new Float32Array(n);
22
+ for (let i = 0; i < n; i++) a[i] = i;
23
+ return a;
24
+ }
25
+ /** @internal Shapes past the WebGL1 loop caps, reported once per page. */
26
+ const warned = { caps: false };
27
+ /** @internal Warns once when an instance needs more loop iterations than the WebGL1 shader runs. */
28
+ function checkCaps(data, count) {
29
+ if (warned.caps) return;
30
+ for (let i = 0; i < count; i++) {
31
+ const o = i * 44;
32
+ const type = data[o + META];
33
+ const a = data[o + SHAPE0 + 1];
34
+ if ((type === Prim.Poly || type === Prim.Union) && a > 4096 || type === Prim.Path && a + data[o + SHAPE0 + 2] > 256) {
35
+ warned.caps = true;
36
+ console.warn(`pixi-silk: a path is too long for WebGL1 (over ${GL1_MAX_EDGES} edges or 256 stroke windows) and draws in part. Split it into several paths.`);
37
+ return;
38
+ }
39
+ }
40
+ }
41
+ /** @internal Builds the hooks `enableWebGL1()` installs in the slot. */
42
+ function createGl1Hooks() {
43
+ const programs = /* @__PURE__ */ new Map();
44
+ const hooks = {
45
+ program(name, vertex, fragment) {
46
+ let entry = programs.get(name);
47
+ if (!entry) {
48
+ const s = gl1Sources(name, vertex, fragment);
49
+ entry = {
50
+ program: GlProgram.from({
51
+ vertex: s.vertex.source,
52
+ fragment: s.fragment.source,
53
+ name: `${name}-gl1`,
54
+ preferredVertexPrecision: "highp",
55
+ preferredFragmentPrecision: "highp"
56
+ }),
57
+ sized: [.../* @__PURE__ */ new Set([...s.vertex.sized, ...s.fragment.sized])]
58
+ };
59
+ programs.set(name, entry);
60
+ }
61
+ return entry.program;
62
+ },
63
+ resources(name) {
64
+ const sized = programs.get(name)?.sized ?? [];
65
+ const uniforms = {};
66
+ for (const s of sized) uniforms[`${s}Size`] = {
67
+ value: new Float32Array([1, 1]),
68
+ type: "vec2<f32>"
69
+ };
70
+ const out = { gl1Sizes: new UniformGroup(uniforms) };
71
+ if (name === "silk-sdf") out.uInstances = dataTexture("silk-instances-gl1");
72
+ return out;
73
+ },
74
+ attach(geometry) {
75
+ if (silkGpu.program === null) {
76
+ for (const name of INSTANCE_ATTRIBUTES) if (!GL1_VERTEX_ATTRIBUTES.has(name)) delete geometry.attributes[name];
77
+ }
78
+ geometry.addAttribute("aIndex", {
79
+ buffer: new Buffer({
80
+ data: ascending(32),
81
+ usage: BufferUsage.VERTEX | BufferUsage.COPY_DST,
82
+ label: "silk-index-gl1"
83
+ }),
84
+ format: "float32",
85
+ stride: 4,
86
+ offset: 0,
87
+ instance: true
88
+ });
89
+ },
90
+ commit(geometry, shader, data, count) {
91
+ const index = geometry.attributes.aIndex?.buffer;
92
+ if (index && index.data.length < count) {
93
+ let n = index.data.length;
94
+ while (n < count) n *= 2;
95
+ index.data = ascending(n);
96
+ }
97
+ const src = shader.resources.uInstances;
98
+ const rows = Math.max(1, Math.ceil(count / 64));
99
+ const floats = rows * INSTANCE_TEXTURE_WIDTH * 4;
100
+ let mirror = src.resource;
101
+ if (mirror.buffer.byteLength < floats * 4) mirror = new Float32Array(floats);
102
+ else mirror = new Float32Array(mirror.buffer, 0, floats);
103
+ mirror.set(data.subarray(0, count * 44));
104
+ src.resource = mirror;
105
+ if (src.height !== rows) src.resize(INSTANCE_TEXTURE_WIDTH, rows);
106
+ src.update();
107
+ hooks.syncSizes(shader);
108
+ checkCaps(data, count);
109
+ },
110
+ syncSizes(shader) {
111
+ const ramps = shader.resources.uGradients;
112
+ if (hooks.nearestRamps && ramps && ramps.style.scaleMode !== "nearest") {
113
+ ramps.style.scaleMode = "nearest";
114
+ ramps.style.update();
115
+ }
116
+ const group = shader.resources.gl1Sizes;
117
+ if (!group) return;
118
+ let changed = false;
119
+ for (const key of Object.keys(group.uniforms)) {
120
+ const src = shader.resources[key.slice(0, -4)];
121
+ const v = group.uniforms[key];
122
+ if (!src || v[0] === src.pixelWidth && v[1] === src.pixelHeight) continue;
123
+ v[0] = src.pixelWidth;
124
+ v[1] = src.pixelHeight;
125
+ changed = true;
126
+ }
127
+ if (changed) group.update();
128
+ },
129
+ release(shader) {
130
+ shader.resources.uInstances?.destroy();
131
+ },
132
+ nearestRamps: false
133
+ };
134
+ return hooks;
135
+ }
136
+ //#endregion
137
+ export { checkCaps, createGl1Hooks };
@@ -0,0 +1,244 @@
1
+ import { INSTANCE_ATTRIBUTES } from "../constants.js";
2
+ import { toGlsl100 } from "./glsl100.js";
3
+ /** @internal Texels per instance in the instance texture (one vec4 attribute each). */
4
+ const TEXELS_PER_INSTANCE = 11;
5
+ /** @internal Width of the instance texture in texels. */
6
+ const INSTANCE_TEXTURE_WIDTH = 704;
7
+ /** @internal Most edges of a filled path, and most records of a union, the WebGL1 shader reads. */
8
+ const GL1_MAX_EDGES = 4096;
9
+ /** @internal Instance attributes the WebGL1 vertex stage still reads (8 attributes is the WebGL1 minimum). */
10
+ const GL1_VERTEX_ATTRIBUTES = /* @__PURE__ */ new Set([
11
+ "aBounds",
12
+ "aShape0",
13
+ "aShape2",
14
+ "aMeta",
15
+ "aFx"
16
+ ]);
17
+ const KEPT = GL1_VERTEX_ATTRIBUTES;
18
+ const silkVertexPatches = [
19
+ {
20
+ find: /^uniform highp sampler2D uBatch;\n/m,
21
+ replace: ""
22
+ },
23
+ {
24
+ find: /^vBase = 0\.0;\nint idx[\s\S]*?vBase = r1\.z;\n\}\n/m,
25
+ replace: ""
26
+ },
27
+ {
28
+ find: /^flat out .*\n/gm,
29
+ replace: ""
30
+ },
31
+ {
32
+ find: new RegExp(`^v(${[
33
+ "Shape0",
34
+ "Shape1",
35
+ "Shape2",
36
+ "Meta",
37
+ "Fill",
38
+ "Stroke",
39
+ "Grad",
40
+ "Paint",
41
+ "Dash",
42
+ "Fx",
43
+ "Tint",
44
+ "Inv",
45
+ "InvT",
46
+ "Base"
47
+ ].join("|")}) = .*\\n`, "gm"),
48
+ replace: ""
49
+ },
50
+ {
51
+ find: new RegExp(`^in vec4 (${INSTANCE_ATTRIBUTES.filter((a) => !KEPT.has(a)).join("|")});\\n`, "gm"),
52
+ replace: ""
53
+ },
54
+ {
55
+ find: "in vec2 aCorner;\n",
56
+ replace: "in vec2 aCorner;\nin float aIndex;\n"
57
+ },
58
+ {
59
+ find: "out vec2 vPos;\n",
60
+ replace: "out vec2 vPos;\nout float vIndex;\n"
61
+ },
62
+ {
63
+ find: "vPos = pos;\n",
64
+ replace: "vPos = pos;\nvIndex = aIndex;\n"
65
+ }
66
+ ];
67
+ function instanceSetup() {
68
+ const reads = INSTANCE_ATTRIBUTES.map((a, i) => a === "aBounds" ? "" : ` v${a.slice(1)} = instanceTexel(${i});\n`).join("");
69
+ return `// WebGL1: what the WebGL2 vertex stage passes in flat varyings, read here from uInstances
70
+ vec4 instanceTexel(int i)
71
+ {
72
+ int slot = int(vIndex + 0.5);
73
+ int row = slot / 64;
74
+ return texelFetch(uInstances, ivec2((slot - row * 64) * ${TEXELS_PER_INSTANCE} + i, row), 0);
75
+ }
76
+
77
+ void gl1Setup()
78
+ {
79
+ ${reads} vTint = uColor * uWorldColorAlpha;
80
+ vBase = 0.0;
81
+ mat3 m = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
82
+ float idet = 1.0 / (m[0].x * m[1].y - m[1].x * m[0].y);
83
+ mat2 ai = mat2(m[1].y, -m[0].y, -m[1].x, m[0].x) * idet;
84
+ vInv = vec4(ai[0], ai[1]);
85
+ vInvT = -(ai * m[2].xy);
86
+ }
87
+
88
+ `;
89
+ }
90
+ const silkFragmentPatches = [
91
+ {
92
+ find: /^flat in (vec4|vec2|float) (\w+);\n/gm,
93
+ replace: "$1 $2;\n"
94
+ },
95
+ {
96
+ find: "in float vProg;\n",
97
+ replace: `in float vProg;
98
+ in float vIndex;
99
+
100
+ uniform mat3 uProjectionMatrix;
101
+ uniform mat3 uWorldTransformMatrix;
102
+ uniform mat3 uTransformMatrix;
103
+ uniform vec4 uColor;
104
+ uniform vec4 uWorldColorAlpha;
105
+ uniform highp sampler2D uInstances;
106
+ `
107
+ },
108
+ {
109
+ find: /float sdPolygon6\(vec2 p, vec2 v\[6\], int n\)\n\{[\s\S]*?return s \* sqrt\(d\);\n\}/,
110
+ replace: `float sdPolygon6(vec2 p, vec2 v[6], int n)
111
+ {
112
+ // WebGL1 indexes arrays with loop indices only: walk the edges with the previous vertex in hand
113
+ vec2 prev = v[0];
114
+ for (int i = 0; i < 6; i++)
115
+ {
116
+ if (i == n - 1) prev = v[i];
117
+ }
118
+ float d = dot(p - v[0], p - v[0]);
119
+ float s = 1.0;
120
+ for (int i = 0; i < 6; i++)
121
+ {
122
+ if (i >= n) break;
123
+ vec2 vi = v[i];
124
+ vec2 e = prev - vi;
125
+ vec2 w = p - vi;
126
+ vec2 b = w - e * clamp(dot(w, e) / max(dot(e, e), 1e-12), 0.0, 1.0);
127
+ d = min(d, dot(b, b));
128
+ bvec3 c = bvec3(p.y >= vi.y, p.y < prev.y, e.x * w.y > e.y * w.x);
129
+ if (all(c) || all(not(c))) s = -s;
130
+ prev = vi;
131
+ }
132
+ return s * sqrt(d);
133
+ }`
134
+ },
135
+ {
136
+ find: ` P[k] = v + d1 * e + n1 * hw;
137
+ P[k + 1] = v + d1 * e + n1 * inner;
138
+ P[k + 2] = v - d0 * e + n0 * inner;
139
+ `,
140
+ replace: ` vec2 t0 = v + d1 * e + n1 * hw;
141
+ vec2 t1 = v + d1 * e + n1 * inner;
142
+ vec2 t2 = v - d0 * e + n0 * inner;
143
+ if (k == 2)
144
+ {
145
+ P[2] = t0;
146
+ P[3] = t1;
147
+ P[4] = t2;
148
+ P[5] = t2;
149
+ }
150
+ else
151
+ {
152
+ P[3] = t0;
153
+ P[4] = t1;
154
+ P[5] = t2;
155
+ }
156
+ `
157
+ },
158
+ {
159
+ find: "float closedSD(vec2 p, int type, float px)\n",
160
+ replace: `float gSt[8];
161
+
162
+ float stGet(int i)
163
+ {
164
+ float r = 0.0;
165
+ for (int j = 0; j < 8; j++)
166
+ {
167
+ if (j == i) r = gSt[j];
168
+ }
169
+ return r;
170
+ }
171
+
172
+ void stSet(int i, float v)
173
+ {
174
+ for (int j = 0; j < 8; j++)
175
+ {
176
+ if (j == i) gSt[j] = v;
177
+ }
178
+ }
179
+
180
+ float closedSD(vec2 p, int type, float px)
181
+ `
182
+ },
183
+ {
184
+ find: "float st[8];",
185
+ replace: ""
186
+ },
187
+ {
188
+ find: /\b(min|max)\((sp[^,()]*), (\d+)\)/g,
189
+ replace: "i$1($2, $3)"
190
+ },
191
+ {
192
+ find: /\bst\[([^\]]+)\] = ([^;]+);/g,
193
+ replace: "stSet($1, $2);"
194
+ },
195
+ {
196
+ find: /\bst\[([^\]]+)\]/g,
197
+ replace: "stGet($1)"
198
+ },
199
+ {
200
+ find: "void main(void)\n{",
201
+ replace: `${instanceSetup()}void main(void)\n{\ngl1Setup();`
202
+ }
203
+ ];
204
+ const rampPatches = [{
205
+ find: "uniform highp sampler2D uGradients;\n",
206
+ replace: `uniform highp sampler2D uGradients;\n\nvec4 rampLinear(float t, float row)
207
+ {
208
+ float x = t * 255.0;
209
+ float i = floor(x);
210
+ float v = (row + 0.5) / 256.0;
211
+ vec4 a = texture(uGradients, vec2((i + 0.5) / 256.0, v));
212
+ vec4 b = texture(uGradients, vec2((min(i + 1.0, 255.0) + 0.5) / 256.0, v));
213
+ return mix(a, b, x - i);
214
+ }
215
+ \n`
216
+ }, {
217
+ find: /textureLod\(uGradients, vec2\(\(t \* 255\.0 \+ 0\.5\) \/ 256\.0, \((\w+)\.y \+ 0\.5\) \/ 256\.0\), 0\.0\)/g,
218
+ replace: "rampLinear(t, $1.y)"
219
+ }];
220
+ /** Per-program conversion options, by program name. Programs not listed need only the general rules. */
221
+ const OPTIONS = {
222
+ "silk-sdf": {
223
+ vertex: { patches: silkVertexPatches },
224
+ fragment: {
225
+ patches: [...silkFragmentPatches, ...rampPatches],
226
+ caps: {
227
+ n: GL1_MAX_EDGES,
228
+ nAll: 256,
229
+ "s + cnt": 32
230
+ }
231
+ }
232
+ },
233
+ "silk-text": { fragment: { patches: rampPatches } }
234
+ };
235
+ /** @internal Converts the GLSL ES 3.00 stages of the program called `name` to GLSL ES 1.00. */
236
+ function gl1Sources(name, vertex, fragment) {
237
+ const options = OPTIONS[name] ?? {};
238
+ return {
239
+ vertex: toGlsl100(vertex, "vertex", options.vertex),
240
+ fragment: toGlsl100(fragment, "fragment", options.fragment)
241
+ };
242
+ }
243
+ //#endregion
244
+ export { GL1_MAX_EDGES, GL1_VERTEX_ATTRIBUTES, INSTANCE_TEXTURE_WIDTH, TEXELS_PER_INSTANCE, gl1Sources };
@@ -0,0 +1,41 @@
1
+ import { Renderer } from "pixi.js";
2
+ //#region src/webgl1.d.ts
3
+ /** Whether `renderer` is Pixi's WebGL renderer on a WebGL1 context. */
4
+ export declare function isWebGL1(renderer: Renderer): boolean;
5
+ /**
6
+ * Lets SilkGraphics, SilkText and Glass render on a WebGL1 context. Pixi falls back to WebGL1 when
7
+ * the browser has no WebGL2. This installs GLSL ES 1.00 versions of the shaders, which live in this
8
+ * module so that apps that leave it out do not ship them.
9
+ *
10
+ * Pass it to {@link createSilkApp} as `webgl1: enableWebGL1`, or call it with the renderer of an
11
+ * application you create yourself. It does nothing unless the renderer runs WebGL1. Call it before
12
+ * you create any SilkGraphics: objects created earlier keep the WebGL2 program and draw nothing.
13
+ *
14
+ * The device needs `OES_texture_float`, `OES_texture_half_float`, `OES_standard_derivatives` and
15
+ * highp in fragment shaders. Without one of them this logs an error, installs nothing and returns
16
+ * `false`: silk objects then draw nothing, and the app can show a fallback. Without
17
+ * `OES_texture_half_float_linear` the gradient ramps switch to nearest filtering, which the WebGL1
18
+ * shaders blend themselves, so they look the same.
19
+ *
20
+ * Limits on WebGL1: `enableSilkBatching()` has no effect, each object is one draw call. A filled
21
+ * path with more than 4096 edges, or a stroked path with more than 256 windows, draws in part with
22
+ * a warning. Programs are global: once enabled, objects on a WebGL2 renderer on the same page use
23
+ * the WebGL1 shaders too and do not batch. They give the same pixels.
24
+ *
25
+ * @param renderer - The renderer of the application.
26
+ * @returns `true` when WebGL1 support is on for this renderer. `false` when the renderer is not
27
+ * WebGL1, or the device lacks something the shaders need (an error is logged).
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { createSilkApp, SilkGraphics } from 'pixi-silk';
32
+ * import { enableWebGL1 } from 'pixi-silk/webgl1';
33
+ *
34
+ * const silk = await createSilkApp({ parent: document.body, webgl1: enableWebGL1 });
35
+ * silk.app.stage.addChild(new SilkGraphics().circle(50, 50, 40).fill(0x30d158));
36
+ * ```
37
+ */
38
+ export declare function enableWebGL1(renderer: Renderer): boolean;
39
+ /** Whether {@link enableWebGL1} has run on a WebGL1 renderer, so new SilkGraphics carry the WebGL1 program. */
40
+ export declare function isWebGL1Enabled(): boolean;
41
+ //#endregion
package/dist/webgl1.js ADDED
@@ -0,0 +1,104 @@
1
+ import { silkGl1 } from "./shader-slot.js";
2
+ import { createGl1Hooks } from "./webgl1/hooks.js";
3
+ //#region src/webgl1.ts
4
+ /** Whether `renderer` is Pixi's WebGL renderer on a WebGL1 context. */
5
+ function isWebGL1(renderer) {
6
+ return renderer.name === "webgl" && renderer.context.webGLVersion === 1;
7
+ }
8
+ /** `HALF_FLOAT_OES` of `OES_texture_half_float`. */
9
+ const HALF_FLOAT_OES = 36193;
10
+ /**
11
+ * The texture formats silk uploads, fixed for WebGL1. Pixi 8 maps them to WebGL2 formats
12
+ * (`RGBA32F`, `RGBA16F`, `R8`, `RED`), so the uploads fail on WebGL1. WebGL1 takes the base format
13
+ * as the internal format, with the float types of `OES_texture_float` and `OES_texture_half_float`.
14
+ * It has no one-channel `RED`, so the text atlas uploads as `LUMINANCE`. The shader reads it the
15
+ * same through `.r`. The tables are private to Pixi: returns `false` when they are not there.
16
+ */
17
+ function patchFormats(renderer) {
18
+ const gl = renderer.gl;
19
+ const t = renderer.texture;
20
+ const internal = t._mapFormatToInternalFormat;
21
+ const format = t._mapFormatToFormat;
22
+ const type = t._mapFormatToType;
23
+ if (!internal || !format || !type) return false;
24
+ internal.rgba32float = gl.RGBA;
25
+ internal.rgba16float = gl.RGBA;
26
+ type.rgba16float = HALF_FLOAT_OES;
27
+ internal.r8unorm = gl.LUMINANCE;
28
+ format.r8unorm = gl.LUMINANCE;
29
+ return true;
30
+ }
31
+ /** What the device lacks for the WebGL1 programs, or `null` when it has everything. */
32
+ function missing(renderer) {
33
+ const gl = renderer.gl;
34
+ const ext = renderer.context.extensions;
35
+ if (!ext.floatTexture) return "OES_texture_float";
36
+ if (!ext.textureHalfFloat) return "OES_texture_half_float";
37
+ if (!gl.getExtension("OES_standard_derivatives")) return "OES_standard_derivatives";
38
+ const high = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
39
+ if (!high || high.precision === 0) return "highp precision in fragment shaders";
40
+ return null;
41
+ }
42
+ const prepared = /* @__PURE__ */ new WeakSet();
43
+ /**
44
+ * Lets SilkGraphics, SilkText and Glass render on a WebGL1 context. Pixi falls back to WebGL1 when
45
+ * the browser has no WebGL2. This installs GLSL ES 1.00 versions of the shaders, which live in this
46
+ * module so that apps that leave it out do not ship them.
47
+ *
48
+ * Pass it to {@link createSilkApp} as `webgl1: enableWebGL1`, or call it with the renderer of an
49
+ * application you create yourself. It does nothing unless the renderer runs WebGL1. Call it before
50
+ * you create any SilkGraphics: objects created earlier keep the WebGL2 program and draw nothing.
51
+ *
52
+ * The device needs `OES_texture_float`, `OES_texture_half_float`, `OES_standard_derivatives` and
53
+ * highp in fragment shaders. Without one of them this logs an error, installs nothing and returns
54
+ * `false`: silk objects then draw nothing, and the app can show a fallback. Without
55
+ * `OES_texture_half_float_linear` the gradient ramps switch to nearest filtering, which the WebGL1
56
+ * shaders blend themselves, so they look the same.
57
+ *
58
+ * Limits on WebGL1: `enableSilkBatching()` has no effect, each object is one draw call. A filled
59
+ * path with more than 4096 edges, or a stroked path with more than 256 windows, draws in part with
60
+ * a warning. Programs are global: once enabled, objects on a WebGL2 renderer on the same page use
61
+ * the WebGL1 shaders too and do not batch. They give the same pixels.
62
+ *
63
+ * @param renderer - The renderer of the application.
64
+ * @returns `true` when WebGL1 support is on for this renderer. `false` when the renderer is not
65
+ * WebGL1, or the device lacks something the shaders need (an error is logged).
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { createSilkApp, SilkGraphics } from 'pixi-silk';
70
+ * import { enableWebGL1 } from 'pixi-silk/webgl1';
71
+ *
72
+ * const silk = await createSilkApp({ parent: document.body, webgl1: enableWebGL1 });
73
+ * silk.app.stage.addChild(new SilkGraphics().circle(50, 50, 40).fill(0x30d158));
74
+ * ```
75
+ */
76
+ function enableWebGL1(renderer) {
77
+ if (!isWebGL1(renderer)) return false;
78
+ const r = renderer;
79
+ const lack = missing(r);
80
+ if (lack) {
81
+ console.error(`pixi-silk: this WebGL1 device lacks ${lack}, which SilkGraphics needs. Silk objects draw nothing.`);
82
+ return false;
83
+ }
84
+ if (!prepared.has(renderer)) {
85
+ if (!patchFormats(r)) {
86
+ console.error("pixi-silk: the format tables of Pixi texture system were not found (a Pixi version silk does not know). WebGL1 support is off.");
87
+ return false;
88
+ }
89
+ prepared.add(renderer);
90
+ r.runners.contextChange.add({ contextChange: () => {
91
+ r.gl.getExtension("OES_standard_derivatives");
92
+ patchFormats(r);
93
+ } });
94
+ }
95
+ silkGl1.hooks ??= createGl1Hooks();
96
+ if (!r.context.extensions.textureHalfFloatLinear) silkGl1.hooks.nearestRamps = true;
97
+ return true;
98
+ }
99
+ /** Whether {@link enableWebGL1} has run on a WebGL1 renderer, so new SilkGraphics carry the WebGL1 program. */
100
+ function isWebGL1Enabled() {
101
+ return silkGl1.hooks !== null;
102
+ }
103
+ //#endregion
104
+ export { enableWebGL1, isWebGL1, isWebGL1Enabled };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pixi-silk",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Smooth vector graphics for PixiJS v8: analytic anti-aliased SDF primitives, squircles, arcs, polylines, dashes, OKLab gradients, glows and DPR-exact canvases, one draw call per object.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -167,6 +167,10 @@
167
167
  "types": "./dist/webgpu.d.ts",
168
168
  "default": "./dist/webgpu.js"
169
169
  },
170
+ "./webgl1": {
171
+ "types": "./dist/webgl1.d.ts",
172
+ "default": "./dist/webgl1.js"
173
+ },
170
174
  "./text": {
171
175
  "types": "./dist/text.d.ts",
172
176
  "default": "./dist/text.js"
@@ -57,6 +57,7 @@ Import each from its own path. The root import does not re-export the others.
57
57
  |---|---|
58
58
  | `pixi-silk` | SilkGraphics, createSilkApp, gradients, colour and curve helpers, motion helpers (`damp`, `Spring`, `ease`), `enableSilkBatching`. |
59
59
  | `pixi-silk/webgpu` | `enableWebGPU` for your own WebGPU Application. |
60
+ | `pixi-silk/webgl1` | `enableWebGL1`, opt-in shaders for Pixi's WebGL1 fallback. |
60
61
  | `pixi-silk/glass` | `Glass`, a frosted pane. |
61
62
  | `pixi-silk/glow` | `Glow`, `Aurora`, `neon`, `halo`, rays. |
62
63
  | `pixi-silk/text` | `SilkText`, `SdfAtlas`, `silkLabel`, `layoutText`, caret helpers. |