Repository navigation
feat(gfx): drawPolygon (Exact + ABuffer) from sutaburosu, with AVR TinyGL-ref root-cause fix - #5269
Conversation
Add Canvas::drawPolygon (plus free-function overloads) for filled arbitrary polygons with per-channel coverage (antialiasing) over the fl::gfx 16x16 s16x16 coordinate space. - PolyPoint<Coord> pair-struct vertex API (x, y in s16x16, clamped to +-8191 px at the boundary); span and C-array overloads; DrawMode (Overwrite/Blend) last, color-first, matching the other primitives. - Even-odd fill rule; vertices >= 3 required, more than 32 truncated. - Coverage kernel integrates each edge exactly against the pixel row: per-line exact T28 coverage via a 94-iteration 128-bit shift-subtract (integer math only, no FPU, no heap), sub-band splits at in-row vertices, exact x-ordering of edges per band, per-row 64-px chunk accumulators quantized once to u8. - Verified against an exact rational-arithmetic reference: 15 shapes byte-identical, parity within +-4 u8 vs 32x32 subsampling, energy within 1.0 px^2 of the shoelace area, sub-100 ms for 1000 pentagons. Tests: tests/fl/gfx/draw_polygon.hpp (42 checks) wired into gfx.cpp. Docs: src/fl/gfx/README.md quick start + edge-case + algorithm notes.
The antialiased drawPolygon (457b21d) rendered correctly but used a uniform 64-bit division kernel and division-based per-row edge extents that cost more AVR cycles and stack than necessary. This rebuilds the core around cheaper integer paths while keeping the rendered output byte-identical: - Split the row kernel into the three division regimes the original 16-bit kernel used (dhi >= 2 -> trivially full; dhi == 1 -> single compare; dhi == 0 -> 64-bit state machine with round-half-up), reproducing each regime's exact rounding. - Replace the per-row edge extent with the division-free shifts of the old box pass: lx0/lx1 = floorDiv16(ed.x +/- ed.hw), hw = ceil(32768*|B|/dy). - Add MAXN/CHUNK template tiers to bound the working set (CHUNK is an X-pixel chunk, not a row chunk; CHUNK must be a power of two). Defaults are unchanged (32, 64); embedded targets select smaller tiers for stack. - Correct the stack-size comments to values measured from the firmware ELF and document the budget. Output verified byte-identical: 15-shape xcheck plus a 200k- iteration randomized differential against the committed kernel, zero mismatches across all three division regimes. New tests: regime-targeted differential (40k-wide dhi=0 stream + 3x5k regime-targeted with per-iteration dhi pinning), division-regime pins, floor-div-by-16 shift pins, and a 16x16 end-to-end regression case.
A 16x8 matrix demo (128 WS2812; the canvas is a fl::CanvasRGB view directly over the LED array, no copy) that cycles six scenes, each exercising a different antialiased drawPolygon edge case: self-intersecting bowtie (even-odd fill), sub-pixel vertices (AA edge ramps), far off-canvas vertices (+/-8191 px clamp), a near-horizontal sliver (dy < 1 px over 13 px of x), degenerate polygons (must fill nothing), and vertices exactly on row centers. All coordinates are integer s16x16 Q16.16; no floats. Also prints a 16x8 hex brightness preview over Serial. Memory is measured from the final firmware ELF, not estimated: 943 B static image, 849 B stack, ~635 B deepest draw chain, leaving ~215 B headroom on the ATmega328P. That budget is why the demo uses the drawPolygon<,4,1> tier and a 16x8 canvas (a 16x16 canvas would leave ~465 B of stack against the 504 B core frame alone). Vertex tables live in PROGMEM and are staged through a 32 B RAM buffer before each draw.
`1 << 15`, `8191 << 16` and `1 << 28` are undefined behavior where `int` is 16 bits, and avr-gcc 7.3 silently collapses the latter two to 0. On the ATmega328P the effect is total: kPolyQ16Max = 0 clamps every vertex to the origin, kPolyOne = 0 collapses all coverage, and drawPolygon renders zero pixels. Verified with a cycle-accurate AVR trace of the built firmware: before the fix every PolyShow scene renders a blank frame; after, the even-odd/AA/clamp fills appear as expected. On 32/64-bit hosts the constants already fit in `int`, so this is a no-op there.
…e numbers Measure the built firmware instead of estimating: 943 B static image (.data 274 + .bss 669, ends 0x4AF), 1104 B of stack from the 0x8FF reset, and a deepest draw chain of 668 B from a cycle-accurate AVR trace (min SP 0x661, with the UART TX ISR preempting at the deepest point) — 434 B of headroom. The old header claimed a 16x16 canvas was impossible; with its 768 B LED array ~720 B of stack remains against the 668 B chain, tight (~50 B) but it fits.
…ath, exact-div fast path
The integer scanline kernel spent most of its AVR time in 64-bit
libgcc helpers (9.59M of 300M profiled cycles: __lshrdi3 5.17M,
__udivmod64 1.44M, __ashldi3 1.17M). Three kernel changes, all in
the dhi==0 / scanline path:
- A: per-row band prepass. The active-edge set, its polySortBand
midpoint order, and the band full-coverage value bfull = (b-a)<<12
depend only on the row and band bounds, never on the column chunk;
the committed code rebuilt and re-sorted each band for every chunk
(one i64 sort key per active edge per chunk, pure redundancy at
CHUNK==1). Now computed once per row.
- C1: the dhi==0 shift-subtract division loop is rewritten as 4 u32
lanes, removing per-iteration __lshrdi3/__ashldi3/__cmpdi2/
__subdi3 calls.
- C2: when mhi==0 && dlo<2^63 the shift-subtract loop is a provably
exact long division (remainder state stays < den, no 128-bit carry
drop; numerator < 2^64, no quotient wrap). Replace it with a single
64/64 division plus the same round-half-up and clamp.
- Row extent (xmin/xmax) is folded into the per-row edge-extent loop
as min-lx0/max-lx1 over all row-active edges, clamped once; rows
whose extent is empty (off-canvas polygon) skip the band prepass.
Measured on ATmega328P (cycle-accurate emulation, 300M cycles,
PolyShow 16x8, avr-gcc 7.3 -Os):
libgcc64 class 9,590,908 -> 2,204,043 (-77%)
draw+libgcc64 total 13,153,011 -> 5,976,002 (-55%)
per-scene (cyc): bowtie 1,943,035 -> 867,776 (2.24x)
subpixel 2,086,212 -> 903,838 (2.31x)
clamp 248,720 -> 212,256 (1.17x)
sliver 2,111,932 -> 889,798 (2.37x)
diamond 2,403,355 -> 1,035,596 (2.32x)
degenerate 191,475 -> 191,443 (1.00x,
scene-independent sketch millis() division)
Rendered output is byte-identical to the baseline firmware (2890 B
UART capture). 55,000-case randomized kernel differential fuzz is
bit-exact; host unit suite 366/366 on the final tree. Flash +1,460 B
(text 21,762 -> 23,222; .data/.bss unchanged); deepest draw chain
668 B -> 735 B (drawPolygonCore frame 316 B -> 564 B; min SP 0x61e,
headroom 367 B vs static end 0x4AF). PolyShow.ino budget comments
updated with the measured numbers.
The 16x8 (128 LED) 328P showcase now covers 20x20 (400 LEDs) and animates all six edge-case scenes. The larger canvas needs ~3.3 KB SRAM (1,805 B statics + 753 B max stack alongside the 1,200 B LED array), which overruns the 2 KB ATmega328P, so the example retargets to the ATmega2560; @filter keeps it on low-memory boards with >= 4 KB SRAM (the 2.5 KB ATmega32u4 "leonardo" is excluded). Animation is integer-only (s16x16 Q16.16, no floats): in-place rotation/scale/translate about the canvas center, advanced in fixed 20 ms sub-steps so angular speed is independent of the ~4.5-73 FPS render rate the scenes set. Measured by cycle-accurate trace of the built mega firmware (422.2 M cycles = 26.4 s simulated, 488 frames, all six scenes): flash 25,214 B / 248 KB (9.9%), static RAM 1,805 B / 8 KB (22%) max stack 753 B (734 B draw -> 64-bit libgcc chain + 19 B ISR nesting); headroom 5,630 B above the static end draw+libgcc64 per frame (cyc) and resulting frame rate: bowtie 1,995,422 -> 4.7 FPS (densest fill) subpixel 1,251,736 -> 7.3 FPS clamp 350,298 -> 21.3 FPS sliver 1,103,280 -> 8.2 FPS degenerate 2,971 -> 72.9 FPS (no-op draws over dim base) diamond 1,121,758 -> 8.2 FPS the rest of each frame is the 400-px WS2812 show (~194k cyc) plus loop/preview overhead Rendered frames verified over UART: even-odd bowtie with hollow self-intersection, degenerate scene leaves the dim base untouched, antialiased ramps on every slanted edge. PolyShow.wokwi.hex is the built mega firmware (Wokwi Arduino Mega 2560, 16 MHz, PIN_DATA = D3, 400 WS2812 row-major).
…efault The startup banner and the per-scene 20x20 brightness preview are now wrapped in POLYSHOW_SERIAL (default 0), so the default build compiles out the HardwareSerial code path and its ring buffers: flash 25,214 -> 23,480 B (mega 2560, -1,734 B) statics 1,805 -> 1,384 B; worst-case RAM 2,558 -> 2,124 B (32% -> 26%) max stack 753 -> 740 B (no UART TX ISR; 728 B draw -> libgcc64 chain + 12 B timer0 ISR nesting) Re-enable with -DPOLYSHOW_SERIAL=1: the on-build is byte-identical to the previously committed firmware, so its measured numbers still hold. The budget and @filter comments now describe the default (off) build; the committed wokwi hex is the off build.
Adds fl::gfx::PolyFill::ABuffer, an 8x4 A-buffer scanline fill for drawPolygon (src/fl/gfx/poly_abuffer.h, wired through canvas.h/primitives.h/gfx.h), a faithful C++ port of aykevl/tinygl's polygon fill as a benchmark reference (tests only, no public API), and the PolyKernels example: the six PolyShow scenes rendered with a selectable kernel (-DPOLY_KERNEL=0 Exact | 1 ABuffer | 2 TinyGL-ref) for side-by-side comparison. A meson sync test guards the example's copy of the reference header. Render-only benchmarks (avr8js simulation, 300M-instruction windows, 16 MHz; render = everything except FastLED.show() and the main loop; instruction steps per frame): ATmega2560, 20x20 canvas, 400 LEDs: scene Exact ABuffer TinyGL-ref speedup AB / ref bowtie 2,141,834 107,902 125,527 19.8x / 17.1x subpixel 1,388,937 126,025 105,430 11.0x / 13.2x clamp 378,760 90,315 51,186 4.2x / 7.4x sliver 1,214,603 56,016 71,215 21.7x / 17.1x degenerate 10,596 10,760 10,418 diamond 1,215,230 134,478 102,197 9.0x / 11.9x ATmega328P, 16x8 canvas, 128 LEDs: scene Exact ABuffer TinyGL-ref speedup AB / ref bowtie 1,517,555 54,612 67,384 27.8x / 22.5x subpixel 729,231 62,907 59,163 11.6x / 12.3x clamp 116,331 44,555 30,054 2.6x / 3.9x sliver 868,869 32,910 58,914 26.4x / 14.8x degenerate 12,447 12,485 12,362 diamond 678,150 70,983 60,280 9.6x / 11.3x Frame rates including show(): 2560 Exact 5-22 fps, ABuffer 43-58, TinyGL-ref 43-59; 328P Exact 10-98, ABuffer 136-202, TinyGL-ref 141-209 (degenerate scene is show-bound at ~74/264 fps for all kernels). ABuffer is fastest on fill-heavy scenes; the reference is fastest where long full-span runs hit its 8x32 fast path. Footprint (flash/RAM statics; worst-case stack per kernel): 2560 20x20: Exact 23,654/1,384 (stack 740 B), ABuffer 12,700/1,384 (408 B), ref 10,360/1,395 (232 B); 328P 16x8: Exact 23,318/552, ABuffer 12,364/552, ref 10,024/563 (stack up to 230 B). The .ino documents the 20x20 (~1.8 KB default / ~2.1 KB Exact; 1/2 KB boards excluded, leonardo thin) and 16x8 (~790 B worst case; fits 2 KB boards) budgets. Quality: ABuffer vs Exact per-pixel deltas max |dr| 37-77, mean <= 2.07 across the scene set; both antialiased kernels use the same 8x4 coverage grid, and the reference port matches ABuffer on the energy/diff parity tests. The TinyGL port needed four documented workarounds (deviations 5-7 in its header): a div-by-4 operand-inversion miscompile in clang-avr -Os (shift form), a loop-direction inversion miscompile (explicit countdowns), a stale edgeEndLeft register in the full-span fast path (volatile), and a 16-bit int truncation of the 0x7fffffff edge sentinel (32-bit runToRightEdge test). The Go reference itself is correct.
… vertices The ABuffer kernel filled a spurious even-odd tail past the far edge of polygons whose vertices sit mid-sub-row (the PolyKernels sketch's bowtie/subpixel scenes showed stray pixels outside the polygons). Two intertwined defects: - Sub-row double-claim. An edge was active on sub-row s for s in [floor(4*ytop), ceil(4*ybot)), so two edges sharing a mid-sub-row vertex both claimed the vertex's sub-row: three crossings on one sub-row, and the even-odd rule filled a spurious tail to the canvas edge. - Vertex-snapped DDA seed. x0 was seeded from the edge's top vertex snapped to the sub-row grid, shifting the edge's scan by up to a quarter sub-row of its slope — tens of px on the near-horizontal edges of the sketch's animated bowtie. Fix (reference-consistent, both xinc signs, no clamps): - A sub-row is active iff the edge's segment reaches the sub-row's TOP grid line: s in [ceil(4*ytop), ceil(4*ybot)). A vertex shared by two edges (on the grid or mid-sub-row) then belongs to exactly one of them (mid-sub-row: the edge that ends there), so no sub-row is claimed twice and the per-sub-row even-odd crossing set stays consistent. - Sub-row r's crossing is the edge's line at the sub-row's top grid line, measured exactly from the top vertex in Q16: x0 = xtop + floor((65536*py0 - ytop_q) * xinc / 65536), corr[r] = floor(((off*xinc mod 65536) + r*16384*(xinc&3)) / 65536). On-grid polygons render bit-identically to the previous kernel. Tests (tests/fl/gfx/draw_polygon_abuffer.hpp): - The independent oracle uses the same top-of-sub-row model (both xinc signs). - New regression scenes bowtie_r1/bowtie_r2: every vertex sits mid-sub-row with two edges sharing it — the geometry class that used to emit the stray tails. - The quality gate vs the Exact backend is now per-scene (PolyABTestScene.maxdLimit). The original "sliver" placement hits a documented committed limitation of the Exact backend: for a <1px-tall edge the crossing on its second row stays anchored at the first row's center, so the integrated line is shifted by a full row of slope (~29 px, off-canvas here) and Exact under-renders the band by up to ~0.5px^2 per pixel. The scene moved to a non-straddling placement where the exact side is exact (measured maxd 47 <= 80), and the original straddling geometry is pinned as sliver_straddle with a documented 120 limit (measured 107). examples/PolyKernels: refreshed the ATmega2560 wokwi hex from a clean rebuild with the fixed kernel (default kernel 1 = ABuffer).
The unified C++ linter flagged 27 violations that predate the PolyDemo example (none in new files); clear them so the branch lints green. src/fl/gfx: - poly_abuffer.h: vertex count as fl::i32 (int is 16-bit on AVR, so a >32767-vertex span would compare < 3 and no-op); int-template-ok on the intentional 16-bit int coordinate overload - primitives.h: the same fl::i32 count in the Exact path, the same int-template-ok on toQ16Clamped<int>, and lo_ -> low in the 128-bit helpers (trailing-underscore member style) tests/fl/gfx: - draw_polygon.hpp: replace the cmath double oracle with frozen literals (bit-identical to the glibc sin/cos values the runtime computed; the golden pixel checks pass unchanged), manual abs in the Shoelace area, and no function-local statics - draw_polygon_abuffer.hpp -> poly_abuffer.hpp: mirror the source path (src/fl/gfx/poly_abuffer.h); update the include in gfx.cpp ci/lint_cpp_rs: - add draw_polygon.hpp to TEST_PATH_EXCLUDED_FILES like its draw_ring/draw_line/draw_disc siblings (its source is primitives.h, which has no same-named header) bash lint: 27 -> 0 violations. bash test --cpp: 369/369 unit + 98/98 examples. AVR firmware for PolyDemo is bit-identical after the edits (32,132 B flash / 1,717 B RAM).
Six ~5 s additive scenes on a 20x20 WS2812 matrix with fade-to-black
transitions, all integer-only (s16x16 Q16.16 vertices, s16x16::sincos
motion, i64 products):
1. Kaleido - triangle orbiting one 60-degree sector, six table-
rotated exact-fold copies, hue per copy
2. Gasket - level-3 Sierpinski built by fill + black-erase, per-
level hue, three orbiting satellite triangles
3. Blob - 12-vertex polygon from two rotating 3x/5x harmonics
plus a counter-rotating 9-vertex inner blob
4. Knot - two mirrored self-intersecting 14-vertex 2:3 Lissajous
polygons, even-odd fill, drifting phases
5. Fireworks - deterministic radial petal bursts with decaying trails
6. Pinwheel - six rotating sail blades summing toward white at the
center
Options: -DPW/-DPH canvas override (scenes stage in 20x20 space),
-DPOLYDEMO_EXACT=1 swaps the Exact backend for an AA comparison,
-DPOLYDEMO_SERIAL=1 adds a startup banner + 20x20 brightness preview
(off by default). The default ABuffer build measures 31.4 KB flash /
1.7 KB RAM on the ATmega2560 (Exact+Serial: 46.3 KB / 1.9 KB);
PolyDemo.wokwi.hex is the default-build firmware for Wokwi.
Registered in the Experimental group manifest (meson example
discovery requires it).
… a miscompile The real AVR firmware compiler is avr-gcc 7.3 (-Os -flto); clang++ --target=avr appears only in fbuild's clangd-flavored compile_commands.json. Reproduced in simavr with both avr-gcc 7.3 and clang 21: the plain Go form hangs only because x = (int)edgeEndLeft truncates the 0x7fffffff sentinel to -1 on 16-bit int. - x-walk is explicitly i16 on every target; edge columns saturate to i16 (exact: vertices clamp to +-8191 px) and the sentinel is 0x7fff. - Restore the plain Go y/x loops; drop volatile edgeEndLeft (deviations 6/7 were misdiagnoses). - Keep the shift-form /4, documented as a speed choice (avr-gcc -Os emits a __divmodsi4 call for p / 4, ~3x slower), not a correctness fix. - Go int32 wrap adds now go through unsigned math (no signed-overflow UB). AVR (ATmega2560, simavr): pixels byte-identical to the previous kernel on all scenes, ~4% faster, 172 B smaller.
… template guards - drawPolygonCore: a row whose active edges all lie right of the canvas (xmin > xmax) skipped the band prepass but still ran the chunk loop, reading uninitialized bnc/bidx (out-of-bounds edge indices). Start the chunk loop past xmax in that case. - s16x16 vertices were passed through unclamped (+-32767 px), overflowing i32 edge deltas; clamp to +-8191 px like every other Coord type. - NaN float/double vertices hit a UB float->int cast; map NaN to 0. - One shared conversion (polyABToQ16) for both kernels instead of two copies. - FL_STATIC_ASSERT MAXN in [3, 256] (u8 edge indices) and CHUNK a power of two. - Drop the dead (br >= 255u) ? color : color ternary; fix the stack estimate. - Regression tests for the off-canvas-right row, NaN, and s16x16 clamping.
~55 ms idle against a 100 ms gate; the parallel full suite doubles it and fails. Raise it to 1 s, a pathological-regression smoke gate like the ABuffer benchmarks' host gates.
|
Caution Review failedThe pull request is closed. Walkthrough
Merge Risk:
|
Memory usage (this PR vs. its merge base)Change in
|
Integrates @sutaburosu's
feat/gfx-poly-abufferwork (from thesutaburosu/FastLEDfork; authorship of those commits is preserved), plus fixes found while integrating it.From sutaburosu's branch
drawPolygon: an antialiased polygon primitive with exact per-pixel area coverage (PolyFill::Exact) and an 8x4 A-buffer backend (PolyFill::ABuffer).tests/fl/gfx/poly_tinygl_ref.h).The AVR hang in the TinyGL reference kernel was not a compiler bug
The branch blamed a "clang-avr miscompile" and added three workarounds: rewritten
/4, countdown loops, and avolatile. The real cause was simpler:-Os -flto.clang++ --target=avronly appears in fbuild's clangd-flavoredcompile_commands.json; the actual commands are incompile_commands.raw.json.inton AVR.x = (int)edgeEndLefttruncates the0x7fffffff"no more edges" sentinel to -1, and the x-walk restarts at -1 forever.fl::i16: edge columns saturate to i16 and the sentinel is0x7fff. This is exact, because vertices are clamped to ±8191 px.volatileis removed./4stays, now documented as a speed choice: avr-gcc-Osemits a__divmodsi4call forp / 4, which makes the kernel about 3x slower.Review fixes (
/code-review)drawPolygonCore: when every active edge in a row was right of the canvas (xmin > xmax), the band prepass was skipped but the chunk loop still read the uninitializedbnc/bidx, an out-of-bounds stack read. The loop is now skipped too.polyABToQ16) instead of two copies.FL_STATIC_ASSERTnow checksMAXN∈ [3, 256] (edge indices are u8) and thatCHUNKis a power of two.Known follow-ups (not fixed here)
32*D*|B| >= 2^64,polyLineT28deliberately reproduces a carry-drop in an earlier quotient loop. That case needs edges of roughly 2900 px or more in both x and y. Fixing it changes the pinned outputs.MAXN=32Exact kernel uses about 4.2 KB of stack, more than an Uno has. AVR sketches must pick a smaller tier, as the examples do.Validation
bash test --cpp: 369/369 unit and 4/4 examples pass.bash test gfx --debug(ASan/UBSan) passes.bash lintis clean.bash compile mega --examples PolyKernels --defines POLY_KERNEL=2builds.Summary by CodeRabbit