Follow-up to 152aa0fd8c. The SVG branch of
hb_vector_paint_glyph divides the instance transform by
x_scale_factor/y_scale_factor (via
hb_vector_svg_append_instance_transform) so input-space
glyph paths land in the pixel-space viewBox. The PDF
branch emitted the raw paint matrix, which kept the CTM in
input space while the MediaBox lived in pixel space —
at any non-identity scale_factor, the glyph rendered
entirely outside the page.
Divide the matrix columns by sx/sy in the emitted cm so
PDF matches SVG. Covers hb-vector's font-size != 20 case
and the website's scale_factor = 64 case, where emoji
rendered blank at 72 px.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
hb_vector_{paint,draw}_set_extents stored caller-supplied
extents as-is, while per-glyph extents accumulated via
hb_vector_set_glyph_extents_common were divided by
scale_factor on the way in. When callers passed extents in
input-space (the natural unit alongside the glyph geometry
they're feeding) and a non-1 scale_factor, the resulting
viewBox didn't match what the glyphs drew.
Make set_extents divide by scale_factor too, matching the
accumulate path; callers can now pass input-space extents
uniformly.
Also:
* hb-vector-paint's global transform wrapper dropped the
redundant /scale_factor division. Each per-glyph
<use transform="... scale(1/scale_factor, ...)"> already
applies scale_factor; wrapping the body in another
/scale_factor matrix double-scaled the output, shrinking
color-glyph output to 1/scale_factor^2 of its intended
size. The wrapper now only fires when the user set a
non-identity paint->transform, and emits that transform
as-is.
* util/vector-output.hh simplification: now that set_extents
handles the divide, drop the local pre-multiply of extents
by upem_to_pixel -- pass the upem-space extents through.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* [gpu] Add hb_gpu_draw_line / _rect / _circle shape helpers
The GPU draw encoder already consumes arbitrary curves via the
hb_draw_funcs_t machinery -- that's how glyph outlines feed in.
Expose three convenience helpers so callers can emit common
shapes (tapered line, rectangle, circle) without having to
hand-roll the curve math:
hb_gpu_draw_line (draw, x0,y0,w0, x1,y1,w1);
hb_gpu_draw_rect (draw, x,y,w,h, stroke_width);
hb_gpu_draw_circle (draw, cx,cy,r, stroke_width);
stroke_width = NaN means "filled". A finite positive value
produces a stroked outline by emitting an outer contour CCW
and an inner contour CW so the fill rule carves a hole.
For shapes beyond these three helpers, callers can feed any
outline through hb_draw_move_to / _line_to / _quadratic_to /
_cubic_to / _close_path with the funcs from
hb_gpu_draw_get_funcs() and the hb_gpu_draw_t as data -- the
helpers are thin wrappers over that path.
Useful for game UI: health bars, progress rings, custom
line-art decorations, rendered through the same slug shader
as text.
Assisted-by: Claude <noreply@anthropic.com>
* [util/gpu] Add --show-extents flag
Exercises hb_gpu_draw_rect: when the flag is set, each glyph
blob encodes its ink-extent frame as an extra stroked
rectangle alongside the glyph outline, so the frame is cached
with the glyph and renders with no extra draw call.
The frame is padded outward by stroke_width / 2 so the stroke
sits entirely outside the glyph ink (otherwise the inner half
would knock out against the glyph shape, since both fill in
the same blob).
Cmdline-only for now -- a runtime 'e' toggle would require a
buffer re-shape hook that native hb-gpu doesn't yet expose.
Assisted-by: Claude <noreply@anthropic.com>
* [util/gpu] Cmdline toggles mirroring interactive keybindings
Add --dark / --no-vsync / --fullscreen / --no-stem-darken /
--debug so scripts and CI can start hb-gpu in any of the
states previously reachable only by pressing a key
interactively. Applied via the same keystroke path by
synthesizing the corresponding key characters through
demo_view_type() at startup -- single source of truth for
each toggle.
Assisted-by: Claude <noreply@anthropic.com>
* [draw] Promote shape helpers from hb-gpu-draw to hb-draw
Three shape-emitting helpers (line, rect, circle) operate on
any hb_draw_funcs_t, not specifically the GPU backend. Move
them out of the GPU-only API surface into the core hb-draw
API so any pen (raster, vector, gpu, user-supplied) gets
them.
API rename / move:
hb_gpu_draw_line -> hb_draw_line (in src/hb-draw.h)
hb_gpu_draw_rect -> hb_draw_rect
hb_gpu_draw_circle -> hb_draw_circle
Signatures gain a (dfuncs, draw_data, st) prefix to match the
existing hb_draw_move_to / line_to / cubic_to / close_path
shape -- the helpers are thin wrappers over those.
Callers in test/api/test-gpu.cc and util/gpu/demo-font.cc
updated to call hb_draw_* with hb_gpu_draw_get_funcs() and a
local hb_draw_state_t.
Updated harfbuzz-sections.txt with the new entries; removed
hb_gpu_draw_line / _rect / _circle from hb-gpu.h.
Assisted-by: Claude <noreply@anthropic.com>
* [draw] hb_draw_line: NaN second width defaults to first
Common case is a uniform-width line. Letting @w1 default to
@w0 when NaN is passed makes the call shorter:
hb_draw_line (..., x0, y0, 4, x1, y1, NAN); /* uniform 4 */
Mirrors the NaN-as-sentinel convention used in hb_draw_rect /
hb_draw_circle for the stroke_width parameter.
Assisted-by: Claude <noreply@anthropic.com>
* [draw] hb_draw_line: add cap parameter (butt / square)
Add hb_draw_line_cap_t enum with HB_DRAW_LINE_CAP_BUTT (the
existing default behavior) and HB_DRAW_LINE_CAP_SQUARE, which
extends each endpoint along the line direction by half its
local stroke width.
Square caps let four hb_draw_line() calls form a closed
rectangle without gaps at the corners -- a meaningfully
cheaper alternative to hb_draw_rect() for thin outlined
rectangles, since each line's bbox is just stroke_width tall
instead of covering the full rectangle interior.
Round caps not implemented yet; can be added as a third enum
value when a use case shows up.
Assisted-by: Claude <noreply@anthropic.com>
Two cleanups:
* Drop hb-gpu-paint's local reduce_linear_anchors and
normalize_stops, use the shared
hb_paint_reduce_linear_anchors() and
hb_paint_normalize_color_line() from hb-paint.hh. All
four backends (cairo, raster, vector, gpu) now share one
implementation.
* Rename the sweep-gradient tiler from hb_sweep_gradient_tiles
to hb_paint_sweep_gradient_tiles to match the namespace
convention of the other paint helpers.
No behavior change.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
SVG <stop offset="..."> requires offsets in [0, 1]. Out-of-
range stops were silently clamped by browsers, producing
visually wrong gradients for COLR fonts whose color lines
extend past those bounds.
Use the centralized hb_paint_normalize_color_line() to rescale
stops in place; shift the gradient axis (linear) / centers and
radii (radial) / start+end angles (sweep) by (mn, mx) along
the gradient axis to keep the visible gradient in the same
place.
Drop the now-unused local hb_vector_color_stop_cmp -- the
shared normalize helper sorts internally.
Regenerate the two affected basic.tests expected SVGs.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Same routine appeared in hb-cairo-utils and hb-raster-paint.
Move to hb-paint.hh as hb_paint_normalize_color_line() and
update both call sites. Behavior unchanged.
(hb-vector-paint and hb-gpu-paint still need normalization
work, separately.)
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
hb-cairo-utils and hb-raster-paint each carried their own
identical static copy of the COLR 3-anchor → 2-point gradient
projection. Drop both, use the shared
hb_paint_reduce_linear_anchors() added in the previous commit.
Behavior unchanged.
(hb-gpu-paint keeps its own copy intentionally -- it has
slightly different surrounding code paths and we don't want
to perturb the GPU encoder in this round.)
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
hb-vector-paint emitted (2*x1 - x2, 2*y1 - y2) as the SVG end
point -- the reflection of P2 about P1, not the projection.
For COLR linear gradients the SVG end should be P1 projected
onto the line through P0 perpendicular to (P2 - P0); that's
the gradient's actual axis (perpendicular to the rotation
line). With the old formula, fonts with rotation references
far from the color line ended up with massively over-scaled
gradient axes -- e.g. BungeeSpice's ABC showed solid red where
raster shows a full red->yellow gradient.
Add hb_paint_reduce_linear_anchors() to hb-paint.hh as the
shared canonical implementation (matches hb-raster-paint and
hb-cairo) and use it from hb-vector-paint.
Regenerate the two affected basic.tests expected SVGs; the
new gradient endpoints are now consistent with the cairo /
raster outputs.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Verb-then-thing matches the rest of the hb-vector setter/getter
naming (set_precision, set_palette, etc.). Update the renamed
internal references and the NEWS / harfbuzz-sections.txt entries
to match.
Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Flat mode disabled glyph reuse / caching to produce inline-
everything SVG output. Its main use case was making
hb-vector SVGs safe to concatenate side-by-side in a single
document, but the recently-added svg_set_prefix API solves
that without giving up the cache. No remaining callers in
tree (util/vector-output.hh's --flat option goes too).
Removes:
- hb_vector_draw_set_flat / get_flat
- hb_vector_paint_set_flat / get_flat
- the `flat` field on both contexts
- all `if (flat)` / `bool can_cache = !flat` branches
- the --flat option in util/vector-output.hh
- the four "flat*" expected files in test/vector/basic
- the flat_draw / flat_paint params in the vector fuzzer
- sections-list entries
meson test --no-rebuild green (241/241).
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
HB_LEAN was dropping GSUB/GPOS out of the subset output,
which turns subsetting Arabic / Indic / any complex-script
font into a paperweight: the produced subset has no layout
so it can't shape the text it was subsetted for. That's
not really "lean", that's broken for most non-Latin use.
Subset layout is load-bearing enough that it should stay in
any HB_LEAN / HB_TINY build. Callers that truly don't want
it can still #define HB_NO_SUBSET_LAYOUT themselves.
meson test --no-rebuild is green (241/241).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Missed one emission site in the SVG color-glyph path: when a
color glyph is first seen, hb-vector both defines it in
<defs id="cg<N>"> (which I prefixed) and emits an initial
<use href="#cg<N>"> in the body (which I did not). The mix
meant body refs for the first use of every color glyph went
unprefixed, so a caller-prefixed document had refs pointing
to nonexistent IDs and the whole image came out blank.
Fix: route that href="#cg<N>" through the prefix too.
Verified on Noto Emoji subset: rsvg-convert with a "v1-"
prefix now renders the full color glyph (was blank before).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
New public API for namespacing SVG output: callers that embed
multiple hb-vector-produced SVGs into the same document can
set a distinct id prefix per context, so hb-vector's short
internal IDs (p<N>, c<N>, clip-g<N>, gr<N>, cg<N>) don't
collide across snippets.
Example collision the new API prevents: page embeds two
hb-vector SVGs produced by different contexts. Both use
id="clip-g10"; the browser's url(#clip-g10) resolves to
whichever element appears first, so paint layers in the
second SVG get clipped against the first SVG's glyph outline
-- visible as giant unclipped color rects bleeding across
the wrong glyph shape.
With the new API the second caller passes e.g. "b-" as its
prefix; the clash disappears. Empty/NULL prefix preserves
the existing output byte-for-byte.
Affects every id / url(#...) / href="#..." emission in SVG
output:
- hb-vector-draw: <path id="p..."> + <use href="#p...">
- hb-vector-paint: <path>, <clipPath>, <linearGradient>,
<radialGradient>, <g id="cg..."> color-glyph cache, and
every corresponding url(#...) / href="#..." ref.
PDF output is unaffected (no ids).
Docs/harfbuzz-sections.txt updated; check-symbols passes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Flat output was still emitting <clipPath id="..."> into <defs>
and referencing them via clip-path="url(#...)". That meant
flat SVGs couldn't be safely concatenated: two documents'
short IDs (c0, clip-g10, ...) would collide and url(#c0)
resolves to whichever element appears first in document
order, producing the wrong clip and giant paint rects
falling through their clips.
SVG 2 lets clip-path take inline basic-shape or path()
values. In flat mode, emit:
push_clip_glyph -> clip-path="path('<glyph-d>')"
push_clip_rectangle -> clip-path="path('M..H..V..H..Z')"
...directly on the wrapping <g>, skipping defs entirely.
The resulting flat SVG truly has no defs for clips and is
safe to embed alongside other hb-vector output.
Gradients still use defs (paint servers need URL refs), but
those only affect color, not geometry -- a gradient
resolution mismatch yields wrong colors, never the
unclipped-rect bleed that was the visible symptom.
Verified on util/gpu/web/ / harfbuzz-world.cc's Noto color
emoji subset: no <clipPath> tags, no clip-path="url(...)",
69 inline clip-path="path('...')" refs instead. Meson
test --suite vector remains 22/22 green.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
src/harfbuzz-world.cc unconditionally #includes hb-number.cc,
hb-ot-cff1-table.cc, and hb-ot-cff2-table.cc in its core
group, then re-#includes the same three files in its
HB_HAS_SUBSET group (carried over from when the subset
library was its own translation unit). In the single-TU
amalgamation that's a redefinition error and prevents
HB_HAS_SUBSET from being enabled.
Wrap each file in the same HB_FOO_CC ifndef/define/ifdef
guard pattern already used by hb-static.cc and hb-zlib.cc, so
a second #include is a no-op.
Verified with a wasm build of harfbuzz-world.cc that has both
the core and subset blocks active, and a full meson test
run (241/241 OK) on the regular library build.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add hb_draw_line_cap_t enum with HB_DRAW_LINE_CAP_BUTT (the
existing default behavior) and HB_DRAW_LINE_CAP_SQUARE, which
extends each endpoint along the line direction by half its
local stroke width.
Square caps let four hb_draw_line() calls form a closed
rectangle without gaps at the corners -- a meaningfully
cheaper alternative to hb_draw_rect() for thin outlined
rectangles, since each line's bbox is just stroke_width tall
instead of covering the full rectangle interior.
Round caps not implemented yet; can be added as a third enum
value when a use case shows up.
Assisted-by: Claude <noreply@anthropic.com>
Common case is a uniform-width line. Letting @w1 default to
@w0 when NaN is passed makes the call shorter:
hb_draw_line (..., x0, y0, 4, x1, y1, NAN); /* uniform 4 */
Mirrors the NaN-as-sentinel convention used in hb_draw_rect /
hb_draw_circle for the stroke_width parameter.
Assisted-by: Claude <noreply@anthropic.com>
Three shape-emitting helpers (line, rect, circle) operate on
any hb_draw_funcs_t, not specifically the GPU backend. Move
them out of the GPU-only API surface into the core hb-draw
API so any pen (raster, vector, gpu, user-supplied) gets
them.
API rename / move:
hb_gpu_draw_line -> hb_draw_line (in src/hb-draw.h)
hb_gpu_draw_rect -> hb_draw_rect
hb_gpu_draw_circle -> hb_draw_circle
Signatures gain a (dfuncs, draw_data, st) prefix to match the
existing hb_draw_move_to / line_to / cubic_to / close_path
shape -- the helpers are thin wrappers over those.
Callers in test/api/test-gpu.cc and util/gpu/demo-font.cc
updated to call hb_draw_* with hb_gpu_draw_get_funcs() and a
local hb_draw_state_t.
Updated harfbuzz-sections.txt with the new entries; removed
hb_gpu_draw_line / _rect / _circle from hb-gpu.h.
Assisted-by: Claude <noreply@anthropic.com>
The GPU draw encoder already consumes arbitrary curves via the
hb_draw_funcs_t machinery -- that's how glyph outlines feed in.
Expose three convenience helpers so callers can emit common
shapes (tapered line, rectangle, circle) without having to
hand-roll the curve math:
hb_gpu_draw_line (draw, x0,y0,w0, x1,y1,w1);
hb_gpu_draw_rect (draw, x,y,w,h, stroke_width);
hb_gpu_draw_circle (draw, cx,cy,r, stroke_width);
stroke_width = NaN means "filled". A finite positive value
produces a stroked outline by emitting an outer contour CCW
and an inner contour CW so the fill rule carves a hole.
For shapes beyond these three helpers, callers can feed any
outline through hb_draw_move_to / _line_to / _quadratic_to /
_cubic_to / _close_path with the funcs from
hb_gpu_draw_get_funcs() and the hb_gpu_draw_t as data -- the
helpers are thin wrappers over that path.
Useful for game UI: health bars, progress rings, custom
line-art decorations, rendered through the same slug shader
as text.
Assisted-by: Claude <noreply@anthropic.com>
Previously clear() bailed outright under !successful, to protect
the Null singleton which lives in (possibly read-only) static
storage. That meant a real instance entering error state would
silently fail to clear, leaving stale contents for the next
caller.
Replace the `!successful` guard with an early-out on already-
empty state. The Null singleton is zero-initialized (population,
occupancy, mask all 0), so the early-out catches it before any
write. Any non-empty instance is by construction a real heap
object with writable storage, so clearing is safe there even
under !successful.
Assisted-by: Claude <noreply@anthropic.com>
The prior commit (2adb01a47c) made hb_bit_set_t::clear() always
zero length/population, parallel to the hb_vector_t::clear()
March fix. But hb_bit_set_t (and hb_hashmap_t) have a different
invariant: an instance returned from a failed create-or-reference
path is an inert / Null singleton in possibly read-only storage,
so clear() MUST bail on !successful or it would segfault.
This was exactly what the `if (unlikely (!successful)) return;`
guard was protecting. test-set caught the regression.
Vector is different: it has no Null singleton returned to users,
so always-clearing is safe there.
The graph/serialize.hh resize(0) -> clear() change from the same
commit is still correct -- that's a caller-supplied vector, not
a set.
Assisted-by: Claude <noreply@anthropic.com>
Two callers were still using vector.resize(0) to drop accumulated
data: graph/serialize.hh's overflow tracking and hb_bit_set_t's
clear() (via its own internal resize()). resize(0) on a vector
in error state short-circuits without zeroing length, leaving
stale entries that downstream code then walks as if valid.
Fix both:
- serialize.hh: call overflows->clear() instead.
- hb-bit-set.hh: reimplement clear() to zero length/population
unconditionally by calling pages.clear() / page_map.clear()
directly, bypassing the internal resize() that bails when
`successful` is false.
Mirrors the March clear() fix in hb-vector.hh (commit d134f88824).
Assisted-by: Claude <noreply@anthropic.com>
After the March refactor that made clear() a direct
shrink_vector(0), reset() going through resize(0) adds an
indirection (resize_full -> alloc(0) no-op -> shrink_vector(0))
for identical observable behavior. Use clear() directly.
Assisted-by: Claude <noreply@anthropic.com>
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>