Commit Graph
21083 Commits
Author SHA1 Message Date
Behdad Esfahbod 7c7b1756c1 [gpu] Support 3 nested glyph clips per layer
Replace the single-slot pending_clip / pending_clip_glyph /
pending_clip_font / pending_clip_transform fields with a stack of
up to HB_GPU_PAINT_MAX_CLIP_DEPTH (3) clips.  push_clip_glyph
appends; pop_clip pops; depth > 3 sets `unsupported`.

LAYER_SOLID and LAYER_GRADIENT ops grow from 2 to 3 texels:

  texel 0: (op_type, flags, clip1_hi, clip1_lo)
  texel 1: (clip2_hi, clip2_lo, clip3_hi, clip3_lo)
  texel 2: color (SOLID) or grad meta (GRADIENT)

The existing flags slot (i16) gains:
  bit 0   IS_FOREGROUND          (SOLID only -- was already there)
  bit 8   HAS_CLIP2              (new)
  bit 9   HAS_CLIP3              (new)
For GRADIENT the gradient subtype lives in bits 0..7.

Shader: nest the HAS_CLIP2 / HAS_CLIP3 checks (HAS_CLIP3 implies
HAS_CLIP2) so single-clip layers pay only one branch, two-clip
layers pay one extra slug call, three-clip layers pay two extra.
On Noto-COLRv1 the bench is unchanged (~320 fps with the emoji
text the user benches against), within noise of the depth-1
baseline -- the extra branches don't fire on most layers.

Ports across all four shader languages (GLSL, MSL, HLSL, WGSL).

NEWS: limitation entry updated to "up to 3 levels are intersected
exactly; deeper nests set unsupported".

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:25:58 -06:00
Behdad Esfahbod f6cd414c9f [gpu] Add hb_gpu_paint_set_scale / _get_scale
Mirror the draw API.  hb_gpu_paint_t already had x_scale / y_scale
fields and hb_gpu_paint_glyph() set them directly, but no public
setter / getter -- callers that want to use the paint funcs
without going through paint_glyph had no way to wire the scale.

Add the public setters / getters and route paint_glyph through
them, matching hb_gpu_draw_glyph's pattern.  Document on both
draw and paint that the convenience wrappers call _set_scale.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:08:03 -06:00
Behdad Esfahbod 8403dce620 [gpu] hb_gpu_paint_glyph: fix docstring
Two errors:

- We use hb_font_paint_glyph (not _or_fail) so non-color glyphs go
  through the synthesized-foreground fallback, which the body's
  comment already explains.
- The return is the encoder-supported flag (!paint->unsupported),
  not "has color paint data".  Monochrome glyphs return true; the
  return is false only when paint walk hit a feature the encoder
  doesn't represent (PaintImage, group-stack overflow, ...).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:06:24 -06:00
Behdad Esfahbod a01bd008ad [gpu] paint_encode: empty-blob singleton for "no ink" (match draw)
hb_gpu_draw_encode already returns the empty-blob singleton (not
NULL) when the encoder has accumulated no curves -- the convention
is "NULL = encoder failed, empty blob = nothing to render".

Make hb_gpu_paint_encode follow the same shape:
  - NULL  -> hard failure (paint_glyph hit an unsupported feature
             or allocation failed).
  - empty -> no ink (e.g. space glyph or paint tree that produced
             no layer ops).

Document on both encode functions, and update the tests to expect
empty (not NULL) for the no-ink path.

The demo already short-circuits on length 0 (no atlas upload) and
_hb_gpu_blob_recycle drops the empty singleton instead of stashing
it, so nothing downstream needs to change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:50:16 -06:00
Behdad Esfahbod b38c5189df [gpu] Detect paint-encoder limits, fail rather than misrender
Paint encoder used to push past several limits and produce a blob
that wraps an int16, overflows the shader's group stack, or skips
unsupported callbacks entirely.  Detect each:

- num_ops > 32767 (the i16 blob header field's range): set
  paint->unsupported in every emit path.
- group depth > HB_GPU_PAINT_MAX_GROUP_DEPTH (4 -- matches the
  fragment shader's HB_GPU_PAINT_GROUP_DEPTH): set unsupported
  in push_group; mirror the symmetric pop guard.
- PaintImage: register an `image` callback that sets unsupported
  (the slug+gradient encoder can't represent raster images).

push_clip_rectangle is intentionally NOT trapped -- the encoder
silently ignores it; rendered output is wider than the rectangle
asks but doesn't fail.

Nested PaintGlyph clips still silently override the outer clip
(only depth 1 is faithfully stored); follow-up commit will lift
this to depth 2.

Document all of the above in NEWS, and relax the COLR test to
tolerate a font where every glyph trips one of these limits.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:45:35 -06:00
Behdad Esfahbod 24e1bde6f2 [gpu] Name composite modes; approximate unsupported ones
a) Add inline /* MODE_NAME */ comments next to each mode == N
   branch in all four paint-shader languages.  The numbers were
   bare hb_paint_composite_mode_t values; the comments match.

b) Approximate unsupported modes with the nearest Porter-Duff
   mode rather than silently SRC_OVER'ing them:

     OVERLAY (14) / COLOR_BURN (18) / HARD_LIGHT (19) -> MULTIPLY
     COLOR_DODGE (17) / SOFT_LIGHT (20)              -> SCREEN

   DIFFERENCE (21), EXCLUSION (22) and HSL_HUE..HSL_LUMINOSITY
   (24-27) still fall through to SRC_OVER -- they're not similar
   enough to anything we have to be worth a misleading
   approximation.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:27:12 -06:00
Behdad Esfahbod 228e1792ac [gpu] Move encoder cleanup out of dtors, into _destroy
LSan flagged sub_blobs and recycled_blob leaks under failing-malloc
in hb_gpu_paint and hb_gpu_draw.  Both structs relied on a C++
destructor invoked indirectly via hb_object_actually_destroy() to
free their nested resources -- the same pattern that fooled me into
not noticing the path is fragile.

Match the established harfbuzz convention (hb_raster_paint_destroy,
hb_face_destroy, ...): drop the destructors, call
hb_object_should_destroy() to take ownership of the dec, do the
nested-resource cleanup explicitly, then hb_object_actually_destroy
+ hb_free.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:38:07 -06:00
Behdad Esfahbod 52b97c7f79 [gpu] Share blob-recycling between draw and paint encoders
hb_gpu_draw already recycled its output blob: hand the blob back
via hb_gpu_draw_recycle_blob() and the next hb_gpu_draw_encode()
reused the underlying buffer (and even returned the same blob
handle), avoiding malloc / blob allocation traffic in the
glyph-by-glyph loop.

Paint had a recycled_blob field but its recycle_blob entry point
just hb_blob_destroy()'d the input.  Lift the recycle machinery
out of hb-gpu-draw.cc into a small set of helpers
(_hb_gpu_blob_acquire / _finalize / _abort / _recycle) that live
in hb-gpu.cc, declared in a new internal header hb-gpu.hh, and
share the destroy-callback identity between both encoders.  Both
paint and draw now reuse the same buffer pool semantics.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:26:16 -06:00
Behdad Esfahbod d235a23b45 [test/api] Silence cast-align in test-gpu blob accessors
Casting hb_blob_get_data()'s const char* to a struct pointer
trips clang's -Wcast-align (1-byte to 2-byte short).  In practice
the blob's underlying buffer is malloc'd and so suitably aligned
for any standard type; suppress the warning around the cast with
the same #pragma GCC diagnostic ignored "-Wcast-align" pattern
used elsewhere in the codebase (hb-bit-set.hh, hb-machinery.hh).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:26:01 -06:00
Behdad Esfahbod 5fac9a0560 [array] Adapt qsort comparator return type to std::sort's bool
Restore the historical qsort contract: a C-style int comparator
(negative / zero / positive) is the canonical convention, and
hb_array_t::qsort accepted that for years -- until it was
switched from hb_qsort to std::sort.  std::sort wants bool
less-than: a +1 return for a > b looked truthy, broke
strict-weak-ordering, and caused out-of-bounds writes that ASAN
flagged from normalize_stops in hb-gpu-paint.

Wrap the std::sort call with a small overloaded helper
_qsort_lt: bool returns pass through; any other arithmetic
return is treated as the int signed comparator (< 0).  Existing
bool-returning callers (hb-cairo-utils, hb-face-builder, _qsort)
keep working; int-returning callers (hb-gpu-paint,
hb-ot-post-table) sort correctly again.

Discovered after extending hb-gpu-fuzzer to also exercise
hb_gpu_paint, which surfaced the latent UB on
noto_handwriting-glyf_colr_1.ttf.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:16:22 -06:00
Behdad Esfahbod 34df3e2b4b [gpu] Cover hb_gpu_paint in the gpu fuzzer
The existing hb-gpu-fuzzer only exercised hb_gpu_draw.  Add a
parallel paint round-trip per glyph (paint_glyph -> encode ->
recycle_blob) so the paint encoder gets the same fuzzed-input
coverage -- gradient / transform / composite parsing in
particular has a lot more surface than the slug encoder.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:03:05 -06:00
Behdad Esfahbod 80e517a31a [gpu] Use real em-dashes in section docs
The existing hb-gpu section uses real em-dashes; my recent
additions slipped some ASCII -- in.  gtk-doc converts -- to en-dash
in the HTML output, but matching the rest of the file with real
em-dashes is cleaner.

Reported by Khaled.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:02:18 -06:00
Behdad Esfahbod 157e5111b3 [gpu] Add tests + benchmark for hb_gpu_paint, NEWS draft
test/api/test-gpu: extends the existing draw test suite with
paint counterparts -- create/destroy, get_funcs singleton,
shader_source for all four langs, empty encode returns nullptr,
encode of a monochrome glyph (synthesized single-layer fallback),
encode of a real COLRv1 glyph (test_glyphs-glyf_colr_1.ttf,
scanning for a glyph our encoder fully supports), auto-clear on
encode, reset wipes config, recycle_blob roundtrip.

perf/benchmark-gpu: add BM_GpuPaintEncode parallel to
BM_GpuDrawEncode (renamed from BM_GpuEncode for symmetry) so the
two paths can be compared on the same fonts.

NEWS: draft entry under "leading to NEXT (REPLACEME)" listing the
new hb_gpu_paint_* API surface and the recent GPU library changes
(--draw / --paint flags, gradient inverse-transform).  Release
manager will fold this into the actual release section.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:00:51 -06:00
Behdad Esfahbod 1f813cfb86 [util/gpu] Extract MSL/HLSL/WGSL demo shaders into own files
Matches the GLSL convention: demo-shader.{msl,hlsl,wgsl} live
alongside demo-fragment.glsl and get stringified by the same
gen-gpu-shader-artifacts.py helper into demo-shader-{msl,hlsl,
wgsl}.hh.  No more giant inline R"msl(...)" / R"hlsl(...)" /
R"wgsl(...)" blobs in the .mm / .cc files.

Each language combines vertex and fragment entry points in one
source, as is idiomatic for MSL / HLSL / WGSL compilers; GLSL's
split (demo-vertex.glsl + demo-fragment.glsl) is preserved
because glCompileShader takes separate stages.

No functional change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:33:44 -06:00
Behdad Esfahbod 5779d9315d [docs] Fix build 2026-04-14 15:33:02 -06:00
Behdad Esfahbod c4da618566 [gpu] Stem-darken by per-fragment color, not by foreground uniform
The demo fragment shaders were passing u_foreground's brightness
to hb_gpu_stem_darken(), which was wrong for color glyphs: a red
cheek on an emoji should darken relative to its own red, not to
whatever the text-foreground uniform happens to be.

Switch all four demo fragment paths (GL, Metal, D3D11, WebGPU)
to compute brightness from the fragment's own straight color
(c.rgb / c.a).  For monochrome glyphs this is identical to the
old formula -- the synthesized single layer's color IS the
foreground uniform -- so non-color rendering is unchanged.

The public hb_gpu_stem_darken() helper is unchanged; only its
callers pass a different brightness.  Document the paint-path
usage in the hb-gpu section.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:24:32 -06:00
Behdad Esfahbod 819fce8352 [gpu] Document Paint renderer; drop encode-time foreground API
Integrates the paint renderer into the hb-gpu module docs:

- Intro notes two renderers (Draw for monochrome, Paint for
  COLRv0/COLRv1, with explicit note that Paint also handles
  monochrome outlines at some cost).
- New Paint section parallel to Draw covers encoding, shader
  composition, and fragment shader, referencing Draw for the
  shared atlas / vertex / dilation / stem-darkening pieces.
- Encoding examples drop hb_gpu_*_reset() in favour of
  hb_gpu_*_encode()'s auto-clear.

Drops hb_gpu_paint_set_foreground() / _get_foreground() and the
foreground field from hb_gpu_paint_t.  The encoded blob only
records an is_foreground flag per layer/stop; the actual
foreground color has always been a shader uniform passed to
hb_gpu_paint() at render time.  The encoder API was never
load-bearing -- the value was handed to hb_font_paint_glyph() but
the encoder callback ignores everything except the flag.

Also makes hb_gpu_paint_encode() auto-clear on return (matching
hb_gpu_draw_encode()), and removes the now-dead
demo_font_set_foreground() wrapper from the demo layer.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:15:53 -06:00
Behdad Esfahbod e8534b6673 [gpu] Bake inverse transform into gradient ops
Previously we baked the current transform into gradient geometry
at encode time -- transformed centers + sqrt(|det|) scaling for
the radial radius, and added the rotation angle to sweep
start/end.  That worked for conformal (scale + rotate) transforms
but was wrong under non-uniform scale or shear: a circle maps to
an ellipse, and angles warp non-linearly.  The prior code
documented this as a known limitation.

This commit stores the inverse of the transform's 2x2 linear part
(Q10 fixed-point, i16, +1 texel per gradient op) in the gradient
params blob, and stores geometry relative to a rendered origin
plus untransformed deltas and radii.  The shader computes
p_canonical = L^-1 * (renderCoord - origin_rendered) and evaluates
the gradient in its untransformed frame, so shear / non-uniform
scale produce proper ellipses and angular distortion exactly
rather than scalar-fudged.

Layouts (per gradient, before the color stops):

  linear: (p0_rendered.xy, d_canonical.xy), (L^-1 Q10 row-major)
  radial: (c0_rendered.xy, d_canonical.xy), (r0, r1, 0, 0),
          (L^-1 Q10 row-major)
  sweep:  (center_rendered.xy, start_q14, end_q14),
          (L^-1 Q10 row-major)

Per-fragment cost: one 2x2 mat-vec (6 flops).  Noto-COLRv1 emoji
bench fps unchanged.  Ported across GLSL / MSL / HLSL / WGSL.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 14:56:39 -06:00
Behdad Esfahbod 86772bf453 [gpu] Regenerated shaders 2026-04-14 00:25:32 -06:00
Behdad Esfahbod e2d58c6e07 [gpu] Skip out-of-bbox layers in paint shader (MSL, HLSL, WGSL)
Port the GLSL _hb_gpu_slug_clipped helper from the previous
commit to the other three shader languages so the paint-path
sub-glyph bbox short-circuit applies on Metal, D3D11, and
WebGPU as well.

Builds cleanly; runtime shader compile in each backend will
validate the syntax.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:24:41 -06:00
Behdad Esfahbod 59da0441d9 [gpu] Skip out-of-bbox layers in paint shader (GLSL)
Many COLRv1 paint layers cover a small region of the outer
glyph quad; emoji fonts in particular can have dozens of
sub-glyphs each clipped to a few percent of the outer bbox.
For fragments outside a layer's clip-outline bbox (plus a
2-pixel AA + MSAA-spread margin) the slug coverage is exactly
0, so the band/curve walk is wasted work.

Adds a paint-shader-only helper _hb_gpu_slug_clipped that
fetches the sub-glyph header and bails out before invoking
_hb_gpu_slug when the fragment is outside.  Draw path is
untouched, paint path on a Noto-COLRv1 emoji frame went from
~200 fps to >300 fps in local testing.

GLSL only for now; MSL, HLSL, WGSL to follow.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:22:27 -06:00
Behdad Esfahbod f840ae39a2 [util/gpu] Add --draw / --paint flags with auto-detect by font
Adds command-line flags --draw (force monochrome Slug path) and
--paint (force COLRv1 paint path) to hb-gpu, defaulting to
auto-detect based on hb_ot_color_has_paint(face).  Threads a
draw_only bool through the demo layer so each backend compiles
exactly one fragment program (draw or paint, not both).

The paint pipeline is ~10x slower than the draw pipeline on
monochrome content; auto-detect lets monochrome fonts keep the
fast path while still exercising both code paths from the same
binary.

Plumbing:

- demo_renderer_create_{gl,metal,d3d11} and demo_font_create
  take a draw_only argument.
- demo-fragment.{glsl,msl,hlsl} branch on HB_GPU_DEMO_DRAW,
  calling either hb_gpu_draw or hb_gpu_paint.
- demo-shader / glstate / d3d11 / metal include only the
  fragment helper for the chosen path and prepend
  HB_GPU_DEMO_DRAW to the source when draw_only.
- demo-font dispatches glyph upload to hb_gpu_draw_* or
  hb_gpu_paint_* and hides palette/foreground setters in
  draw mode.

Web demos pass false (paint-only) for now; a runtime
re-creation hook on font change would be needed there.

Tested on desktop GL, win64 D3D11, WebGL, WebGPU.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:04:27 -06:00
Behdad Esfahbod a63afbee9e [gpu] Regenerate hb-gpu-fragment-msl.hh
Regenerate from the .msl source after the missing closing brace
fix in 6ef71b9a6.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:54:05 -06:00
Behdad Esfahbod 6ef71b9a69 [gpu] Fix missing closing brace in Metal fragment shader
_hb_gpu_slug in hb-gpu-fragment.msl was missing its closing
brace, so hb_gpu_stem_darken got parsed as a nested function
definition, which MSL rejects:

    error: function definition is not allowed here

The other three shader languages already had the brace; this
regression was limited to the Metal source during the recent
refactor that moved the slug body to the shared fragment file.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:53:18 -06:00
Behdad Esfahbod 18360b24fd [gpu] Shaders: move Slug body to shared, rename _hb_gpu_draw_impl to _hb_gpu_slug
The Slug coverage algorithm (root-code math, band decode, single-
sample coverage, MSAA wrapper) and stem-darkening curve are useful
to both the draw renderer and the paint renderer.  Until now they
lived inside hb-gpu-draw-fragment.{glsl,msl,hlsl,wgsl} and
hb-gpu-paint-fragment had to include the draw source to reach them,
even though the paint renderer doesn't need hb_gpu_draw itself.

Move everything except the thin fwidth wrapper into the already-
shared hb-gpu-fragment.{ext} helpers, and rename the MSAA-aware
entry point _hb_gpu_draw_impl -> _hb_gpu_slug since it's no longer
specific to the draw renderer.  hb_gpu_draw is now a one-liner in
hb-gpu-draw-fragment that calls _hb_gpu_slug with pixelsPerEm
derived from fwidth at uniform control flow.

No functional change.  bench --demo stays at ~1750fps.

Next step: demo dispatches to either the draw or paint shader
based on whether the font has any color paint, recovering the ~25%
perf gap for monochrome fonts while still exercising both paths
from the same binary.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 23:41:26 -06:00
Behdad Esfahbod 6ca076f36b [util/gpu] Apply stem darkening in Metal and D3D11 fragment shaders
demo-fragment.glsl (desktop GL/WebGL) and the WGSL shader in
hb-gpu-web-webgpu.cc already invoked hb_gpu_stem_darken on the
painted result; the Metal (fragment_main) and D3D11 (ps_main)
entry points were missing that block, so stem darkening did
nothing on those backends.

Add the same call: compute ppem from fwidth(texcoord), derive
brightness from the foreground luminance, and scale the
premultiplied result by darkened/c.a.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 22:43:18 -06:00
Behdad Esfahbod ea88d25d07 [util/gpu] Web demos: drop stale gamma-toggle hints
The `g` key was removed when we hardcoded gamma 2.2; the shell's
help overlay still mentioned it.  Drop the lines.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 22:29:00 -06:00
Behdad Esfahbod f034699e2d [gpu] hb_gpu_paint: transform clip outline at push_clip_glyph time
The outline of a PaintGlyph's clip is defined in the coord space
that was active when push_clip_glyph fires -- call it T_outer.
The paint subtree underneath can have its own PaintTransform
wrappers; when a gradient/color callback fires, cur_transform may
be deeper than T_outer.  The previous code used cur_transform for
the clip outline too, which placed the clip at the WRONG position
when the child paint was wrapped in inner transforms (e.g. Noto-
COLRv1 emoji 🤣).

Snapshot cur_transform into pending_clip_transform at
push_clip_glyph time, and use that transform for the clip outline
in emit_clip_sub_blob.  Gradient params keep using cur_transform
(the innermost composition) because HB dispatches their endpoints
in the innermost local space.

This matches what CPU raster already does implicitly (it paints
the clip into its current compositing surface using the transform
active at push_clip time, then rasterizes the child paint with
the deeper transform inside the same surface).

Fixes the "face split in two" glitch on 🤣 where the base face
stayed near the origin while the inner rotated features rendered
offset.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 22:22:31 -06:00
Behdad Esfahbod 11f9a36a0d [gpu] hb_gpu_paint: honor COLRv1 paint transforms
Register push_transform / pop_transform callbacks and maintain a
current-affine stack (hb_transform_t<float>) on hb_gpu_paint_t.
Each push_transform multiplies the incoming matrix into the
current transform; pop_transform restores the previous one.

At each layer, the current transform is baked into the per-layer
data at encode time so the shader stays transform-unaware:

  - Clip-glyph outlines: feed them through a transforming pen
    (same pattern as VARC.cc's hb_transforming_pen_get_funcs) that
    multiplies each move/line/quadratic/cubic point by the current
    affine before forwarding to hb_gpu_draw's callbacks.
  - Linear gradient: transform both axis endpoints.
  - Radial gradient: transform the two centers, scale the two
    radii by sqrt(|det|) (uniform-scale approximation; a non-
    uniform scale turns the gradient circle into an ellipse which
    the current shader does not model).
  - Sweep gradient: transform the center, rotate both angles by
    atan2(yx, xx) to pick up any rotation component.

Identity-transform layers (still the common case) use a fast path
that skips the transforming pen entirely.  The pen keeps a
separate hb_draw_state_t for the downstream so transformed-space
state writes don't leak back into the caller's pre-transform
state; explicitly close any trailing open path on the downstream
state before returning.

Noto-COLRv1's "kissing face" glyph now renders with correctly
positioned small pink cheek blushes instead of a red overlay on
the whole face.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 21:53:07 -06:00
Behdad Esfahbod e9f4be3ff2 [gpu] hb_gpu_paint: implement PUSH_GROUP / POP_GROUP compositing
Register push_group/pop_group paint callbacks, emit 1-texel
PUSH_GROUP / POP_GROUP ops, and handle them in all four paint
fragment shaders.

Each shader keeps an HB_GPU_PAINT_GROUP_DEPTH (=4) stack of vec4
accumulators.  PUSH_GROUP pushes the current `acc` and resets to
(0,0,0,0) so the enclosed subtree composites in isolation;
POP_GROUP pops the saved `acc` and composites the subtree result
into it using the mode stored in the op's aux slot (values match
hb_paint_composite_mode_t).

Implemented composite modes: CLEAR, SRC, DST, SRC_OVER (default),
DST_OVER, SRC_IN, DST_IN, SRC_OUT, DST_OUT, SRC_ATOP, DST_ATOP,
XOR, PLUS, SCREEN, DARKEN, LIGHTEN, MULTIPLY.  The CSS/PDF
separable blend modes (OVERLAY, COLOR_DODGE, COLOR_BURN,
HARD_LIGHT, SOFT_LIGHT, DIFFERENCE, EXCLUSION) and all four HSL
modes fall back to SRC_OVER for now.

Noto-COLRv1 happens not to emit any PaintComposite nodes, so this
doesn't change rendering for that font; fonts that do use it
(e.g. test_glyphs-glyf_colr_1.ttf) will pick this up.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 21:45:22 -06:00
Behdad Esfahbod 51318f2608 [gpu] hb_gpu_paint: normalize gradient color lines; add sweep
Gradient stops can arrive with offsets that don't span [0, 1] --
e.g. stops at 0.3 and 0.7 -- in which case REPEAT / REFLECT extend
modes would previously wrap over [0, 1] instead of over the stop
range.  Match hb_raster_paint's normalize_color_line: sort stops
by offset, find (mn, mx), rescale offsets to [0, 1], and shift the
gradient geometry along its direction by mn..mx so the rendered
gradient position stays identical.  Linear shifts axis endpoints,
radial shifts both centers and both radii, sweep shifts both
angles.

While there, implement real sweep gradient rendering.  Encoder
emits LAYER_GRADIENT subtype=2 with a 1-texel param block
(cx, cy, start_q14, end_q14) -- angles stored as Q14 fractions of
pi (angles come in as radians; shader divides atan2 by pi before
comparing).  All four shader languages grew _hb_gpu_sample_sweep.

The old hb_gpu_paint_gradient_first_stop fallback is gone now that
all three gradient subtypes are handled.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 21:28:34 -06:00
Behdad Esfahbod 5ce5be6bd2 [gpu] hb_gpu_paint: encode radial gradients as LAYER_GRADIENT
Same shape as linear: emit LAYER_GRADIENT with subtype=1 and a
gradient-params sub-blob.  Radial just uses two param texels
(c0:x,y,r0 and c1:x,y,r1) before the stops instead of one.

Shader side: add _hb_gpu_sample_radial in all four languages.
Solves the COLRv1 two-circle radial quadratic
|P - C0 - t*(C1-C0)|^2 = (r0 + t*(r1-r0))^2 for t, picking the
larger root when the interpolated radius stays non-negative,
falling through to the smaller root otherwise, and degenerating to
a linear solve when the quadratic coefficient is near zero.  Same
matching of hb_raster_paint's radial formulation.

Also extracted the color-stop walk (formerly inlined in
_hb_gpu_sample_linear) into _hb_gpu_eval_stops so both subtypes
share it; the per-subtype stops_base differs by one texel.

Sweep still uses the first-stop solid placeholder.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 20:52:56 -06:00
Behdad Esfahbod 6cf5e1a858 [gpu] hb_gpu_paint: encode linear gradients as LAYER_GRADIENT
The linear_gradient callback now emits a real LAYER_GRADIENT op
instead of falling back to a flat first-stop solid.  Per-layer op
layout:

  texel 0: (op_type=1, subtype=0, clip_payload_hi, clip_payload_lo)
  texel 1: (grad_payload_hi, grad_payload_lo, extend_mode, stop_count)

Both payloads are sub_blob indices that hb_gpu_paint_encode()
patches to absolute atlas offsets.  The clip payload is the
existing Slug draw blob for the layer's clip glyph; the gradient
payload is a fresh sub-blob laid out as:

  texel 0 : (lx0, ly0, lx1, ly1)  -- 2-point axis in font units,
            reduced from COLRv1's 3-point anchors the same way
            hb_raster_paint's reduce_anchors does it
  texels 1..N : color stops, 2 texels each
    texel a: (offset_q15, flags, _, _)  flags bit 0 = is_foreground
    texel b: (r_q15, g_q15, b_q15, a_q15)

All four paint fragment shaders (GLSL/MSL/HLSL/WGSL) grew a
_hb_gpu_sample_linear helper that projects the fragment onto the
axis, applies the COLRv1 extend mode, and walks stops to find the
enclosing segment.

Refactored the existing LAYER_SOLID emission body into
emit_clip_sub_blob + hb_gpu_paint_emit_solid so the gradient path
can share the clip-outline encode and extents accumulation.  The
LAYER_GRADIENT encode-time patching walks both payload slots.

Radial and sweep callbacks still fall back to the first-stop solid
placeholder; they'll be replaced next.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:31:04 -06:00
Behdad Esfahbod 62a8a3a26c [util/gpu] Drop sRGB framebuffer mode; always gamma 2.2
The paint encoder bakes sRGB-encoded font palette values directly
(quantizing 0..255 to 0..32767 without decoding), so the shader
writes sRGB-ish values.  With GL_FRAMEBUFFER_SRGB enabled the
driver then applied linear->sRGB encoding on store, giving a
double-encoded, washed-out result -- most visible on mid-tone
gradients.

The cleanest fix is to stop pretending we're doing linear-space
compositing: drop the sRGB framebuffer mode entirely and always
apply the classic 2.2 gamma exponent for coverage correction
(flipped to 1/2.2 in dark mode to match the existing light/dark
logic).  Removed pieces:

 - demo_view_t::gamma_mode enum, demo_view_set_gamma_mode,
   demo_view_cycle_gamma, and the `g` keybinding + help line
 - demo_renderer_t::set_srgb virtual + every backend override
 - GLFW_SRGB_CAPABLE hint in gpu-output.hh
 - Metal swapchain MTLPixelFormatBGRA8Unorm_sRGB -> BGRA8Unorm

Replaced with demo_view_update_gamma, called on setup() and after
the dark-mode toggle.  Shader side stays the same (only alpha gets
the gamma curve, as before).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:30:45 -06:00
Behdad Esfahbod 1fbbb0a627 [gpu] hb_gpu_paint: emit LAYER_SOLID from gradients using first stop
Register linear/radial/sweep gradient callbacks that read just the
first color stop from the color line and emit a LAYER_SOLID op with
that stop's color.  Previously these callbacks were unregistered,
so every gradient-filled layer silently produced no op -- Noto
COLRv1 emoji lost their face/body fills entirely.

Factor the LAYER_SOLID emission body out of hb_gpu_paint_color
into hb_gpu_paint_emit_solid so the color and gradient callbacks
share it.  Reading one stop (count=1) drives the usual
custom_palette_color / foreground resolution path exactly once,
so palette overrides and is_foreground still apply.

This is a placeholder until real gradient ops land; it just makes
gradient-heavy fonts render with sensible flat colors instead of
missing layers.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:48:23 -06:00
Behdad Esfahbod 087fd84a49 [util/gpu] Drop renderer palette plumbing, forward to hb_gpu_paint
Colors are now baked into encoded blobs (see prior commit), so
nothing needs to upload or bind a palette buffer.  Remove
demo_renderer_t::set_palette from all backends (GL, Metal, D3D11,
WebGPU), the hb_gpu_palette GL uniform plumbing in demo-glstate,
the Metal/D3D11 palette buffers, and the WebGPU storage buffer +
bind-group entry.  demo_font_get_palette is also gone.

Replace with new demo_font accessors that forward to the encoder:

  demo_font_set_palette
  demo_font_set_foreground
  demo_font_clear_custom_palette_colors
  demo_font_set_custom_palette_color

Each invalidates the glyph cache because colors are baked into
the atlas entries.  gpu-output.hh now forwards view-option
--font-palette / --custom-palette through these.

Web demos stop allocating / uploading the palette buffer; the
WGSL fragment shader drops its third bind-group slot.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:45:12 -06:00
Behdad Esfahbod e66500fd8e [gpu] hb_gpu_paint: bake resolved color into blob, drop palette binding
Add a raster-style configuration surface to hb_gpu_paint_t:

  hb_gpu_paint_set_foreground / hb_gpu_paint_get_foreground
  hb_gpu_paint_set_palette    / hb_gpu_paint_get_palette
  hb_gpu_paint_clear_custom_palette_colors
  hb_gpu_paint_set_custom_palette_color

hb_gpu_paint_glyph now passes paint->palette and paint->foreground
through to hb_font_paint_glyph, and the custom-palette-color
callback consults the user's overrides map (same pattern as
hb_raster_paint_t) before letting harfbuzz fall back to the font's
own palette.

With that in place, the color() callback can bake the already-
resolved RGBA into the encoded op directly, quantized as signed
Q15 in the existing second texel, instead of recording a palette
index and trusting the shader to look it up.  The is_foreground
flag stays in the op so a runtime foreground-color change (e.g.
dark-mode toggle) still works without re-encoding.

Shader side: drop the hb_gpu_palette uniform/storage binding and
its HB_GPU_PALETTE_SIZE knob from all four paint-fragment shaders
(GLSL / MSL / WGSL / HLSL); read the per-layer color straight out
of the blob texel.  This removes a per-backend binding slot and
the 256-entry uniform-array size ceiling that blocked fonts like
Noto-COLRv1 (~6200 entries).

Trade-off: changing the palette selection or overrides invalidates
previously encoded blobs and requires re-encoding.  In practice
palette switches are rare, and the rendering hot path gets
simpler.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:44:58 -06:00
Behdad Esfahbod 585154aa10 [util/gpu] Web demos: fix URL-param handling for ?font= and ?text=
rebuild_buffer did free(current_text); strdup(text); but was often
called with text == current_text (from web_load_font's
"custom_text ? current_text : default").  Strdup of freed memory
shaped garbage and made multi-char strings look like 1 char.  Fix:
strdup first, then free.

The WebGL rebuild_buffer also called demo_view_display itself,
which runs fine from a main loop tick but not from a fetch
promise's microtask (the canvas back-buffer doesn't swap).  Drop
it: demo_view_reset sets needs_redraw=true, and the next
main_loop_iter renders inside a proper rAF tick.

Emscripten allocates argv on the JS stack, which is unwound when
main returns.  WebGPU's init is async and reads arg_text/arg_font
after main returns, so those pointers were dangling -- early null
bytes in freed stack memory made the emoji URL shape to 1 glyph.
strdup them in main so they survive.

Finally, forward ?font= to argv as --font= (already done for
?text=) so the C side's "skip initial default-font glyph upload
when a font fetch is pending" path actually triggers.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:12:47 -06:00
Behdad Esfahbod 736d59bf72 [util/gpu] demo-font: tolerate NULL paint encode
hb_gpu_paint_encode returns NULL when the glyph uses unsupported
paint features (e.g. COLRv1 gradients/transforms) or emits zero
ops.  Treat that as an empty glyph instead of die()-ing the whole
app, so fonts mixing supported and unsupported paint still render
their supported parts.

Zero-init hb_ext so the empty-glyph extents are well-defined, and
skip recycle_blob when blob is NULL.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 18:12:23 -06:00
Behdad Esfahbod b616298d73 [util/gpu] Web demos: skip default-font upload when ?font= pending; preserve URL on backend switch; reflect custom text in URL
Three small UX improvements to the web demos.

### Skip default-font upload when ?font= is pending

When ?font= is set, the async fetch replaces the font later.  main
was still populating the atlas with the default font's glyphs for
the initial text, just to throw them away when _web_load_font ran
its own rebuild_buffer.  Gate demo_buffer_add_text() on !arg_font
so the buffer stays empty until the real font lands.

### WebGPU ready signal

WebGPU's init_demo is async (awaits adapter/device), so
onRuntimeInitialized fires before the demo is usable; calling
_web_load_font from the ?font= fetch at that point tripped a wasm
indirect-call signature mismatch.  init_demo now EM_ASMs a
window._webDemoReady() hook at its tail; the shell installs
_webDemoReady = startFontFetch when running the WebGPU build and
starts the fetch immediately for WebGL.

### URL ergonomics

* Backend-selector change now carries location.search across the
  navigation -- ?text= and ?font= survive the WebGL <-> WebGPU
  switch.
* The text-edit modal's Apply button updates history.replaceState
  with a ?text= param so the typed text is copy/pasteable.  Skips
  the update when the text is unchanged from what was open.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 17:10:31 -06:00
Behdad Esfahbod c85b453e90 [util/gpu] Web demos: URL ?text= and ?font=; wider default font
Two user-visible features plus a font swap.

### URL parameters

Forwards ?text= and ?font= from the query string into the C main
as --text=... and --font=... via Module.arguments, so the initial
text is applied before the first rendered frame (no flash of
default demo text).  ?font= is still fetched asynchronously on
the JS side; once loaded, the text is re-applied to the new font.

If neither parameter is present, behaviour is unchanged: the
baked-in default text renders in the baked-in default font.

Data URLs (?font=data:font/ttf;base64,...) work naturally via
fetch().  Remote URLs need CORS; raw.githubusercontent.com and
jsdelivr both work, github.com/.../raw/... does not.

### Wider default font

The baked-in default-font.hh was a narrow subset that didn't
include uppercase Latin, so `?text=Hello` shaped to .notdef for
H and W.  Re-subset Parastoo-Regular.ttf via hb-subset with:

    --unicodes='U+0020-007E,U+0600-06FF,U+FB50-FDFF,U+FE70-FEFF'

covering printable ASCII plus the Arabic block and the two
Arabic presentation-forms blocks.

Font size:
    source Parastoo-Regular.ttf     109152
    new subset                       49940

Wasm size impact (webgl build, Oz+lto):
    before  443628  181597 gz
    after   466657  196209 gz
    delta   +23029  +14612 gz

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 17:03:53 -06:00
Behdad Esfahbod 44a0fb1cd5 [util/gpu] Respect view-options: foreground, background, palette, custom-palette
Wires view_options_t into gpu_output_t so hb-gpu picks up the
same foreground/background/palette flags the rest of the tools
use:

  --foreground=#RRGGBB[AA]
  --background=#RRGGBB[AA]
  --font-palette=N
  --custom-palette=N=#RRGGBB[,N=#RRGGBB,...]

After demo_view_setup() the gpu main loop now:

1. Fetches the active palette from the face via
   demo_font_get_palette(font, view.palette, ...) -- palette index
   out of range falls back to 0.
2. Overlays each view.custom_palette_entries entry on top of that
   palette (clamped to 256 entries).
3. Uploads via renderer->set_palette().  Web demos and the
   headless WebGPU path do the same, with palette_index=0 (they
   don't yet plumb --font-palette).
4. Calls renderer->set_foreground / _background from the
   post-parsed view-options colours.  Defaults match the demo's
   prior LIGHT mode, so no-op when the user passes no flags; the
   dark-mode toggle (b key) still mutates renderer state
   independently.

Other view-options flags (--rainbow, --stroke, --line-space,
--margin, --logical/--ink, --show-extents, --font-extents)
appear in --help-view for familiarity but currently no-op in
hb-gpu; they're inherited wholesale from view_options_t and the
gpu path just doesn't wire them.

demo_font_get_palette() now takes a palette_index parameter so
callers can ask for non-zero palettes (e.g. dark-mode palettes in
fonts that ship them).  Web demos pass 0 for now.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:28:09 -06:00
Behdad Esfahbod cf3d69bc54 [util/gpu] Cross-backend palette upload via demo_renderer_t::set_palette
Reorganises the palette-upload plumbing so every backend handles
it uniformly and the hacky atlas-backend palette callback goes
away.

Before: demo_font_upload_palette in demo-font.cc mixed a GL
glUniform4fv direct call with a detour through an extra
demo_atlas_backend_t.upload_palette callback used by the Metal
renderer.  demo-font and demo-atlas both knew about palettes.

After:

* demo_font_get_palette (font, out, capacity) just reports the
  active palette as RGBA floats; demo-font no longer touches GL
  state or the atlas for palettes.

* demo_renderer_t gains a virtual set_palette (rgba, count).
  Default is a no-op.  Backends override:
   - demo-renderer-gl.cc -> demo_glstate_set_palette() ->
     glUniform4fv.
   - demo-metal.mm -> memcpy into the MTLBuffer's contents.
   - demo-renderer-d3d11.cc -> ID3D11DeviceContext::UpdateSubresource
     (palette buffer switched from IMMUTABLE to DEFAULT).
   - hb-gpu-web-webgpu.cc -> wgpuQueueWriteBuffer on the palette
     storage buffer.

* Callers invoke renderer->set_palette (palette, n) right after
  demo_font_create:
   - util/gpu-output.hh (desktop demo: GL / Metal / D3D11).
   - util/gpu/web/hb-gpu-web.cc (WebGL).
   - util/gpu/web/hb-gpu-web-webgpu.cc (WebGPU).

* The extra upload_palette field on demo_atlas_backend_t is
  removed along with demo_atlas_upload_palette / _is_external --
  atlas is back to being about glyph data only.

COLRv0 rendering now works with proper palette colours through
every backend that implements set_palette (WebGL, WebGPU, and
Metal/D3D11 once tested).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:19:13 -06:00
Behdad Esfahbod 9aec34108b [gpu] Fix Metal segfault: route palette upload through atlas backend
The Metal path creates a GLFW window with GLFW_NO_API (no GL
context), but demo_font_upload_palette() unconditionally called
glGetIntegerv(), causing a segfault on the first glyph lookup.

Split palette upload into GL and external-backend paths:

- Extract demo_font_get_palette() to read CPAL colors into a
  float array, shared by both paths.
- GL path (demo_font_upload_palette_gl) uploads via glUniform4fv
  as before.
- External-backend path uploads via a new upload_palette callback
  in demo_atlas_backend_t.
- Metal renderer implements the callback, writing palette data
  directly to its paletteBuffer.

This fixes the --metal crash and enables proper COLRv0 palette
color rendering on Metal.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:59:29 -06:00
Behdad Esfahbod dfd5d5b3cb [gpu] Paint: port to HLSL/WGSL; add _hb_gpu_draw_impl; fix WGSL
This commit unblocks end-to-end paint rendering on the WebGPU
demo, adds the HLSL port, and avoids losing MSAA or stem
darkening along the way.

### Shared: _hb_gpu_draw_impl

hb_gpu_draw internally did fwidth(renderCoord) + MSAA.  That works
fine in the single-call-per-fragment case but not when called from
inside a non-uniform branch (e.g. an op-stream LAYER_SOLID
conditional in the paint fragment shader) -- WGSL rejects fwidth
from non-uniform control flow.

Factor the MSAA-aware body into _hb_gpu_draw_impl, which takes a
caller-supplied pixelsPerEm.  hb_gpu_draw is now a thin wrapper
that computes pixelsPerEm via fwidth and delegates.  The paint
fragment shader in every language now computes pixelsPerEm once
at the top of hb_gpu_paint and calls _hb_gpu_draw_impl per layer
-- MSAA preserved, no redundant fwidth calls per layer.

In WGSL, _hb_gpu_draw_impl also inlines the ppem computation from
pixelsPerEm rather than recurring into hb_gpu_ppem (which itself
calls fwidth).

### Paint shaders

- hb-gpu-paint-fragment.hlsl (new): HLSL transcription.  Assumes
  a caller-declared StructuredBuffer<float4> hb_gpu_palette at
  register(t1).
- hb-gpu-paint-fragment.wgsl: switched from hb_gpu_draw to
  _hb_gpu_draw_impl; comment updated.
- hb-gpu-paint-fragment.msl, .glsl: same switch, cached
  pixelsPerEm at entry.

hb_gpu_paint_shader_source() now returns content for all four
languages.

### Demos

- util/gpu/demo-fragment.glsl: restores stem darkening (dropped in
  the first paint wiring commit); applies to the premultiplied
  RGBA by scaling both colour and alpha.  The desktop GL demo
  regenerates demo-fragment-glsl.hh from this source.
- util/gpu/web/hb-gpu-web-webgpu.cc: WGSL fs_main concatenates the
  paint source, binds a zero-filled palette storage buffer at
  @group(0) @binding(2), and restores stem darkening.  fwidth
  hoisted outside the stem-darkening conditional so WGSL's
  derivative-uniformity rule is happy.
- util/gpu/demo-renderer-d3d11.cc: HLSL ps_main switches to
  hb_gpu_paint.  Adds a second StructuredBuffer<float4>
  hb_gpu_palette at t1, zero-filled for now, bound alongside the
  atlas SRV.

### Misc

- perf/benchmark-gpu.cc: fix stale reset/encode(draw) calls.

Measured build (local Emscripten):
  WebGL   index.wasm  : 443638  181640 gz
  WebGPU  webgpu.wasm : 461626  188400 gz

COLRv0 rendering (BungeeTint, Noto Color Emoji, etc.) now works
end-to-end on WebGL and WebGPU with the correct palette.  Metal
and D3D11 demos should likewise compile against the new shader
flow; real palette upload cross-backend remains a TODO.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:52:21 -06:00
Behdad Esfahbod d5f07d72d0 [gpu] Port paint fragment shader to WGSL; wire WebGPU demo
WGSL transcription of the paint interpreter.  Takes the atlas and
palette as explicit storage-buffer pointer parameters (matching
the WGSL draw helper's calling convention):

  fn hb_gpu_paint (renderCoord: vec2f, glyphLoc: u32,
		   foreground: vec4f,
		   hb_gpu_atlas: ptr<storage, array<vec4<i32>>, read>,
		   hb_gpu_palette: ptr<storage, array<vec4f>, read>) -> vec4f

hb_gpu_paint_shader_source() now returns real content for
HB_GPU_SHADER_LANG_WGSL fragment; HLSL still stubs to "".

util/gpu/web/hb-gpu-web-webgpu.cc:
  - Concats the paint source alongside the draw source into the
    WGSL shader module.
  - Declares @group(0) @binding(2) for hb_gpu_palette.
  - Allocates a 256 * vec4f storage buffer (zero-filled for now;
    real palette upload is TODO), binds it at entry index 2.
  - Fragment main switches from hb_gpu_draw to hb_gpu_paint.

util/gpu/web/gl-stub.h: adds glUniform4fv stub (demo-font.cc now
calls it for the GL palette path) and makes
glGetUniformLocation return -1 so the WebGPU build's
demo_font_upload_palette short-circuits.

Wasm sizes:
  WebGL   index.wasm  : 443628  181597 gz
  WebGPU  webgpu.wasm : 461110  188045 gz

Non-color text should render through WebGPU.  COLRv0 color glyphs
come up transparent until the cross-backend palette upload lands.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:27:41 -06:00
Behdad Esfahbod 5e2b77d2ea [gpu] Port paint fragment shader to MSL; wire Metal demo
MSL transcription of the GLSL paint fragment interpreter.  Same
per-pixel op-stream walk and LAYER_SOLID SRC_OVER composite; the
only surface difference is that MSL's hb_gpu_fetch /
hb_gpu_paint take the atlas and palette as explicit buffer
pointer parameters (matching MSL's lack of globally-scoped
device-address-space globals).

  float4 hb_gpu_paint (float2 renderCoord, uint glyphLoc,
		       float4 foreground,
		       device const short4* hb_gpu_atlas,
		       constant float4* hb_gpu_palette);

hb_gpu_paint_shader_source() now returns a real string for
HB_GPU_SHADER_LANG_MSL fragment; vertex and WGSL/HLSL still stub
to "".

util/gpu/demo-metal.mm: concatenates the paint source alongside
the draw source into the Metal library, fragment_main switches
from hb_gpu_draw to hb_gpu_paint, and a 256-element palette
MTLBuffer is created + bound at fragment buffer index 2.  The
palette buffer is zero-filled for now; real palette upload from
the font's active palette is a follow-up (the GL path in
demo-font.cc uses glUniform4fv, which is GL-specific; a cleaner
cross-backend upload will come with the general palette plumbing).

Non-color text (u_foreground path) should render correctly on
Metal.  COLRv0 color glyphs will render transparent until the
palette upload lands -- ready for Mac smoke-testing.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:14:36 -06:00
Behdad Esfahbod 34a9f22f25 [util/gpu] Extract demo shaders into .glsl files
demo_vertex_glsl and demo_fragment_glsl were inline R"glsl(...)"
string literals in util/gpu/demo-shader.cc.  Pull them into
dedicated util/gpu/demo-{vertex,fragment}.glsl source files with
their own copyright headers, and wire the existing
gen-gpu-shader-artifacts.py generator to stringize them into
demo-*-glsl.hh at build time.

Also simplifies gen-gpu-shader-artifacts.py: the decl_map had
grown to cover every shader and its entries were all trivial
filename-to-symbol derivations.  Replace the map with direct
derivation (hyphens -> underscores, strip .hh), so adding more
shaders anywhere -- library or demo -- needs no generator edit.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:10:09 -06:00
Behdad Esfahbod f3fcd46ba9 [gpu] First working COLRv0 GPU render
Two paint-encoder bugs and two demo-plumbing bugs together
prevented end-to-end rendering.  With all four fixed, BungeeTint
and similar COLRv0 fonts now render through the GL demo in their
proper palette colors.

### Paint encoder

1. hb-gpu-paint-fragment.glsl: the LAYER_SOLID op's payload is a
   blob-relative texel offset, but the shader was passing it to
   hb_gpu_draw() as-is -- which treats its argument as an absolute
   atlas offset.  Add the glyph's `base` to the payload before the
   draw-coverage call so the sub-blob reference resolves inside
   the paint blob instead of elsewhere in the atlas.

2. hb-gpu-paint.cc push_clip_glyph callback: was resetting
   pending_palette_index to 0.  But harfbuzz's COLRv0 paint
   emitter calls custom_palette_color BEFORE push_clip_glyph for
   each layer, so the index set by custom_palette_color was being
   clobbered before the color callback consumed it -- every layer
   ended up tagged palette_index=0.  Leave pending_palette_index
   alone in push_clip_glyph.

### Demo plumbing

3. util/gpu/demo-glstate.cc: demo_glstate_create now glUseProgram's
   its program immediately.  The palette uniform upload reads
   GL_CURRENT_PROGRAM, and glyph upload happens from
   demo_buffer_current_line() -- which runs before
   demo_view_setup() would have bound the program.  Without this,
   glGetIntegerv returned 0 and the palette was never uploaded.

4. util/gpu/demo-font.cc: adds lazy demo_font_upload_palette() on
   first glyph request.  Also tries both "hb_gpu_palette" and
   "hb_gpu_palette[0]" for the uniform lookup since drivers
   disagree.

### Bonus

util/hb-gpu-encode-all.cc: reports paint-encoded and draw-fallback
counts / sizes / timings separately so you can tell where time
goes in mixed-content fonts.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:03:58 -06:00
Behdad Esfahbod 7c97464406 [gpu] encode-all: paint-first with draw fallback; skip empty clip glyphs
util/hb-gpu-encode-all.cc now exercises the paint encoder instead
of the draw encoder directly.  Every glyph is routed through
hb_gpu_paint_glyph + hb_gpu_paint_encode; on NULL result (v1
features not yet handled, or fully empty paint tree) it falls
back to hb_gpu_draw_glyph + hb_gpu_draw_encode.  Reports paint
encoded count separately from draw-fallback count.

hb_gpu_paint.cc: the color callback now checks the
hb_gpu_draw_glyph return value and skips the layer when the
clip-glyph has no outline, so fallback-synthesized LAYER_SOLIDs
for glyphs like U+0020 don't produce a 1-op blob that the shader
would sample as zero coverage anyway.

Sample run on BungeeTint-Regular.ttf (COLRv0, 2 layers/glyph):

  glyphs:   2126
  paint:    2126    (all routed through paint)
  empty:    0
  total:    8347.27 KiB
  avg:      3.93 KiB/glyph
  max:      10.84 KiB (gid 1005)
  paint:    13.10ms  (6.2us/glyph)
  encode:    0.27ms  (0.1us/glyph)
  wall:     13.53ms  (157185 glyphs/s)

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 14:41:44 -06:00