Three accumulator vectors -- ops, sub_blobs, transform_stack --
can enter error state via failed push_or_fail() under
failing-malloc. Once in error state, resize(0) short-circuits
at the in_error() guard in alloc() and leaves length unchanged.
In hb_gpu_paint_clear that means the next iteration's clear
walks the stale entries again. For sub_blobs this is a
double-destroy: the blob pointers were already freed in the
previous clear, and hb_blob_destroy reads the dead ref_count
field -- heap-use-after-free.
Fix by calling vector.reset(), which clears the error state
before resizing to 0. Matches the pattern hb_gpu_draw_clear
already uses for draw->curves.
Found by oss-fuzz/CIFuzz on hb-gpu-fuzzer; minimized testcase
added to the fuzz corpus.
Assisted-by: Claude <noreply@anthropic.com>
The curve accumulator grew without bound, reaching 2.9 GB on
fuzzer-crafted inputs (VARC components expanded recursively, or
cu2qu subdivisions on degenerate cubics, or a glyf with absurd
contour counts). libFuzzer flags this as OOM.
Add HB_GPU_DRAW_MAX_CURVES = 0x10000 (65536) -- far above any
real glyph's needs -- and refuse to emit beyond it, flipping
success=false so the encoder returns a valid empty/failure
blob. Catches all upstream explosions (glyf / cu2qu / VARC /
any future source) at the single choke point.
Found by oss-fuzz/CIFuzz on hb-gpu-fuzzer.
Assisted-by: Claude <noreply@anthropic.com>
Two sites queried color-stop count, resized the scratch vector to
match, then called hb_color_line_get_color_stops() passing the
requested count as the write capacity. If the resize() failed
(OOM), the vector stayed at its previous (smaller) length while
the callee still wrote the full requested count -- heap-buffer-
overflow.
Fixed by checking resize() and bailing: build_gradient_function
returns 0, paint_sweep_gradient returns. Matches the pattern
already used in hb-raster-paint.cc and hb-vector-paint.cc.
Found by oss-fuzz/CIFuzz on hb-vector-fuzzer against a sweep-
gradient COLRv1 glyph under failing-malloc.
Assisted-by: Claude <noreply@anthropic.com>
hb_vector_t::push(args) returns &Crap(Type) on allocation failure,
not nullptr -- Crap is a static pool slot, always non-null. So
`!vec.push(item)` is *always* false and the cleanup branch never
fires. Use push_or_fail(), which is a bool-returning wrapper that
checks against the Crap address properly.
Under failing-malloc the five affected call sites would:
- leak the clip sub-blob in emit_clip_sub_blob (and its 1.9KB
draw-encoded buffer + 32-byte data-wrapper)
- leak the gradient parameters sub-blob in the three
emit_{linear,radial,sweep}_gradient paths
- silently ignore the overflow in push_transform
The blob leaks reproduce cleanly on oss-fuzz/CIFuzz (2056 bytes
in 6 allocations on the reported crash). Confirmed by running the
gpu tests after the fix.
Assisted-by: Claude <noreply@anthropic.com>
The LAYER_SOLID and LAYER_GRADIENT paths both walked the clip
stack (1-3 slug evaluations) inline, so the coverage logic was
duplicated across six call sites in each of GLSL, MSL, HLSL, and
WGSL. Hoist that walk into a single helper used by both ops.
Same behavior; cleaner surface; single place to edit if the clip
mask logic changes.
Assisted-by: Claude <noreply@anthropic.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
_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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
* hb_gpu_paint_glyph() switches from hb_font_paint_glyph_or_fail
to hb_font_paint_glyph so non-color glyphs also produce a blob
(harfbuzz synthesizes push_clip_glyph + color(is_foreground) +
pop_clip which our callbacks turn into a single LAYER_SOLID
op). Return value is now "no internal error" rather than
"glyph had color paint".
* util/gpu/demo-font.cc: drops the draw-only upload path and
routes every glyph through hb_gpu_paint_{clear,glyph,encode,
recycle_blob}. Uploads the active palette to the
hb_gpu_palette uniform array in demo_font_create.
* util/gpu/demo-shader.cc: concatenates hb_gpu_paint_shader_source
after the shared + draw sources, and the demo's fragment main
now calls hb_gpu_paint(texcoord, glyphLoc, u_foreground)
directly. Stem-darkening / debug overlay paths preserved
against the premultiplied alpha channel returned by paint.
MSL / WGSL / HLSL demo paths are unchanged for now -- the paint
shader is GLSL-only and those demos keep using the draw path.
wasm size impact (local Emscripten build):
baseline 412722 170342 gz
+HB_NO_COLOR/HB_NO_PAINT 437752 179165 gz
+demo paint wiring 443313 181502 gz
delta (vs baseline) +30591 +11160
All 241 tests pass.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Implements the paint-renderer fragment entry point
hb_gpu_paint(renderCoord, glyphLoc, foreground) -> vec4 as an
interpreter over the blob format documented in hb-gpu-paint.hh.
For this first slice only LAYER_SOLID ops are handled -- enough
to render COLRv0 color glyphs end to end once the demo is
rewired. LAYER_GRADIENT and PUSH/POP_GROUP cause the interpreter
to stop; COLRv1 support lands in follow-up commits.
The shader:
* Reads the blob header for num_ops and ops_offset.
* Walks the op stream. For each LAYER_SOLID it fetches the
clip-glyph coverage via hb_gpu_draw() (provided by
hb_gpu_draw_shader_source), looks up the color from
hb_gpu_palette[] or the caller-supplied foreground parameter
(per the is_foreground flag), and composites SRC_OVER.
hb_gpu_paint_shader_source() now returns the compiled source for
GLSL fragment; other languages and the vertex stage still return
"" until transcribed.
Wires meson.build and gen-gpu-shader-artifacts.py to generate the
.hh artifact.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Wire the paint-callback pipeline for COLRv0 color glyphs.
Adds:
* push_clip_glyph / pop_clip / color / custom_palette_color
callbacks. Each COLRv0 layer's push_clip_glyph is captured,
then the following color callback rasterizes the clip-glyph
outline through a scratch hb_gpu_draw_t, appends the resulting
Slug sub-blob, and emits a LAYER_SOLID op carrying the
palette_index (preserved via custom_palette_color) plus the
is_foreground flag. pop_clip clears the pending state.
* hb_gpu_paint_get_funcs(): cached singleton hb_paint_funcs_t via
the standard hb_paint_funcs_lazy_loader_t.
* hb_gpu_paint_glyph(): stashes the font scale and invokes
hb_font_paint_glyph_or_fail() with our funcs and a sentinel
foreground (the encoder never stores foreground -- the shader
resolves it per quad from a caller-supplied attribute).
* hb_gpu_paint_encode(): concatenates the 3-texel header, the op
stream, and the collected sub-blobs into one RGBA16I blob,
patching each op's sub_blob-index into an absolute texel
offset. Returns NULL when no layers accumulated or an
unsupported (v1) feature was seen.
* hb_gpu_paint_clear(): discards ops, sub-blobs, and pending
state while preserving the font scale.
The gradient / group / transform callbacks are not wired yet, so
COLRv1 paint graphs silently fall through -- callers should
precheck with hb_ot_color_glyph_has_paint() and route v1 glyphs
elsewhere (or fall back to draw).
Enables HB_NO_COLOR and HB_NO_PAINT in the web demo config
override so the wasm link resolves the new paint pipeline
symbols. Measured on a local Emscripten build:
raw wasm: 412722 -> 437752 (+25030 B, +6.1%)
gzip wasm: 170342 -> 179165 ( +8823 B, +5.2%)
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The stub called hb_font_paint_glyph_or_fail() with the empty paint
funcs just to get a truthful has-paint return value. That pulls in
hb_paint_funcs_get_empty from hb-paint.cc, which HB_LEAN strips out
of the wasm build, breaking the web demo link step.
Since the encoder is still a stub that accumulates nothing, there is
no reason to actually invoke the paint callback walk. Stash the
font scale and return false directly. When the real encoder lands
it will naturally pull in whichever paint symbols it needs.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Reserve the paint-encoder API shape and wire the demo to try the
paint path before falling back to draw. The encoder itself is
still a stub so the fallback always fires today; when the encoder
lands, color glyphs will flip automatically with no demo changes.
New public API:
hb_gpu_paint_glyph (paint, font, glyph)
Stashes the font scale on @paint and calls
hb_font_paint_glyph_or_fail() with hb_paint_funcs_get_empty()
so non-color glyphs report false. Returns the funcs call
result.
hb_gpu_paint_encode (paint, &extents)
Stub, returns NULL.
hb_gpu_paint_clear (paint)
hb_gpu_paint_reset (paint)
hb_gpu_paint_recycle_blob (paint, blob)
Stubs that preserve the right semantics. clear is a no-op
(no accumulator state yet), reset additionally zeroes the
stashed scale, recycle_blob hb_blob_destroys.
Adds x_scale / y_scale to hb_gpu_paint_t so glyph can stash them
for the encoder to consume later.
util/gpu/demo-font.cc:
- Creates a paired hb_gpu_paint_t alongside hb_gpu_draw_t.
- Per glyph: if the face has COLRv1 paint for the glyph, tries
hb_gpu_paint_glyph + hb_gpu_paint_encode. On NULL blob, falls
through to the existing draw path.
- Changes the per-iteration sync from _reset to _clear for both
draw and paint: _reset zeroes the font-scale config that
_glyph immediately re-populates, which wastes work and is
semantically wrong. _clear discards accumulator state while
preserving user config.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add a design-doc comment in hb-gpu-paint.hh pinning the model
before any encoder code lands:
* One blob per glyph, one quad per glyph. The fragment shader
walks a flat pre-order op stream and maintains a small (depth-4)
group stack to composite.
* Op types: LAYER_SOLID, LAYER_GRADIENT, PUSH_GROUP, POP_GROUP.
* Clip-glyph outlines are embedded as Slug-format sub-payloads
(same format hb_gpu_draw_encode produces). v1 bakes the full
paint transform into each outline; v2 may canonicalize and share
translate-only variants.
* Gradient parameters embedded as RGBA16I texels: inverse transform
in q15.16, type+extend, subtype params, color stops.
* Colors carry a (palette_index, flags, alpha_q15) triple rather
than resolved RGBA. Palette is a shader-side uniform array of
256 vec4; swapping palettes never requires re-encoding. The
encoder preserves palette indices through harfbuzz's paint
pipeline via a custom_palette_color_func that returns a sentinel
hb_color_t with the index encoded, decoded again in the color /
color-stop callbacks.
* Shader entry point:
vec4 hb_gpu_paint (vec2 renderCoord, uint glyphLoc,
vec4 foreground);
Foreground is an explicit parameter; the caller chooses whether
to source it from a uniform or a per-quad flat varying (per-quad
lets styled text runs render in one draw call).
* Out of scope for v1: RECT_CLIP ops (treated as hints, not
enforced), paint images.
No code yet. The skeleton hb_gpu_paint_t stays as a bare
hb_object_header_t; encoder state and public API additions come in
follow-up commits.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Each subsystem already had a dedicated source file for its C API;
having the shader-source getter live in a separate `*-shaders.cc`
was unnecessary. Merge:
hb-gpu-shaders.cc -> hb-gpu.cc
hb-gpu-draw-shaders.cc -> hb-gpu-draw.cc
hb-gpu-paint-shaders.cc -> hb-gpu-paint.cc
Each subsystem's .cc is now self-contained: the lifecycle, glyph
accumulation, and shader-source getter all live together.
The large stringized-shader .hh artifacts are included locally at
the bottom of each file, right above the function that uses them,
rather than with the primary includes at the top -- they are only
used by one function.
Updates meson.build, CMakeLists.txt, and harfbuzz-world.cc to
drop the removed files. All 241 tests still pass.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Reserve the API shape for the upcoming GPU color-glyph paint
encoder. The skeleton adds:
hb_gpu_paint_t opaque type
hb_gpu_paint_create_or_fail ()
hb_gpu_paint_reference ()
hb_gpu_paint_destroy ()
hb_gpu_paint_set_user_data () / _get_user_data ()
hb_gpu_paint_shader_source (stage, lang)
Only the lifecycle is functional. hb_gpu_paint_shader_source()
returns an empty string for all supported (stage, lang) pairs
until the paint-renderer shaders land.
This commit wires up the files, public declarations, section
index, and build system (meson, CMake, harfbuzz-world.cc,
vtable). Callers can now hold, reference, destroy, and attach
user data to a paint context.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The draw-renderer fragment shaders defined utilities
(HB_GPU_UNITS_PER_EM, the hb_gpu_atlas uniform, hb_gpu_fetch) that
any future GPU renderer will also need. The draw-renderer vertex
shader likewise contained only the generic hb_gpu_dilate helper.
If a paint renderer were added today and a caller linked both
fragment sources together, hb_gpu_fetch would be defined twice.
Move these shared helpers into a new family of sources and expose
them via a new public entry point:
hb_gpu_shader_source (stage, lang);
The existing hb_gpu_draw_shader_source() now returns only the
draw-specific fragment code; it returns an empty string for the
vertex stage because all current vertex logic is shared. Callers
concatenate the shared source first, then the draw-specific
source, then their own main():
[#version, hb_gpu_shader_source (...), hb_gpu_draw_shader_source
(...), main]
Additions:
- src/hb-gpu-fragment.{glsl,msl,wgsl,hlsl} — shared fragment
- src/hb-gpu-vertex.{glsl,msl,wgsl,hlsl} — shared vertex,
renamed from hb-gpu-draw-vertex.*
- src/hb-gpu-shaders.cc — hb_gpu_shader_source() dispatcher
Removals:
- src/hb-gpu-draw-vertex.{glsl,msl,wgsl,hlsl} — moved to common
Shared sources are Behdad-only copyright; the Eric Lengyel / Slug
attribution stays on the draw-specific fragment sources where the
Slug algorithm actually lives.
Updates: test/api/test-gpu.cc, the Metal/D3D11/WebGPU/GL demo
shaders, the hb-gpu SECTION documentation, meson.build,
CMakeLists.txt, gen-gpu-shader-artifacts.py decl_map,
harfbuzz-world.cc, and docs/harfbuzz-sections.txt.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* [subset] Return size_t rather than unsigned from get_size() methods
It's possible some get_size() computations during serialization
may overflow 32-bit arithmetic.
(The result of get_size() is used as size_t when allocating via
hb_serialize_context_t::extend(), but if the return value was
declared as unsigned int, the value may have wrapped resulting
in under-allocation.)
* [subset] Use size_t when accumulating subset_data_size
* [graph] Use size_t (rather than signed int64_t) for vertex_len variables
* Use size_t for sanitize_closure_t::stride to avoid narrowing
The function only reads the image; the internal
hb_raster_image_t::serialize_to_png_or_fail() method is already
declared const. Take a const pointer at the public API boundary.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
set_foreground, set_palette
Every storable setter on hb_vector_draw_t and hb_vector_paint_t
now has a matching getter, matching the symmetry already present
for transform/scale_factor/extents:
hb_vector_draw_get_flat ()
hb_vector_draw_get_precision ()
hb_vector_paint_get_flat ()
hb_vector_paint_get_precision ()
hb_vector_paint_get_foreground ()
hb_vector_paint_get_palette ()
set_glyph_extents has no getter companion since it does not store
its input; it transforms the glyph extents into the context's
pixel-space extents, which are already retrievable via
hb_vector_*_get_extents().
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>