@geastack/gea3d 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/gea3d",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Typed Three.js-style scene graph and native software 3D renderer for Gea devices",
6
6
  "exports": {
@@ -16,6 +16,7 @@
16
16
  #include "pixel.h"
17
17
 
18
18
  #include <algorithm>
19
+ #include <atomic>
19
20
  #include <climits>
20
21
  #include <cmath>
21
22
  #include <cstring>
@@ -37,6 +38,9 @@
37
38
  #include "freertos/FreeRTOS.h"
38
39
  #include "freertos/semphr.h"
39
40
  #include "freertos/task.h"
41
+ #include "esp_memory_utils.h"
42
+ #include "esp_heap_caps.h"
43
+ #include "freertos/idf_additions.h"
40
44
  #define GEA3D_ASYNC_PRESENT 1
41
45
  #else
42
46
  #define GEA3D_ASYNC_PRESENT 0
@@ -406,6 +410,21 @@ struct Renderer {
406
410
  };
407
411
 
408
412
  Renderer g_renderer;
413
+ // Bumped each time a frame slot is rebuilt; keys the per-frame strip lists.
414
+ std::uint32_t g_frameSerial[2] = {0, 0};
415
+ // Per frame slot, a content hash of each kBandHashRows-row band: what its
416
+ // primitives draw there, in draw order. A composited frame marks dirty only
417
+ // the bands that differ from the frame on screen.
418
+ // The band height is the painter's strip height when it stages strips
419
+ // (g_stripRowsHint), so dirty runs start where strips do and every strip
420
+ // reads one prebuilt band list; 8 rows until it is known.
421
+ constexpr int kBandHashRows = 8;
422
+ std::atomic<int> g_stripRowsHint{0};
423
+ int g_bandHashRows[2] = {kBandHashRows, kBandHashRows};
424
+ int g_shownBandHashRows = kBandHashRows;
425
+ std::vector<std::uint64_t> g_bandHash[2];
426
+ std::vector<std::uint64_t> g_shownBandHash;
427
+ bool g_shownBandHashValid = false;
409
428
 
410
429
  // Fast memory for the raster. On the STM32F7 the heap and framebuffers are
411
430
  // SDRAM (framebuffers write-through), so two band buffers fill the zero-wait
@@ -482,8 +501,13 @@ RayHit g_rayHit;
482
501
 
483
502
  // ---------------------------------------------------------------- helpers
484
503
 
504
+ #if GEA3D_XTENSA_FPU
505
+ // No float max on Xtensa: the builtin is an fmaxf call.
506
+ GEA3D_INLINE float maxFloat(float a, float b) { return a > b || b != b ? a : b; }
507
+ #else
485
508
  // VMAXNM on FPv5: no float compare stalls the pipeline.
486
509
  GEA3D_INLINE float maxFloat(float a, float b) { return __builtin_fmaxf(a, b); }
510
+ #endif
487
511
 
488
512
  // 0..255 by truncation; clamped in integer registers (USAT), not with float
489
513
  // compares.
@@ -610,7 +634,7 @@ GEA3D_INLINE float fogFactor(float distance)
610
634
  const Environment &env = g_renderer.environment;
611
635
  if (env.fog == 1) {
612
636
  if (env.fogFar <= env.fogNear) return 1.0f;
613
- return clampFloat((env.fogFar - distance) / (env.fogFar - env.fogNear), 0.0f, 1.0f);
637
+ return clampFloat((env.fogFar - distance) * raster::detail::reciprocal(env.fogFar - env.fogNear), 0.0f, 1.0f);
614
638
  }
615
639
  if (env.fog == 2) {
616
640
  const float d = env.fogDensity * distance;
@@ -644,14 +668,14 @@ GEA3D_INLINE void project(const View &v, float x, float y, float z, std::int32_t
644
668
  const float cy = p[1] * x + p[5] * y + p[9] * z + p[13];
645
669
  float cw = p[3] * x + p[7] * y + p[11] * z + p[15];
646
670
  if (cw < 0.000001f && cw > -0.000001f) cw = 0.000001f;
647
- const float invW = 1.0f / cw;
671
+ const float invW = raster::detail::reciprocal(cw);
648
672
  const float fx = clampFloat((cx * invW + 1.0f) * v.halfW, -kCoordLimit, kCoordLimit);
649
673
  const float fy = clampFloat((1.0f - cy * invW) * v.halfH, -kCoordLimit, kCoordLimit);
650
674
  *sx = roundToInt(fx * 16.0f);
651
675
  *sy = roundToInt(fy * 16.0f);
652
676
  if (v.orthographic) {
653
677
  const float range = v.far - v.near;
654
- *depth = range > 0.0f ? clampFloat(1.0f - (-z - v.near) / range, 0.0f, 1.0f) : 1.0f;
678
+ *depth = range > 0.0f ? clampFloat(1.0f - (-z - v.near) * raster::detail::reciprocal(range), 0.0f, 1.0f) : 1.0f;
655
679
  } else {
656
680
  *depth = clampFloat(v.near * invW, 0.0f, 1.0f);
657
681
  }
@@ -1390,6 +1414,7 @@ void sortFrame()
1390
1414
  Renderer &r = g_renderer;
1391
1415
  raster::Frame &frame = r.frame();
1392
1416
  const int n = frame.count;
1417
+ for (int i = 0; i < n; i++) raster::prepareTriangle(frame.prims[i]);
1393
1418
  frame.order.resize(static_cast<std::size_t>(n));
1394
1419
  r.keys.resize(static_cast<std::size_t>(n));
1395
1420
  r.bucketStarts.assign(2 * (kDepthBuckets + 1), 0);
@@ -1548,6 +1573,24 @@ void rasterizeInto(const raster::Frame &frame, Pixel *base, int stride, int x0,
1548
1573
 
1549
1574
  Bands &bands = g_renderer.bands;
1550
1575
  const int width = x1 - x0 + 1;
1576
+ #if GEA3D_ASYNC_PRESENT && !defined(GEA3D_BAND_ROWS)
1577
+ // A target in PSRAM (the ESP32-P4's swapped scanout buffers) takes the
1578
+ // raster in bands of internal RAM, painter's order, each copied out in one
1579
+ // sequential pass: coverage mode straight into PSRAM cost the CrowPanel 5.0
1580
+ // ~65 ms of a Lantern frame, the same figure painter's order in fast
1581
+ // memory cut to ~20 ms on the 7.0.
1582
+ if (width > bands.width && !esp_ptr_internal(base + static_cast<std::ptrdiff_t>(y0) * stride + x0)) {
1583
+ constexpr int kEspBandRows = 32;
1584
+ const int bandWidth = std::max(width, frame.width);
1585
+ Pixel *pixels = static_cast<Pixel *>(heap_caps_aligned_alloc(16, static_cast<std::size_t>(bandWidth) * kEspBandRows * sizeof(Pixel), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
1586
+ if (pixels) {
1587
+ if (bands.pixels) heap_caps_free(bands.pixels);
1588
+ bands.pixels = pixels;
1589
+ bands.width = bandWidth;
1590
+ bands.rows = kEspBandRows;
1591
+ }
1592
+ }
1593
+ #endif
1551
1594
  if (!bands.pixels || width > bands.width) {
1552
1595
  raster::Rasterizer rasterizer(frame, g_renderer.scratch, base, stride, x0, y0, x1, y1);
1553
1596
  rasterizer.run();
@@ -1589,6 +1632,92 @@ void rasterizeInto(const raster::Frame &frame, Pixel *base, int stride, int x0,
1589
1632
  #endif
1590
1633
  }
1591
1634
 
1635
+ #if GEA3D_ASYNC_PRESENT
1636
+ // A target in internal RAM (the display's staged strip) takes painter's order
1637
+ // straight into it: the background, then the region's primitives back to
1638
+ // front. Coverage mode suits slow target memory only; in fast memory its
1639
+ // per-pixel coverage bits, and the depth scratch it zeroes for every region
1640
+ // once anything blends, cost more than the overdraw they save (Neon Drift on
1641
+ // the CrowPanel 7.0: 66 -> 19.5 ms of raster a frame).
1642
+ // The UI paints the underlay in strips of one height, top to bottom, every
1643
+ // frame: each strip's primitives come from bands of that height built once
1644
+ // per frame, not from a scan of every primitive per strip.
1645
+ struct StripLists {
1646
+ const raster::Frame *frame = nullptr;
1647
+ std::uint32_t serial = 0;
1648
+ int rows = 0;
1649
+ Bands bands;
1650
+ };
1651
+ // One per frame slot: the build core fills the building frame's lists for
1652
+ // the strip height the painter last used (g_stripRowsHint), so the painter
1653
+ // core no longer spends ~0.75 ms a frame on them.
1654
+ StripLists g_stripLists[2];
1655
+ void prebuildStripLists(const raster::Frame &frame, int slot)
1656
+ {
1657
+ const int rows = g_stripRowsHint.load(std::memory_order_relaxed);
1658
+ if (rows <= 0 || slot < 0 || slot > 1) return;
1659
+ StripLists &cache = g_stripLists[slot];
1660
+ cache.bands.rows = rows;
1661
+ buildBandLists(frame, 0, frame.height - 1, cache.bands);
1662
+ cache.frame = &frame;
1663
+ cache.serial = g_frameSerial[slot];
1664
+ cache.rows = rows;
1665
+ }
1666
+
1667
+ bool rasterizePainterInPlace(const raster::Frame &frame, Pixel *base, int stride, int x0, int y0, int x1, int y1)
1668
+ {
1669
+ if (!esp_ptr_internal(base + static_cast<std::ptrdiff_t>(y0) * stride + x0)) return false;
1670
+ x1 = std::min(x1, frame.width - 1);
1671
+ y1 = std::min(y1, frame.height - 1);
1672
+ if (x0 > x1 || y0 > y1) return true;
1673
+
1674
+ const int rows = y1 - y0 + 1;
1675
+ // The tallest full-width strip is the staging height (a run's first and
1676
+ // last strips can be shorter; narrower boxes stage taller strips): the
1677
+ // next builds hash bands and prebuild lists at it.
1678
+ if (x0 == 0 && x1 == frame.width - 1 && rows > g_stripRowsHint.load(std::memory_order_relaxed)) g_stripRowsHint.store(rows, std::memory_order_relaxed);
1679
+ const std::ptrdiff_t slot = &frame - g_renderer.frames;
1680
+ raster::BandList list{nullptr, 0, 0};
1681
+ bool listed = false;
1682
+ if (slot >= 0 && slot < 2) {
1683
+ StripLists &cache = g_stripLists[slot];
1684
+ const std::uint32_t serial = g_frameSerial[slot];
1685
+ bool fresh = cache.frame == &frame && cache.serial == serial && cache.rows > 0;
1686
+ if (!fresh && y0 % rows == 0) {
1687
+ cache.bands.rows = rows;
1688
+ buildBandLists(frame, 0, frame.height - 1, cache.bands);
1689
+ cache.frame = &frame;
1690
+ cache.serial = serial;
1691
+ cache.rows = rows;
1692
+ fresh = true;
1693
+ }
1694
+ // Any strip inside one band reads that band's list (the build core
1695
+ // made it, at the staging height); the extra primitives clip away. A
1696
+ // strip across two bands (a UI dirty box moved its start) scans.
1697
+ if (fresh && y0 / cache.rows == y1 / cache.rows) {
1698
+ list = bandList(cache.bands, y0 / cache.rows);
1699
+ listed = true;
1700
+ }
1701
+ }
1702
+ if (!listed) {
1703
+ std::vector<std::int32_t> &items = g_renderer.bands.items;
1704
+ items.clear();
1705
+ int opaque = 0;
1706
+ for (int i = 0; i < frame.count; i++) {
1707
+ const int first = static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu);
1708
+ const int last = static_cast<std::int16_t>(frame.rows[i] >> 16);
1709
+ if (last < y0 || first > y1) continue;
1710
+ items.push_back(frame.order[static_cast<std::size_t>(i)]);
1711
+ opaque += i < frame.opaqueCount;
1712
+ }
1713
+ list = raster::BandList{items.data(), static_cast<int>(items.size()), opaque};
1714
+ }
1715
+ raster::Rasterizer rasterizer(frame, g_renderer.scratch, base, stride, x0, y0, x1, y1, raster::Occlusion::kPainter);
1716
+ rasterizer.runPainter(list);
1717
+ return true;
1718
+ }
1719
+ #endif
1720
+
1592
1721
  // Display::flushRectsRasterized chunk: pixels hold rows [oy, oy + h) of a
1593
1722
  // full-width band, so the chunk width is its stride.
1594
1723
  void rasterChunk(Pixel *pixels, int width, int height, int ox, int oy, void *user)
@@ -1672,18 +1801,78 @@ void paintUnderlay(int x0, int y0, int x1, int y1, void *user)
1672
1801
  if (x0 > x1 || y0 > y1) return;
1673
1802
 
1674
1803
  const int stride = canvas->strideBytes() / static_cast<int>(sizeof(Pixel));
1804
+ #if GEA3D_ASYNC_PRESENT
1805
+ if (rasterizePainterInPlace(*static_cast<const raster::Frame *>(user), canvas->pixels(), stride, x0, y0, x1, y1)) return;
1806
+ #endif
1675
1807
  rasterizeInto(*static_cast<const raster::Frame *>(user), canvas->pixels(), stride, x0, y0, x1, y1);
1676
1808
  }
1677
1809
 
1678
- bool presentUnderlay(raster::Frame &frame)
1679
- {
1680
- if (!gea::framework::display::Underlay::composited()) return false;
1681
-
1682
- auto *canvas = pd::Display::canvas();
1683
- if (!canvas || frame.width <= 0 || frame.height <= 0) return false;
1810
+ // The display's draw canvas for state only (the dirty box), where the target
1811
+ // splits it from pixel access. A double-buffered panel readies its back buffer
1812
+ // the first time Display::canvas() is asked for, copying every stale pixel in
1813
+ // from the front; asked here, before the UI's refresh can say it repaints the
1814
+ // whole frame, that was a full-screen PSRAM copy every frame.
1815
+ extern "C" gea::framework::graphics::Canvas *gea_display_state_canvas() __attribute__((weak));
1816
+
1817
+ // `hash` is the frame's band hashes, or null when it has none: then every
1818
+ // row is dirty. Rows whose bands match the frame on screen stay as they are,
1819
+ // so the UI repaints, recomposites and copies out only what moved.
1820
+ bool presentUnderlay(raster::Frame &frame, const std::vector<std::uint64_t> *hash = nullptr)
1821
+ {
1822
+ if (!gea::framework::display::Underlay::composited()) {
1823
+ g_shownBandHashValid = false;
1824
+ return false;
1825
+ }
1826
+
1827
+ auto *canvas = gea_display_state_canvas ? gea_display_state_canvas() : nullptr;
1828
+ if (!canvas) canvas = pd::Display::canvas();
1829
+ if (!canvas || frame.width <= 0 || frame.height <= 0) {
1830
+ g_shownBandHashValid = false;
1831
+ return false;
1832
+ }
1833
+
1834
+ // Changed bands as row runs; unchanged bands between them stay clean, so
1835
+ // a frame whose motion sits in a few separate bands repaints only those.
1836
+ constexpr int kMaxRuns = 8;
1837
+ int runFirst[kMaxRuns];
1838
+ int runLast[kMaxRuns];
1839
+ int runs = 0;
1840
+ const int hashRows = hash ? g_bandHashRows[hash == &g_bandHash[1] ? 1 : 0] : kBandHashRows;
1841
+ if (hash && g_shownBandHashValid && g_shownBandHashRows == hashRows && g_shownBandHash.size() == hash->size() && gea::framework::display::Underlay::active()) {
1842
+ const int bands = static_cast<int>(hash->size());
1843
+ for (int b = 0; b < bands; b++) {
1844
+ if ((*hash)[b] == g_shownBandHash[b]) continue;
1845
+ if (runs > 0 && runLast[runs - 1] == b - 1) {
1846
+ runLast[runs - 1] = b;
1847
+ } else if (runs < kMaxRuns) {
1848
+ runFirst[runs] = runLast[runs] = b;
1849
+ runs++;
1850
+ } else {
1851
+ runLast[runs - 1] = b; // out of runs: extend the last one
1852
+ }
1853
+ }
1854
+ for (int k = 0; k < runs; k++) {
1855
+ runFirst[k] *= hashRows;
1856
+ runLast[k] = std::min(frame.height - 1, (runLast[k] + 1) * hashRows - 1);
1857
+ }
1858
+ } else {
1859
+ runFirst[0] = 0;
1860
+ runLast[0] = frame.height - 1;
1861
+ runs = 1;
1862
+ }
1863
+ if (hash) {
1864
+ g_shownBandHash = *hash;
1865
+ g_shownBandHashRows = hashRows;
1866
+ g_shownBandHashValid = true;
1867
+ } else {
1868
+ g_shownBandHashValid = false;
1869
+ }
1684
1870
 
1685
1871
  gea::framework::display::Underlay::set(paintUnderlay, &frame, 0, 0, frame.width - 1, frame.height - 1);
1686
- canvas->markDirty(0, 0, frame.width - 1, frame.height - 1);
1872
+ // A background colour fills the frame before any triangle: every pixel of
1873
+ // it is written, so the UI's refresh need not restore what was there.
1874
+ gea::framework::display::Underlay::setOpaque(frame.background.mode != raster::kBackgroundNone);
1875
+ for (int k = 0; k < runs; k++) canvas->markDirty(0, runFirst[k], frame.width - 1, runLast[k]);
1687
1876
  return true;
1688
1877
  }
1689
1878
  #endif
@@ -1739,7 +1928,8 @@ void waitForPresent() {}
1739
1928
  #endif
1740
1929
 
1741
1930
  // Hands the built frame to its destination. Returns false when rejected.
1742
- bool present()
1931
+ // `hash`: the frame's band hashes, when it has them (drawScene builds).
1932
+ bool present(const std::vector<std::uint64_t> *hash = nullptr)
1743
1933
  {
1744
1934
  Renderer &r = g_renderer;
1745
1935
  raster::Frame &frame = r.frame();
@@ -1754,7 +1944,7 @@ bool present()
1754
1944
  #else
1755
1945
  #if GEA3D_UNDERLAY
1756
1946
  waitForPresent();
1757
- if (presentUnderlay(frame)) {
1947
+ if (presentUnderlay(frame, hash)) {
1758
1948
  r.stats.composited = 1;
1759
1949
  return true;
1760
1950
  }
@@ -1787,23 +1977,107 @@ void setBackground(raster::Background &background, double bgColor)
1787
1977
  std::memcpy(background.bottom, background.top, sizeof(background.top));
1788
1978
  }
1789
1979
 
1980
+
1981
+ #if GEA3D_ASYNC_PRESENT && GEA3D_UNDERLAY && !GEA3D_PRESENT_COMMANDS
1982
+ // Frame build on the other core. drawScene presents the frame built during
1983
+ // the previous call and hands this call's build to a task pinned beside the
1984
+ // display's row worker, below it in priority: the build (world matrices,
1985
+ // transform, clip, sort) overlaps the UI's strip loop instead of preceding it,
1986
+ // for one frame of latency. The build reads nodes, buffers, geometries and
1987
+ // materials and writes world matrices, so every other entry point waits for
1988
+ // it first; the painter reads only the shown frame, the band lists and the
1989
+ // raster scratch, none of which the build touches.
1990
+ #define GEA3D_ASYNC_BUILD 1
1991
+ extern "C" void gea_render_worker_block_when_idle(bool on) __attribute__((weak));
1992
+
1993
+ struct BuildJob {
1994
+ int scene = -1;
1995
+ int camera = -1;
1996
+ int width = 0;
1997
+ int height = 0;
1998
+ };
1999
+
2000
+ TaskHandle_t g_buildTask = nullptr;
2001
+ SemaphoreHandle_t g_buildWork = nullptr;
2002
+ SemaphoreHandle_t g_buildDone = nullptr;
2003
+ BuildJob g_buildJob;
2004
+ bool g_buildInFlight = false;
2005
+ // The presented frame's stats while the next build overwrites the live ones.
2006
+ Stats g_shownStats;
2007
+ bool g_buildFailed = false;
2008
+ // The slot holding a finished frame not yet presented, or -1.
2009
+ int g_readyFrame = -1;
2010
+
2011
+ void buildFrame(int scene, int camera, int width, int height);
2012
+
2013
+ void buildTaskMain(void *)
2014
+ {
2015
+ for (;;) {
2016
+ xSemaphoreTake(g_buildWork, portMAX_DELAY);
2017
+ buildFrame(g_buildJob.scene, g_buildJob.camera, g_buildJob.width, g_buildJob.height);
2018
+ g_renderer.stats.composited = 1;
2019
+ xSemaphoreGive(g_buildDone);
2020
+ }
2021
+ }
2022
+
2023
+ bool ensureBuildTask()
2024
+ {
2025
+ if (g_buildTask) return true;
2026
+ if (g_buildFailed) return false;
2027
+ g_buildFailed = true;
2028
+ g_buildWork = xSemaphoreCreateBinary();
2029
+ g_buildDone = xSemaphoreCreateBinary();
2030
+ if (!g_buildWork || !g_buildDone) return false;
2031
+ const BaseType_t core = xPortGetCoreID() == 0 ? 1 : 0;
2032
+ const UBaseType_t own = uxTaskPriorityGet(nullptr);
2033
+ const UBaseType_t priority = own > 1 ? own - 1 : 1;
2034
+ BaseType_t ok = xTaskCreatePinnedToCore(buildTaskMain, "gea3d_build", 8192, nullptr, priority, &g_buildTask, core);
2035
+ if (ok != pdPASS || !g_buildTask) {
2036
+ g_buildTask = nullptr;
2037
+ ok = xTaskCreatePinnedToCoreWithCaps(buildTaskMain, "gea3d_build", 8192, nullptr, priority, &g_buildTask, core, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
2038
+ }
2039
+ if (ok != pdPASS || !g_buildTask) {
2040
+ g_buildTask = nullptr;
2041
+ return false;
2042
+ }
2043
+ if (gea_render_worker_block_when_idle) gea_render_worker_block_when_idle(true);
2044
+ g_buildFailed = false;
2045
+ return true;
2046
+ }
2047
+
2048
+ void waitBuild()
2049
+ {
2050
+ if (!g_buildInFlight) return;
2051
+ xSemaphoreTake(g_buildDone, portMAX_DELAY);
2052
+ g_buildInFlight = false;
2053
+ }
2054
+
2055
+ #define GEA3D_SYNC_BUILD() waitBuild()
2056
+ #else
2057
+ #define GEA3D_ASYNC_BUILD 0
2058
+ #define GEA3D_SYNC_BUILD() ((void)0)
2059
+ #endif
2060
+
1790
2061
  } // namespace
1791
2062
 
1792
2063
  // ================================================================ buffers
1793
2064
 
1794
2065
  double createBuffer()
1795
2066
  {
2067
+ GEA3D_SYNC_BUILD();
1796
2068
  return allocate(g_buffers);
1797
2069
  }
1798
2070
 
1799
2071
  void deleteBuffer(double buffer)
1800
2072
  {
2073
+ GEA3D_SYNC_BUILD();
1801
2074
  Buffer *slot = lookup(g_buffers, buffer);
1802
2075
  if (slot) *slot = Buffer();
1803
2076
  }
1804
2077
 
1805
2078
  void bufferDataF32Raw(double buffer, const float *data, std::size_t count)
1806
2079
  {
2080
+ GEA3D_SYNC_BUILD();
1807
2081
  Buffer *slot = lookup(g_buffers, buffer);
1808
2082
  if (!slot) return;
1809
2083
  slot->f32.assign(data, data + count);
@@ -1812,6 +2086,7 @@ void bufferDataF32Raw(double buffer, const float *data, std::size_t count)
1812
2086
 
1813
2087
  void bufferDataU32Raw(double buffer, const std::uint32_t *data, std::size_t count)
1814
2088
  {
2089
+ GEA3D_SYNC_BUILD();
1815
2090
  Buffer *slot = lookup(g_buffers, buffer);
1816
2091
  if (!slot) return;
1817
2092
  slot->u32.assign(data, data + count);
@@ -1822,17 +2097,20 @@ void bufferDataU32Raw(double buffer, const std::uint32_t *data, std::size_t coun
1822
2097
 
1823
2098
  double createGeometry()
1824
2099
  {
2100
+ GEA3D_SYNC_BUILD();
1825
2101
  return allocate(g_geometries);
1826
2102
  }
1827
2103
 
1828
2104
  void deleteGeometry(double geometry)
1829
2105
  {
2106
+ GEA3D_SYNC_BUILD();
1830
2107
  Geometry *slot = lookup(g_geometries, geometry);
1831
2108
  if (slot) *slot = Geometry();
1832
2109
  }
1833
2110
 
1834
2111
  void geometryBuffers(double geometry, double position, double index, double color, double normal)
1835
2112
  {
2113
+ GEA3D_SYNC_BUILD();
1836
2114
  Geometry *slot = lookup(g_geometries, geometry);
1837
2115
  if (!slot) return;
1838
2116
  slot->position = static_cast<int>(position);
@@ -1844,17 +2122,20 @@ void geometryBuffers(double geometry, double position, double index, double colo
1844
2122
 
1845
2123
  double createMaterial()
1846
2124
  {
2125
+ GEA3D_SYNC_BUILD();
1847
2126
  return allocate(g_materials);
1848
2127
  }
1849
2128
 
1850
2129
  void deleteMaterial(double material)
1851
2130
  {
2131
+ GEA3D_SYNC_BUILD();
1852
2132
  Material *slot = lookup(g_materials, material);
1853
2133
  if (slot) *slot = Material();
1854
2134
  }
1855
2135
 
1856
2136
  void materialSet(double material, double shade, double r, double g, double b, double opacity, double side, double flags, double size)
1857
2137
  {
2138
+ GEA3D_SYNC_BUILD();
1858
2139
  Material *slot = lookup(g_materials, material);
1859
2140
  if (!slot) return;
1860
2141
  slot->shade = static_cast<int>(shade);
@@ -1870,6 +2151,7 @@ void materialSet(double material, double shade, double r, double g, double b, do
1870
2151
 
1871
2152
  double createNode(double kind)
1872
2153
  {
2154
+ GEA3D_SYNC_BUILD();
1873
2155
  const int id = allocate(g_nodes);
1874
2156
  g_nodes[static_cast<std::size_t>(id)].kind = static_cast<int>(kind);
1875
2157
  return id;
@@ -1877,6 +2159,7 @@ double createNode(double kind)
1877
2159
 
1878
2160
  void deleteNode(double node)
1879
2161
  {
2162
+ GEA3D_SYNC_BUILD();
1880
2163
  Node *slot = lookup(g_nodes, node);
1881
2164
  if (!slot) return;
1882
2165
 
@@ -1888,6 +2171,7 @@ void deleteNode(double node)
1888
2171
 
1889
2172
  void nodeParent(double node, double parent)
1890
2173
  {
2174
+ GEA3D_SYNC_BUILD();
1891
2175
  if (!lookup(g_nodes, node)) return;
1892
2176
 
1893
2177
  const int id = static_cast<int>(node);
@@ -1901,6 +2185,7 @@ void nodeParent(double node, double parent)
1901
2185
 
1902
2186
  void nodeTransform(double node, double px, double py, double pz, double qx, double qy, double qz, double qw, double sx, double sy, double sz)
1903
2187
  {
2188
+ GEA3D_SYNC_BUILD();
1904
2189
  Node *slot = lookup(g_nodes, node);
1905
2190
  if (!slot) return;
1906
2191
  const float position[3] = {static_cast<float>(px), static_cast<float>(py), static_cast<float>(pz)};
@@ -1920,6 +2205,7 @@ void nodeTransform(double node, double px, double py, double pz, double qx, doub
1920
2205
 
1921
2206
  void nodeMatrixRaw(double node, const float *elements, std::size_t count)
1922
2207
  {
2208
+ GEA3D_SYNC_BUILD();
1923
2209
  Node *slot = lookup(g_nodes, node);
1924
2210
  if (!slot || count < 16) return;
1925
2211
  // An unchanged matrix keeps the cached world matrices.
@@ -1932,6 +2218,7 @@ void nodeMatrixRaw(double node, const float *elements, std::size_t count)
1932
2218
 
1933
2219
  void nodeFlags(double node, double visible, double frustumCulled, double renderOrder)
1934
2220
  {
2221
+ GEA3D_SYNC_BUILD();
1935
2222
  Node *slot = lookup(g_nodes, node);
1936
2223
  if (!slot) return;
1937
2224
  slot->visible = visible != 0;
@@ -1941,6 +2228,7 @@ void nodeFlags(double node, double visible, double frustumCulled, double renderO
1941
2228
 
1942
2229
  void nodeGeometry(double node, double geometry, double material)
1943
2230
  {
2231
+ GEA3D_SYNC_BUILD();
1944
2232
  Node *slot = lookup(g_nodes, node);
1945
2233
  if (!slot) return;
1946
2234
  slot->geometry = static_cast<int>(geometry);
@@ -1949,6 +2237,7 @@ void nodeGeometry(double node, double geometry, double material)
1949
2237
 
1950
2238
  void nodeInstances(double node, double matrices, double colors, double count)
1951
2239
  {
2240
+ GEA3D_SYNC_BUILD();
1952
2241
  Node *slot = lookup(g_nodes, node);
1953
2242
  if (!slot) return;
1954
2243
  slot->instanced = true;
@@ -1959,6 +2248,7 @@ void nodeInstances(double node, double matrices, double colors, double count)
1959
2248
 
1960
2249
  void nodeLight(double node, double kind, double r, double g, double b, double intensity, double groundR, double groundG, double groundB, double distance, double decay)
1961
2250
  {
2251
+ GEA3D_SYNC_BUILD();
1962
2252
  Node *slot = lookup(g_nodes, node);
1963
2253
  if (!slot) return;
1964
2254
  slot->lightKind = static_cast<int>(kind);
@@ -1975,6 +2265,7 @@ void nodeLight(double node, double kind, double r, double g, double b, double in
1975
2265
 
1976
2266
  void nodeLightTarget(double node, double x, double y, double z)
1977
2267
  {
2268
+ GEA3D_SYNC_BUILD();
1978
2269
  Node *slot = lookup(g_nodes, node);
1979
2270
  if (!slot) return;
1980
2271
  slot->target[0] = static_cast<float>(x);
@@ -1984,6 +2275,7 @@ void nodeLightTarget(double node, double x, double y, double z)
1984
2275
 
1985
2276
  void cameraProjectionRaw(double node, const float *elements, std::size_t count, double near, double far)
1986
2277
  {
2278
+ GEA3D_SYNC_BUILD();
1987
2279
  Node *slot = lookup(g_nodes, node);
1988
2280
  if (!slot || count < 16) return;
1989
2281
  std::memcpy(slot->projection, elements, sizeof(slot->projection));
@@ -1993,6 +2285,7 @@ void cameraProjectionRaw(double node, const float *elements, std::size_t count,
1993
2285
 
1994
2286
  void sceneEnvironment(double scene, double background, double top, double bottom, double fog, double fogColor, double fogNear, double fogFar, double fogDensity)
1995
2287
  {
2288
+ GEA3D_SYNC_BUILD();
1996
2289
  Node *slot = lookup(g_nodes, scene);
1997
2290
  if (!slot) return;
1998
2291
 
@@ -2015,17 +2308,20 @@ void sceneEnvironment(double scene, double background, double top, double bottom
2015
2308
 
2016
2309
  void renderOptions(double depthBuffer, double capacity)
2017
2310
  {
2311
+ GEA3D_SYNC_BUILD();
2018
2312
  g_renderer.depthBuffer = depthBuffer != 0;
2019
2313
  if (capacity >= 64) g_renderer.capacity = static_cast<int>(capacity);
2020
2314
  }
2021
2315
 
2022
2316
  void renderTarget(double surface)
2023
2317
  {
2318
+ GEA3D_SYNC_BUILD();
2024
2319
  g_renderer.surface = static_cast<int>(surface);
2025
2320
  }
2026
2321
 
2027
2322
  double createSurface(double width, double height)
2028
2323
  {
2324
+ GEA3D_SYNC_BUILD();
2029
2325
  const int w = static_cast<int>(width);
2030
2326
  const int h = static_cast<int>(height);
2031
2327
  if (w <= 0 || h <= 0 || g_surfaces.count >= 8) return -1;
@@ -2045,36 +2341,145 @@ double createSurface(double width, double height)
2045
2341
  return id;
2046
2342
  }
2047
2343
 
2048
- double drawScene(double scene, double camera, double width, double height)
2344
+ namespace {
2345
+ GEA3D_INLINE std::uint64_t mixHash(std::uint64_t h, std::uint64_t v)
2346
+ {
2347
+ h ^= v + 0x9E3779B97F4A7C15ull + (h << 6) + (h >> 2);
2348
+ return h * 0xBF58476D1CE4E5B9ull;
2349
+ }
2350
+
2351
+ std::uint64_t primHash(const raster::Prim &p, bool opaque, bool withDepth, bool withKey)
2049
2352
  {
2050
- Node *sceneNode = lookup(g_nodes, scene);
2051
- Node *cameraNode = lookup(g_nodes, camera);
2052
- if (!sceneNode || !cameraNode) return 0;
2353
+ std::uint64_t h = 0xCBF29CE484222325ull;
2354
+ for (int k = 0; k < 3; k++) h = mixHash(h, (static_cast<std::uint64_t>(static_cast<std::uint32_t>(p.x[k])) << 32) | static_cast<std::uint32_t>(p.y[k]));
2355
+ h = mixHash(h, static_cast<std::uint64_t>(p.r[0]) | static_cast<std::uint64_t>(p.r[1]) << 8 | static_cast<std::uint64_t>(p.r[2]) << 16 |
2356
+ static_cast<std::uint64_t>(p.g[0]) << 24 | static_cast<std::uint64_t>(p.g[1]) << 32 | static_cast<std::uint64_t>(p.g[2]) << 40 |
2357
+ static_cast<std::uint64_t>(p.b[0]) << 48 | static_cast<std::uint64_t>(p.b[1]) << 56);
2358
+ h = mixHash(h, static_cast<std::uint64_t>(p.b[2]) | static_cast<std::uint64_t>(p.type) << 8 | static_cast<std::uint64_t>(p.flags) << 16 |
2359
+ static_cast<std::uint64_t>(p.alpha) << 24 | static_cast<std::uint64_t>(p.width) << 32 | static_cast<std::uint64_t>(p.color) << 40 |
2360
+ static_cast<std::uint64_t>(opaque) << 56);
2361
+ if (withDepth) {
2362
+ std::uint32_t d[3];
2363
+ std::memcpy(d, p.depth, sizeof(d));
2364
+ h = mixHash(h, (static_cast<std::uint64_t>(d[0]) << 32) | d[1]);
2365
+ h = mixHash(h, d[2]);
2366
+ }
2367
+ if (withKey) {
2368
+ std::uint32_t key;
2369
+ std::memcpy(&key, &p.key, sizeof(key));
2370
+ h = mixHash(h, key);
2371
+ }
2372
+ return h;
2373
+ }
2374
+
2375
+ // Band hashes of a sorted frame. Depth matters only to a depth-tested frame,
2376
+ // and the sort key only where blended primitives interleave by it.
2377
+ void hashBands(const raster::Frame &frame, std::vector<std::uint64_t> &out, int bandRows)
2378
+ {
2379
+ const int bands = frame.height > 0 ? (frame.height + bandRows - 1) / bandRows : 0;
2380
+ std::uint64_t seed = mixHash(0x84222325CBF29CE4ull, static_cast<std::uint64_t>(frame.width) << 32 | static_cast<std::uint32_t>(frame.height));
2381
+ const raster::Background &bg = frame.background;
2382
+ seed = mixHash(seed, static_cast<std::uint64_t>(bg.mode) | static_cast<std::uint64_t>(bg.top[0]) << 8 | static_cast<std::uint64_t>(bg.top[1]) << 16 |
2383
+ static_cast<std::uint64_t>(bg.top[2]) << 24 | static_cast<std::uint64_t>(bg.bottom[0]) << 32 |
2384
+ static_cast<std::uint64_t>(bg.bottom[1]) << 40 | static_cast<std::uint64_t>(bg.bottom[2]) << 48 |
2385
+ static_cast<std::uint64_t>(frame.depthBuffer) << 56);
2386
+ out.assign(static_cast<std::size_t>(bands), seed);
2387
+ const bool withDepth = frame.depthBuffer;
2388
+ const bool withKey = frame.blendCount > 0;
2389
+ for (int i = 0; i < frame.count; i++) {
2390
+ const int first = maxInt(static_cast<std::int16_t>(frame.rows[i] & 0xFFFFu), 0);
2391
+ const int last = minInt(static_cast<std::int16_t>(frame.rows[i] >> 16), frame.height - 1);
2392
+ if (first > last) continue;
2393
+ const std::uint64_t h = primHash(frame.prims[frame.order[static_cast<std::size_t>(i)]], i < frame.opaqueCount, withDepth, withKey);
2394
+ for (int b = first / bandRows; b <= last / bandRows; b++) out[static_cast<std::size_t>(b)] = mixHash(out[static_cast<std::size_t>(b)], h);
2395
+ }
2396
+ }
2053
2397
 
2398
+ // Builds the scene into frames[building] (no present).
2399
+ void buildFrame(int scene, int camera, int width, int height)
2400
+ {
2401
+ Node &sceneNode = g_nodes[static_cast<std::size_t>(scene)];
2402
+ Node &cameraNode = g_nodes[static_cast<std::size_t>(camera)];
2054
2403
  Renderer &r = g_renderer;
2055
- beginFrameState(static_cast<int>(width), static_cast<int>(height));
2404
+ beginFrameState(width, height);
2056
2405
  r.legacyActive = false;
2057
2406
  raster::Frame &frame = r.frame();
2058
- r.environment = sceneNode->environment;
2407
+ r.environment = sceneNode.environment;
2059
2408
  frame.background = r.environment.background;
2060
2409
 
2061
- collect(static_cast<int>(scene));
2410
+ collect(scene);
2062
2411
 
2063
- ensureWorld(static_cast<int>(camera));
2064
- math::invertAffine(r.view.view, cameraNode->world);
2065
- setProjection(cameraNode->projection, cameraNode->near, cameraNode->far);
2412
+ ensureWorld(camera);
2413
+ math::invertAffine(r.view.view, cameraNode.world);
2414
+ setProjection(cameraNode.projection, cameraNode.near, cameraNode.far);
2066
2415
 
2067
2416
  for (const int id : r.lightNodes) addLight(g_nodes[static_cast<std::size_t>(id)]);
2068
2417
  for (const int id : r.drawables) drawNode(g_nodes[static_cast<std::size_t>(id)]);
2069
2418
 
2070
2419
  sortFrame();
2071
- const int count = frame.count;
2072
- return present() ? count : -1;
2420
+ r.stats.primitives = frame.count;
2421
+ {
2422
+ const int hint = g_stripRowsHint.load(std::memory_order_relaxed);
2423
+ g_bandHashRows[r.building] = hint >= 4 && hint <= 32 ? hint : kBandHashRows;
2424
+ }
2425
+ hashBands(frame, g_bandHash[r.building], g_bandHashRows[r.building]);
2426
+ g_frameSerial[r.building]++;
2427
+ #if GEA3D_ASYNC_PRESENT
2428
+ prebuildStripLists(frame, r.building);
2429
+ #endif
2430
+ }
2431
+ } // namespace
2432
+
2433
+ double drawScene(double scene, double camera, double width, double height)
2434
+ {
2435
+ GEA3D_SYNC_BUILD();
2436
+ if (!lookup(g_nodes, scene) || !lookup(g_nodes, camera)) return 0;
2437
+ const int sceneId = static_cast<int>(scene);
2438
+ const int cameraId = static_cast<int>(camera);
2439
+ const int w = static_cast<int>(width);
2440
+ const int h = static_cast<int>(height);
2441
+ Renderer &r = g_renderer;
2442
+
2443
+ #if GEA3D_ASYNC_BUILD
2444
+ if (r.surface < 0 && gea::framework::display::Underlay::composited() && ensureBuildTask()) {
2445
+ if (g_readyFrame < 0) {
2446
+ // First frame (or after a synchronous one): nothing built ahead.
2447
+ waitForPresent();
2448
+ buildFrame(sceneId, cameraId, w, h);
2449
+ g_readyFrame = r.building;
2450
+ }
2451
+ raster::Frame &shown = r.frames[g_readyFrame];
2452
+ if (shown.width != w || shown.height != h || !presentUnderlay(shown, &g_bandHash[g_readyFrame])) {
2453
+ g_readyFrame = -1;
2454
+ } else {
2455
+ const int count = shown.count;
2456
+ g_shownStats = r.stats;
2457
+ g_shownStats.composited = 1;
2458
+ r.building = g_readyFrame ^ 1;
2459
+ g_buildJob = BuildJob{sceneId, cameraId, w, h};
2460
+ g_buildInFlight = true;
2461
+ g_readyFrame = r.building;
2462
+ xSemaphoreGive(g_buildWork);
2463
+ return count;
2464
+ }
2465
+ } else {
2466
+ g_readyFrame = -1;
2467
+ }
2468
+ #endif
2469
+
2470
+ buildFrame(sceneId, cameraId, w, h);
2471
+ const int count = r.frame().count;
2472
+ return present(&g_bandHash[r.building]) ? count : -1;
2073
2473
  }
2074
2474
 
2075
2475
  double stat(double which)
2076
2476
  {
2477
+ // The shown frame's counts: no wait for the build running ahead.
2478
+ #if GEA3D_ASYNC_BUILD
2479
+ const Stats &s = g_buildInFlight ? g_shownStats : g_renderer.stats;
2480
+ #else
2077
2481
  const Stats &s = g_renderer.stats;
2482
+ #endif
2078
2483
  switch (static_cast<int>(which)) {
2079
2484
  case 0: return s.submitted;
2080
2485
  case 1: return s.nearRejected;
@@ -2093,6 +2498,7 @@ double stat(double which)
2093
2498
 
2094
2499
  double raycast(double node, double ox, double oy, double oz, double dx, double dy, double dz, double near, double far)
2095
2500
  {
2501
+ GEA3D_SYNC_BUILD();
2096
2502
  Node *slot = lookup(g_nodes, node);
2097
2503
  if (!slot || slot->kind != kNodeMesh) return 0;
2098
2504
  Geometry *geometry = lookup(g_geometries, slot->geometry);
@@ -2163,6 +2569,7 @@ double raycast(double node, double ox, double oy, double oz, double dx, double d
2163
2569
 
2164
2570
  double rayResult(double which)
2165
2571
  {
2572
+ GEA3D_SYNC_BUILD();
2166
2573
  switch (static_cast<int>(which)) {
2167
2574
  case 0: return g_rayHit.distance;
2168
2575
  case 1: return g_rayHit.point[0];
@@ -2178,6 +2585,7 @@ double rayResult(double which)
2178
2585
 
2179
2586
  void beginFrameRaw(const float *projection, std::size_t count, double near, double bgColor, double viewportW, double viewportH)
2180
2587
  {
2588
+ GEA3D_SYNC_BUILD();
2181
2589
  Renderer &r = g_renderer;
2182
2590
  beginFrameState(static_cast<int>(viewportW), static_cast<int>(viewportH));
2183
2591
  r.legacyActive = true;
@@ -2191,6 +2599,7 @@ void beginFrameRaw(const float *projection, std::size_t count, double near, doub
2191
2599
 
2192
2600
  void ambientLight(double r, double g, double b)
2193
2601
  {
2602
+ GEA3D_SYNC_BUILD();
2194
2603
  Lights &lights = g_renderer.lights;
2195
2604
  lights.ambient[0] += static_cast<float>(r);
2196
2605
  lights.ambient[1] += static_cast<float>(g);
@@ -2199,6 +2608,7 @@ void ambientLight(double r, double g, double b)
2199
2608
 
2200
2609
  void directionalLight(double x, double y, double z, double r, double g, double b)
2201
2610
  {
2611
+ GEA3D_SYNC_BUILD();
2202
2612
  Lights &lights = g_renderer.lights;
2203
2613
  float direction[3] = {static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)};
2204
2614
  if (lights.directionalCount >= kMaxLights || !math::normalize3(direction)) return;
@@ -2221,6 +2631,7 @@ void drawElementsRaw(double positionBuffer,
2221
2631
  double baseB,
2222
2632
  double doubleSide)
2223
2633
  {
2634
+ GEA3D_SYNC_BUILD();
2224
2635
  if (!g_renderer.legacyActive || modelViewCount < 16) return;
2225
2636
  const Buffer *positions = bufferAt(static_cast<int>(positionBuffer));
2226
2637
  if (!positions) return;
@@ -2251,6 +2662,7 @@ void drawElementsRaw(double positionBuffer,
2251
2662
 
2252
2663
  double endFrame()
2253
2664
  {
2665
+ GEA3D_SYNC_BUILD();
2254
2666
  if (!g_renderer.legacyActive) return 0;
2255
2667
  g_renderer.legacyActive = false;
2256
2668
  sortFrame();
@@ -29,6 +29,7 @@
29
29
 
30
30
  #include <cstdint>
31
31
  #include <cstring>
32
+ #include <utility>
32
33
  #include <vector>
33
34
 
34
35
  #if defined(__GNUC__) || defined(__clang__)
@@ -51,6 +52,7 @@ enum PrimFlag : std::uint8_t {
51
52
  kSmooth = 1, // per-vertex colours interpolated across the primitive
52
53
  kBlend = 2, // alpha-blended (drawn back-to-front after the opaque pass)
53
54
  kAdd = 4, // with kBlend: added to the pixel (scaled by alpha), not mixed
55
+ kPrepared = 8, // triangle: corners sorted by y, edges set up (prepareTriangle)
54
56
  };
55
57
 
56
58
  // Screen coordinates are 28.4 fixed point; depth is near/w in (0, 1], larger
@@ -71,6 +73,10 @@ struct Prim {
71
73
  std::int16_t rowY1;
72
74
  // Painter's key: view distance of the primitive's farthest vertex.
73
75
  float key;
76
+ // With kPrepared: edges 0->2, 0->1, 1->2 of the y-sorted corners, as
77
+ // x at the edge's first row centre and step per row (16.16 px).
78
+ std::int32_t edgeX[3];
79
+ std::int32_t edgeStep[3];
74
80
  };
75
81
 
76
82
  enum BackgroundMode : std::uint8_t {
@@ -135,18 +141,55 @@ struct Scratch {
135
141
  int dirtyLast = -1;
136
142
  };
137
143
 
144
+
138
145
  namespace detail {
139
146
 
140
147
  GEA3D_INLINE int minInt(int a, int b) { return a < b ? a : b; }
141
148
  GEA3D_INLINE int maxInt(int a, int b) { return a > b ? a : b; }
149
+ #if defined(__XTENSA__) && !defined(__XTENSA_SOFT_FLOAT__)
150
+ // Xtensa's FPU has no min/max: the builtins become fminf/fmaxf calls, a
151
+ // function call per clamp. Compares keep fmax's NaN-to-`lo`.
152
+ #define GEA3D_XTENSA_FPU 1
153
+ GEA3D_INLINE float clampFloat(float v, float lo, float hi) { return !(v >= lo) ? lo : (v > hi ? hi : v); }
154
+ #else
155
+ #define GEA3D_XTENSA_FPU 0
142
156
  // Branch-free on FPv5 (VMINNM/VMAXNM): a float compare's transfer to the
143
157
  // integer flags stalls the Cortex-M7 pipeline.
144
158
  GEA3D_INLINE float clampFloat(float v, float lo, float hi) { return __builtin_fminf(__builtin_fmaxf(v, lo), hi); }
159
+ #endif
145
160
  GEA3D_INLINE int clampInt(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
146
161
  GEA3D_INLINE int ctz(std::uint32_t value) { return __builtin_ctz(value); }
147
162
 
163
+ #if GEA3D_XTENSA_FPU
164
+ // Round to nearest, ties away from zero. roundf is a libm call on Xtensa; the
165
+ // truncating conversion is one instruction, and value - trunc(value) is exact
166
+ // for every float below 2^24 (larger ones are already integers).
167
+ GEA3D_INLINE std::int32_t roundToInt(float value)
168
+ {
169
+ std::int32_t whole = static_cast<std::int32_t>(value);
170
+ const float fraction = value - static_cast<float>(whole);
171
+ if (fraction >= 0.5f) whole++;
172
+ else if (fraction <= -0.5f) whole--;
173
+ return whole;
174
+ }
175
+
176
+ // 1 / value. GCC lowers a float division here to the soft-float __divsf3,
177
+ // though the FPU has a reciprocal seed: two Newton steps take its estimate to
178
+ // float precision. On the ESP32-S3 the vertex transform halved (7.1 -> 3.2 ms
179
+ // a frame for ~1,400 vertices) with this, clampFloat and roundToInt.
180
+ GEA3D_INLINE float reciprocal(float value)
181
+ {
182
+ float r;
183
+ asm("recip0.s %0, %1" : "=f"(r) : "f"(value));
184
+ r = r * (2.0f - value * r);
185
+ r = r * (2.0f - value * r);
186
+ return r;
187
+ }
188
+ #else
148
189
  // Round to nearest, ties away from zero (VRINTA on FPv5, no libm call).
149
190
  GEA3D_INLINE std::int32_t roundToInt(float value) { return static_cast<std::int32_t>(__builtin_roundf(value)); }
191
+ GEA3D_INLINE float reciprocal(float value) { return 1.0f / value; }
192
+ #endif
150
193
 
151
194
  constexpr float kFixedOne = 65536.0f;
152
195
  constexpr float kMaxSlope = 16000.0f; // px per row; steeper edges span under one row
@@ -157,13 +200,29 @@ struct Edge {
157
200
  std::int32_t x = 0;
158
201
  std::int32_t step = 0;
159
202
 
203
+ // x at the edge's first row centre and the step per row, 16.16 px.
204
+ static GEA3D_INLINE void setup(std::int32_t x0, std::int32_t y0, std::int32_t x1, std::int32_t y1, std::int32_t &xTop, std::int32_t &stepOut)
205
+ {
206
+ const float slope = clampFloat(static_cast<float>(x1 - x0) * reciprocal(static_cast<float>(y1 - y0)), -kMaxSlope, kMaxSlope);
207
+ const int top = (y0 - 8 + 15) >> 4;
208
+ const float xt = (static_cast<float>(x0) + static_cast<float>(top * 16 + 8 - y0) * slope) * (1.0f / 16.0f);
209
+ stepOut = roundToInt(slope * kFixedOne);
210
+ xTop = roundToInt(xt * kFixedOne);
211
+ }
212
+
160
213
  GEA3D_INLINE void init(std::int32_t x0, std::int32_t y0, std::int32_t x1, std::int32_t y1, int row)
161
214
  {
162
- const float slope = clampFloat(static_cast<float>(x1 - x0) / static_cast<float>(y1 - y0), -kMaxSlope, kMaxSlope);
215
+ std::int32_t xTop, stepIn;
216
+ setup(x0, y0, x1, y1, xTop, stepIn);
217
+ at(xTop, stepIn, y0, row);
218
+ }
219
+
220
+ // From a prepared setup: the edge starting at y0 (28.4), at `row`.
221
+ GEA3D_INLINE void at(std::int32_t xTop, std::int32_t stepIn, std::int32_t y0, int row)
222
+ {
163
223
  const int top = (y0 - 8 + 15) >> 4;
164
- const float xTop = (static_cast<float>(x0) + static_cast<float>(top * 16 + 8 - y0) * slope) * (1.0f / 16.0f);
165
- step = roundToInt(slope * kFixedOne);
166
- x = roundToInt(xTop * kFixedOne) + static_cast<std::int32_t>(static_cast<std::int64_t>(row - top) * step);
224
+ step = stepIn;
225
+ x = xTop + static_cast<std::int32_t>(static_cast<std::int64_t>(row - top) * stepIn);
167
226
  }
168
227
 
169
228
  GEA3D_INLINE void advance() { x += step; }
@@ -213,7 +272,49 @@ GEA3D_INLINE Pixel packRgb(std::int32_t r, std::int32_t g, std::int32_t b)
213
272
  // A constant-colour run: paired 32-bit stores on 16-bit framebuffers.
214
273
  GEA3D_INLINE void fillPixels(Pixel *dst, int count, Pixel color)
215
274
  {
216
- #if GEA_PIXEL_FORMAT_IS_8888 || GEA_PIXEL_FORMAT_IS_GRAY || GEA_PIXEL_PIE_FILL16
275
+ #if GEA_PIXEL_PIE_FILL16 && !GEA_PIXEL_FORMAT_IS_8888 && !GEA_PIXEL_FORMAT_IS_GRAY
276
+ // Raster rows average ~50 px, where the shared span fill spent ~90 of its
277
+ // ~108 cycles on a per-pixel head and tail and an 8-store pattern. Here the
278
+ // head and tail are at most three stores each (16/32/64-bit by address and
279
+ // length bits) and the vector is one broadcast load.
280
+ const std::uint32_t pair = static_cast<std::uint32_t>(color) | (static_cast<std::uint32_t>(color) << 16);
281
+ if (count >= 16) {
282
+ if ((reinterpret_cast<std::uintptr_t>(dst) & 2u) != 0) {
283
+ *dst++ = color;
284
+ count--;
285
+ }
286
+ if ((reinterpret_cast<std::uintptr_t>(dst) & 4u) != 0) {
287
+ *reinterpret_cast<std::uint32_t *>(dst) = pair;
288
+ dst += 2;
289
+ count -= 2;
290
+ }
291
+ if ((reinterpret_cast<std::uintptr_t>(dst) & 8u) != 0) {
292
+ std::uint32_t *wide = reinterpret_cast<std::uint32_t *>(dst);
293
+ wide[0] = pair;
294
+ wide[1] = pair;
295
+ dst += 4;
296
+ count -= 4;
297
+ }
298
+ const int vec = count >> 3;
299
+ std::uint32_t lane = pair;
300
+ const std::uint32_t *lanePtr = &lane;
301
+ asm volatile(
302
+ "ee.vldbc.32 q0, %[lane]\n"
303
+ "loopnez %[vec], 1f\n"
304
+ "ee.vst.128.ip q0, %[dst], 16\n"
305
+ "1:\n"
306
+ : [dst] "+r"(dst)
307
+ : [lane] "r"(lanePtr), [vec] "r"(vec)
308
+ : "memory");
309
+ count &= 7;
310
+ } else if ((reinterpret_cast<std::uintptr_t>(dst) & 2u) != 0 && count > 0) {
311
+ *dst++ = color;
312
+ count--;
313
+ }
314
+ std::uint32_t *wide = reinterpret_cast<std::uint32_t *>(dst);
315
+ for (int pairs = count >> 1; pairs > 0; pairs--) *wide++ = pair;
316
+ if ((count & 1) != 0) *reinterpret_cast<Pixel *>(wide) = color;
317
+ #elif GEA_PIXEL_FORMAT_IS_8888 || GEA_PIXEL_FORMAT_IS_GRAY || GEA_PIXEL_PIE_FILL16
217
318
  pixel::fillNative(dst, count, color);
218
319
  #else
219
320
  if (count <= 0) return;
@@ -327,6 +428,133 @@ GEA3D_INLINE void shadeEach(Pixel *dst, int count, std::int32_t r, std::int32_t
327
428
  #endif
328
429
  }
329
430
 
431
+ #if GEA_PIXEL_PIE_FILL16 && !GEA_PIXEL_FORMAT_IS_8888 && !GEA_PIXEL_FORMAT_IS_GRAY
432
+ #define GEA3D_PIE_SHADE 1
433
+ // ESP32-S3 PIE Gouraud span: eight RGB565 pixels per iteration. Each channel
434
+ // steps in 32-bit lanes (four pixels per q register), so every pixel is
435
+ // exactly packRgb(r + dr*i, ...) of the scalar walk: for a channel in
436
+ // 0..0xFFFFFF, (r >> 8) & 0xF800 == (r >> 19) << 11 and likewise for green
437
+ // and blue, which needs shifts only, no mask registers. Two groups of four
438
+ // are narrowed to 16-bit lanes with one unzip and stored with one 128-bit
439
+ // store. q0-q2 hold the channels, q6 streams the 4-pixel steps from memory;
440
+ // q registers are caller-saved and switched lazily by the IDF port.
441
+ // dst must be 16-byte aligned; count8 >= 1 groups of eight.
442
+ GEA3D_INLINE void shadePie(Pixel *dst, int count8, std::int32_t r, std::int32_t g, std::int32_t b, std::int32_t dr, std::int32_t dg, std::int32_t db)
443
+ {
444
+ alignas(16) std::int32_t start[12] = {r, r + dr, r + 2 * dr, r + 3 * dr, g, g + dg, g + 2 * dg, g + 3 * dg, b, b + db, b + 2 * db, b + 3 * db};
445
+ alignas(16) std::int32_t step[12] = {4 * dr, 4 * dr, 4 * dr, 4 * dr, 4 * dg, 4 * dg, 4 * dg, 4 * dg, 4 * db, 4 * db, 4 * db, 4 * db};
446
+ const std::int32_t *acc = start;
447
+ const std::int32_t *st = step;
448
+ const int s19 = 19, s11 = 11, s18 = 18, s5 = 5;
449
+ asm volatile(
450
+ "ee.vld.128.ip q0, %[acc], 16\n"
451
+ "ee.vld.128.ip q1, %[acc], 16\n"
452
+ "ee.vld.128.ip q2, %[acc], 0\n"
453
+ "loopnez %[n], 1f\n"
454
+ // pixels 0..3 -> q3
455
+ "wsr.sar %[s19]\n"
456
+ "ee.vsr.32 q3, q0\n"
457
+ "ee.vsr.32 q7, q2\n"
458
+ "wsr.sar %[s11]\n"
459
+ "ee.vsl.32 q3, q3\n"
460
+ "ee.orq q3, q3, q7\n"
461
+ "wsr.sar %[s18]\n"
462
+ "ee.vsr.32 q7, q1\n"
463
+ "wsr.sar %[s5]\n"
464
+ "ee.vsl.32 q7, q7\n"
465
+ "ee.orq q3, q3, q7\n"
466
+ "ee.vld.128.ip q6, %[st], 16\n"
467
+ "ee.vadds.s32 q0, q0, q6\n"
468
+ "ee.vld.128.ip q6, %[st], 16\n"
469
+ "ee.vadds.s32 q1, q1, q6\n"
470
+ "ee.vld.128.ip q6, %[st], -32\n"
471
+ "ee.vadds.s32 q2, q2, q6\n"
472
+ // pixels 4..7 -> q4
473
+ "wsr.sar %[s19]\n"
474
+ "ee.vsr.32 q4, q0\n"
475
+ "ee.vsr.32 q7, q2\n"
476
+ "wsr.sar %[s11]\n"
477
+ "ee.vsl.32 q4, q4\n"
478
+ "ee.orq q4, q4, q7\n"
479
+ "wsr.sar %[s18]\n"
480
+ "ee.vsr.32 q7, q1\n"
481
+ "wsr.sar %[s5]\n"
482
+ "ee.vsl.32 q7, q7\n"
483
+ "ee.orq q4, q4, q7\n"
484
+ "ee.vld.128.ip q6, %[st], 16\n"
485
+ "ee.vadds.s32 q0, q0, q6\n"
486
+ "ee.vld.128.ip q6, %[st], 16\n"
487
+ "ee.vadds.s32 q1, q1, q6\n"
488
+ "ee.vld.128.ip q6, %[st], -32\n"
489
+ "ee.vadds.s32 q2, q2, q6\n"
490
+ // Low halves of both groups, in pixel order, into q3 (q4 = zeros).
491
+ "ee.vunzip.16 q3, q4\n"
492
+ #if GEA_EMBEDDED_PIXEL_PANEL_ENDIAN
493
+ // Panel byte order: split low/high bytes, re-interleave swapped.
494
+ "ee.vunzip.8 q3, q4\n"
495
+ "ee.vzip.8 q4, q3\n"
496
+ "ee.vst.128.ip q4, %[dst], 16\n"
497
+ #else
498
+ "ee.vst.128.ip q3, %[dst], 16\n"
499
+ #endif
500
+ "1:\n"
501
+ : [dst] "+r"(dst), [acc] "+r"(acc), [st] "+r"(st)
502
+ : [n] "r"(count8), [s19] "r"(s19), [s11] "r"(s11), [s18] "r"(s18), [s5] "r"(s5)
503
+ : "memory");
504
+ }
505
+
506
+ // ESP32-S3 PIE additive blend: dst = dst + src per RGB565 channel, each
507
+ // saturating, eight pixels per iteration -- exactly addPixel(src, dst, 255).
508
+ // Blue and green add in place (masked to their fields, so neither can carry
509
+ // into the next); red is moved down a bit first so its sum stays positive in
510
+ // a signed 16-bit lane, then clamped and moved back. vsr/vsl shift 32-bit
511
+ // lanes: the bit that crosses into the lower lane's top is masked off, and
512
+ // the clamped red never sets the bit that would cross back.
513
+ // dst and src must be 16-byte aligned; count8 >= 1 groups of eight.
514
+ alignas(16) inline std::uint16_t g_addPieMasks[24] = {
515
+ 0x001F, 0x001F, 0x001F, 0x001F, 0x001F, 0x001F, 0x001F, 0x001F,
516
+ 0x07E0, 0x07E0, 0x07E0, 0x07E0, 0x07E0, 0x07E0, 0x07E0, 0x07E0,
517
+ 0x7C00, 0x7C00, 0x7C00, 0x7C00, 0x7C00, 0x7C00, 0x7C00, 0x7C00,
518
+ };
519
+ GEA3D_INLINE void addPie(Pixel *dst, const Pixel *src, int count8)
520
+ {
521
+ const std::uint16_t *masks = g_addPieMasks;
522
+ const int one = 1;
523
+ asm volatile(
524
+ "ee.vld.128.ip q5, %[masks], 16\n"
525
+ "ee.vld.128.ip q6, %[masks], 16\n"
526
+ "ee.vld.128.ip q7, %[masks], 0\n"
527
+ "wsr.sar %[one]\n"
528
+ "loopnez %[n], 1f\n"
529
+ "ee.vld.128.ip q0, %[src], 16\n"
530
+ "ee.vld.128.ip q1, %[dst], 0\n"
531
+ "ee.andq q2, q0, q5\n"
532
+ "ee.andq q3, q1, q5\n"
533
+ "ee.vadds.s16 q2, q2, q3\n"
534
+ "ee.vmin.s16 q2, q2, q5\n"
535
+ "ee.andq q3, q0, q6\n"
536
+ "ee.andq q4, q1, q6\n"
537
+ "ee.vadds.s16 q3, q3, q4\n"
538
+ "ee.vmin.s16 q3, q3, q6\n"
539
+ "ee.orq q2, q2, q3\n"
540
+ "ee.vsr.32 q0, q0\n"
541
+ "ee.vsr.32 q1, q1\n"
542
+ "ee.andq q0, q0, q7\n"
543
+ "ee.andq q1, q1, q7\n"
544
+ "ee.vadds.s16 q0, q0, q1\n"
545
+ "ee.vmin.s16 q0, q0, q7\n"
546
+ "ee.vsl.32 q0, q0\n"
547
+ "ee.orq q2, q2, q0\n"
548
+ "ee.vst.128.ip q2, %[dst], 16\n"
549
+ "1:\n"
550
+ : [dst] "+r"(dst), [src] "+r"(src), [masks] "+r"(masks)
551
+ : [n] "r"(count8), [one] "r"(one)
552
+ : "memory");
553
+ }
554
+ #else
555
+ #define GEA3D_PIE_SHADE 0
556
+ #endif
557
+
330
558
  // A Gouraud span whose channels stay in 0..0xFFFFFF (16.16). Spans that
331
559
  // change colour rarely are filled as flat runs between the changes; the
332
560
  // pixels are exactly those of the per-pixel walk.
@@ -334,6 +562,39 @@ GEA3D_INLINE void shadePixels(Pixel *dst, int count, std::int32_t r, std::int32_
334
562
  {
335
563
  const int last = count - 1;
336
564
  const int changes = levelChanges(r, r + dr * last, kShiftR) + levelChanges(g, g + dg * last, kShiftG) + levelChanges(b, b + db * last, kShiftB);
565
+ // A linear ramp whose ends pack to one pixel colour packs to it all the
566
+ // way: a fogged or gently lit face's short rows are mostly such runs.
567
+ if (changes == 0) {
568
+ fillPixels(dst, count, packRgb(r, g, b));
569
+ return;
570
+ }
571
+ #if GEA3D_PIE_SHADE
572
+ // Short rows (Neon's are ~19 px) spent most of their time in the scalar
573
+ // head and tail around one vector group, ~400 cycles a row. Shade whole
574
+ // groups into an aligned scratch row and copy the span out: lanes past the
575
+ // span (whose channels may leave 0..0xFFFFFF) stay in their own lanes and
576
+ // are dropped, so the span is exactly the scalar walk's.
577
+ if (count >= 4 && count <= 64) {
578
+ alignas(16) Pixel row[64];
579
+ shadePie(row, (count + 7) >> 3, r, g, b, dr, dg, db);
580
+ std::memcpy(dst, row, static_cast<std::size_t>(count) * sizeof(Pixel));
581
+ return;
582
+ }
583
+ #endif
584
+ #if GEA3D_PIE_SHADE
585
+ // Long steady runs stay flat vector fills; anything busier is shaded
586
+ // eight pixels at a time with no per-run divides.
587
+ if (count >= 16 && count < 32 * (changes + 1)) {
588
+ const int head = static_cast<int>(((16u - (reinterpret_cast<std::uintptr_t>(dst) & 15u)) & 15u) >> 1);
589
+ shadeEach(dst, head, r, g, b, dr, dg, db);
590
+ const std::int32_t rh = r + dr * head, gh = g + dg * head, bh = b + db * head;
591
+ const int body = (count - head) >> 3;
592
+ shadePie(dst + head, body, rh, gh, bh, dr, dg, db);
593
+ const int done = head + (body << 3);
594
+ shadeEach(dst + done, count - done, r + dr * done, g + dg * done, b + db * done, dr, dg, db);
595
+ return;
596
+ }
597
+ #endif
337
598
  if (count < 4 * (changes + 1)) {
338
599
  shadeEach(dst, count, r, g, b, dr, dg, db);
339
600
  return;
@@ -358,6 +619,7 @@ GEA3D_INLINE void shadePixels(Pixel *dst, int count, std::int32_t r, std::int32_
358
619
 
359
620
  } // namespace detail
360
621
 
622
+
361
623
  // The primitives touching one band, in sorted order (indices into
362
624
  // Frame::prims), the first `opaque` of them opaque.
363
625
  struct BandList {
@@ -371,6 +633,31 @@ enum class Occlusion : std::uint8_t {
371
633
  kPainter, // background first, then back to front: for fast buffers
372
634
  };
373
635
 
636
+ // Sorts a triangle's corners by y (the order drawTriangle would pick, ties
637
+ // included, so its own sort leaves them) and sets its edges up once, on the
638
+ // frame-build core: every band the triangle crosses otherwise re-did this,
639
+ // ~250 cycles a triangle a band on the ESP32-S3.
640
+ inline void prepareTriangle(Prim &p)
641
+ {
642
+ if (p.type != kTriangle) return;
643
+ const auto swapCorners = [&p](int a, int b) {
644
+ std::swap(p.x[a], p.x[b]);
645
+ std::swap(p.y[a], p.y[b]);
646
+ std::swap(p.depth[a], p.depth[b]);
647
+ std::swap(p.r[a], p.r[b]);
648
+ std::swap(p.g[a], p.g[b]);
649
+ std::swap(p.b[a], p.b[b]);
650
+ };
651
+ if (p.y[0] > p.y[1]) swapCorners(0, 1);
652
+ if (p.y[0] > p.y[2]) swapCorners(0, 2);
653
+ if (p.y[1] > p.y[2]) swapCorners(1, 2);
654
+ if (p.y[2] == p.y[0]) return; // no area: drawTriangle skips it
655
+ detail::Edge::setup(p.x[0], p.y[0], p.x[2], p.y[2], p.edgeX[0], p.edgeStep[0]);
656
+ if (p.y[1] != p.y[0]) detail::Edge::setup(p.x[0], p.y[0], p.x[1], p.y[1], p.edgeX[1], p.edgeStep[1]);
657
+ if (p.y[2] != p.y[1]) detail::Edge::setup(p.x[1], p.y[1], p.x[2], p.y[2], p.edgeX[2], p.edgeStep[2]);
658
+ p.flags |= kPrepared;
659
+ }
660
+
374
661
  class Rasterizer {
375
662
  public:
376
663
  Rasterizer(const Frame &frame, Scratch &scratch, Pixel *base, int stride, int x0, int y0, int x1, int y1, Occlusion occlusion = Occlusion::kCoverage)
@@ -378,6 +665,7 @@ public:
378
665
  {
379
666
  width_ = x1 - x0 + 1;
380
667
  height_ = y1 - y0 + 1;
668
+ alignedRows_ = (reinterpret_cast<std::uintptr_t>(base) & 15u) == 0 && (static_cast<std::size_t>(stride) * sizeof(Pixel)) % 16u == 0;
381
669
  if (width_ <= 0 || height_ <= 0) return;
382
670
 
383
671
  if (!painter_) bindCoverage();
@@ -453,6 +741,9 @@ private:
453
741
  Scratch &scratch_;
454
742
  Pixel *base_;
455
743
  int stride_;
744
+ // Every row starts on a 16-byte boundary: addRunPie may widen a span to
745
+ // whole vector groups within its row.
746
+ bool alignedRows_ = false;
456
747
  int x0_, y0_, x1_, y1_;
457
748
  int width_ = 0;
458
749
  int height_ = 0;
@@ -574,7 +865,7 @@ private:
574
865
  if (rowFirst > rowLast) return;
575
866
 
576
867
  const SpanState span = spanState(prim, blendPass, i0, i1, i2);
577
- const Walk walk{X0, Y0, X1, Y1, X2, Y2, rowFirst, rowLast, ySplit, cross > 0};
868
+ const Walk walk{X0, Y0, X1, Y1, X2, Y2, rowFirst, rowLast, ySplit, cross > 0, (prim.flags & kPrepared) ? &prim : nullptr};
578
869
 
579
870
  // Painter's order without blending or depth: spans go straight to the band.
580
871
  if (painter_ && !span.blend && !useDepth_) {
@@ -597,6 +888,7 @@ private:
597
888
  std::int32_t x0, y0, x1, y1, x2, y2;
598
889
  int rowFirst, rowLast, ySplit;
599
890
  bool longLeft;
891
+ const Prim *prepared; // edges set up by prepareTriangle, or null
600
892
  };
601
893
 
602
894
  // Calls emit(row, xa, xb) for the pixels [xa, xb) of each row, clipped to
@@ -605,16 +897,19 @@ private:
605
897
  GEA3D_INLINE void walkRows(const Walk &w, Emit emit)
606
898
  {
607
899
  detail::Edge longEdge;
608
- longEdge.init(w.x0, w.y0, w.x2, w.y2, w.rowFirst);
900
+ if (w.prepared) longEdge.at(w.prepared->edgeX[0], w.prepared->edgeStep[0], w.y0, w.rowFirst);
901
+ else longEdge.init(w.x0, w.y0, w.x2, w.y2, w.rowFirst);
609
902
  detail::Edge shortEdge;
610
903
  int row = w.rowFirst;
611
904
  if (row < w.ySplit) {
612
- shortEdge.init(w.x0, w.y0, w.x1, w.y1, row);
905
+ if (w.prepared) shortEdge.at(w.prepared->edgeX[1], w.prepared->edgeStep[1], w.y0, row);
906
+ else shortEdge.init(w.x0, w.y0, w.x1, w.y1, row);
613
907
  row = walkSection(longEdge, shortEdge, w.longLeft, row, detail::minInt(w.ySplit - 1, w.rowLast), emit);
614
908
  }
615
909
  if (row > w.rowLast || w.y2 == w.y1) return;
616
910
 
617
- shortEdge.init(w.x1, w.y1, w.x2, w.y2, row);
911
+ if (w.prepared) shortEdge.at(w.prepared->edgeX[2], w.prepared->edgeStep[2], w.y1, row);
912
+ else shortEdge.init(w.x1, w.y1, w.x2, w.y2, row);
618
913
  walkSection(longEdge, shortEdge, w.longLeft, row, w.rowLast, emit);
619
914
  }
620
915
 
@@ -662,7 +957,7 @@ private:
662
957
  return span;
663
958
  }
664
959
 
665
- const float invArea = 1.0f / area;
960
+ const float invArea = detail::reciprocal(area);
666
961
  if (span.smooth) {
667
962
  span.r.init(sx, sy, invArea, prim.r[i0], prim.r[i1], prim.r[i2]);
668
963
  span.g.init(sx, sy, invArea, prim.g[i0], prim.g[i1], prim.g[i2]);
@@ -877,6 +1172,18 @@ private:
877
1172
  const Pixel flat = span.prim->color;
878
1173
  const int alpha = span.prim->alpha;
879
1174
  const bool add = (span.prim->flags & kAdd) != 0;
1175
+ #if !(GEA_PIXEL_FORMAT_IS_8888 || GEA_PIXEL_FORMAT_IS_GRAY)
1176
+ if (add && !span.depthTest && !span.depthWrite) {
1177
+ #if GEA3D_PIE_SHADE && !GEA_EMBEDDED_PIXEL_PANEL_ENDIAN
1178
+ if (alpha == 255 && alignedRows_ && (!span.smooth || (inRange(r, dr, last) && inRange(g, dg, last) && inRange(b, db, last)))) {
1179
+ addRunPie(dst, count, span.smooth, flat, r, g, b, dr, dg, db);
1180
+ return;
1181
+ }
1182
+ #endif
1183
+ addRun(dst, count, span.smooth, flat, r, g, b, dr, dg, db, alpha);
1184
+ return;
1185
+ }
1186
+ #endif
880
1187
  for (int i = 0; i < count; i++) {
881
1188
  bool visible = true;
882
1189
  if (span.depthTest) {
@@ -897,6 +1204,104 @@ private:
897
1204
  }
898
1205
  }
899
1206
 
1207
+ #if !(GEA_PIXEL_FORMAT_IS_8888 || GEA_PIXEL_FORMAT_IS_GRAY)
1208
+ // An additive run on RGB565: the same sums as addPixel(packRgb(..)) per
1209
+ // pixel, with the loop invariants hoisted and the 565 channels of the
1210
+ // source taken straight from the colour ramp instead of packed and
1211
+ // unpacked again. Pixels whose scaled source is black are left alone.
1212
+ static void addRun(Pixel *dst, int count, bool smooth, Pixel flat, std::int32_t r, std::int32_t g, std::int32_t b, std::int32_t dr, std::int32_t dg, std::int32_t db, int alpha)
1213
+ {
1214
+ const int scale = alpha + (alpha >> 7);
1215
+ if (!smooth) {
1216
+ const std::uint32_t f = pixel::toRgb565(flat);
1217
+ const int ar = (static_cast<int>(f >> 11) * scale) >> 8;
1218
+ const int ag = (static_cast<int>((f >> 5) & 63) * scale) >> 8;
1219
+ const int ab = (static_cast<int>(f & 31) * scale) >> 8;
1220
+ if ((ar | ag | ab) == 0) return;
1221
+ for (int i = 0; i < count; i++) dst[i] = addRgb565(dst[i], ar, ag, ab);
1222
+ return;
1223
+ }
1224
+ for (int i = 0; i < count; i++) {
1225
+ const int ar = ((clampColor(r) >> 19) * scale) >> 8;
1226
+ const int ag = ((clampColor(g) >> 18) * scale) >> 8;
1227
+ const int ab = ((clampColor(b) >> 19) * scale) >> 8;
1228
+ r += dr;
1229
+ g += dg;
1230
+ b += db;
1231
+ if ((ar | ag | ab) == 0) continue;
1232
+ dst[i] = addRgb565(dst[i], ar, ag, ab);
1233
+ }
1234
+ }
1235
+
1236
+ #if GEA3D_PIE_SHADE && !GEA_EMBEDDED_PIXEL_PANEL_ENDIAN
1237
+ // addRun at full opacity, eight pixels at a time between a scalar head
1238
+ // (to 16-byte alignment) and tail: the source ramp is shaded into an
1239
+ // aligned row (shadePie: the caller checked its channels stay in range),
1240
+ // then added in. Pixel for pixel the same as addRun.
1241
+ static void addRunPie(Pixel *dst, int count, bool smooth, Pixel flat, std::int32_t r, std::int32_t g, std::int32_t b, std::int32_t dr, std::int32_t dg, std::int32_t db)
1242
+ {
1243
+ if (count < 4) {
1244
+ addOpaqueRamp(dst, count, smooth, flat, r, g, b, dr, dg, db);
1245
+ return;
1246
+ }
1247
+ // Whole aligned groups only, from the 16-byte boundary at or before the
1248
+ // span: lanes outside it add zero, a saturating add of zero leaves a
1249
+ // pixel as it was, and band rows are 16-byte aligned, so the widened
1250
+ // groups stay in this row. The scalar head and tail this replaces were
1251
+ // ~10 cycles a pixel, most of a ~40 px glow row.
1252
+ const int lead = static_cast<int>((reinterpret_cast<std::uintptr_t>(dst) & 15u) >> 1);
1253
+ Pixel *const aligned = dst - lead;
1254
+ const int total = lead + count;
1255
+ alignas(16) Pixel src[64];
1256
+ for (int done = 0; done < total;) {
1257
+ const int chunk = detail::minInt(total - done, 64);
1258
+ const int groups = (chunk + 7) >> 3;
1259
+ const int first = done - lead; // span index of src[0]
1260
+ if (smooth) detail::shadePie(src, groups, r + dr * first, g + dg * first, b + db * first, dr, dg, db);
1261
+ else detail::fillPixels(src, groups << 3, flat);
1262
+ if (done == 0)
1263
+ for (int k = 0; k < lead; k++) src[k] = 0;
1264
+ for (int k = chunk; k < (groups << 3); k++) src[k] = 0;
1265
+ detail::addPie(aligned + done, src, groups);
1266
+ done += groups << 3;
1267
+ }
1268
+ }
1269
+ #endif
1270
+
1271
+ // addRun at full opacity with every channel of the ramp in range: no
1272
+ // clamps, no scale, no zero test -- the scalar head and tail (and the
1273
+ // short rows) of addRunPie.
1274
+ static GEA3D_INLINE void addOpaqueRamp(Pixel *dst, int count, bool smooth, Pixel flat, std::int32_t r, std::int32_t g, std::int32_t b, std::int32_t dr, std::int32_t dg, std::int32_t db)
1275
+ {
1276
+ if (!smooth) {
1277
+ const std::uint32_t f = pixel::toRgb565(flat);
1278
+ r = static_cast<std::int32_t>(f >> 11) << 19;
1279
+ g = static_cast<std::int32_t>((f >> 5) & 63) << 18;
1280
+ b = static_cast<std::int32_t>(f & 31) << 19;
1281
+ dr = dg = db = 0;
1282
+ }
1283
+ for (int i = 0; i < count; i++) {
1284
+ const std::uint32_t c = pixel::toRgb565(dst[i]);
1285
+ const int rr = detail::minInt(31, static_cast<int>(c >> 11) + (r >> 19));
1286
+ const int gg = detail::minInt(63, static_cast<int>((c >> 5) & 63) + (g >> 18));
1287
+ const int bb = detail::minInt(31, static_cast<int>(c & 31) + (b >> 19));
1288
+ dst[i] = pixel::fromRgb565(static_cast<std::uint16_t>((rr << 11) | (gg << 5) | bb));
1289
+ r += dr;
1290
+ g += dg;
1291
+ b += db;
1292
+ }
1293
+ }
1294
+
1295
+ static GEA3D_INLINE Pixel addRgb565(Pixel bg, int ar, int ag, int ab)
1296
+ {
1297
+ const std::uint32_t c = pixel::toRgb565(bg);
1298
+ const int rr = detail::minInt(31, static_cast<int>(c >> 11) + ar);
1299
+ const int gg = detail::minInt(63, static_cast<int>((c >> 5) & 63) + ag);
1300
+ const int bb = detail::minInt(31, static_cast<int>(c & 31) + ab);
1301
+ return pixel::fromRgb565(static_cast<std::uint16_t>((rr << 11) | (gg << 5) | bb));
1302
+ }
1303
+ #endif
1304
+
900
1305
  static GEA3D_INLINE int absStep(std::int32_t step) { return step < 0 ? -step : step; }
901
1306
 
902
1307
  // inRange for all three channels, when their ramps fit 32 bits: a value
@@ -1016,7 +1421,7 @@ private:
1016
1421
  w.from = 1;
1017
1422
  }
1018
1423
  const float span = mb - ma;
1019
- w.inv = span > 0.0f ? 1.0f / span : 0.0f;
1424
+ w.inv = span > 0.0f ? detail::reciprocal(span) : 0.0f;
1020
1425
  const float slope = (nb - na) * w.inv;
1021
1426
  const int across = detail::maxInt(prim.width, 1);
1022
1427
  w.lo = -((across - 1) >> 1);
@@ -1028,7 +1433,7 @@ private:
1028
1433
  w.last = detail::minInt(detail::roundToInt(mb), w.xMajor ? x1_ : y1_);
1029
1434
  // Where the minor coordinate can round into the region, with slack.
1030
1435
  if (slope != 0.0f) {
1031
- const float perMinor = 1.0f / slope;
1436
+ const float perMinor = detail::reciprocal(slope);
1032
1437
  float m0 = ma + (static_cast<float>(w.minorLo - 1 - w.hi) - na) * perMinor;
1033
1438
  float m1 = ma + (static_cast<float>(w.minorHi + 1 - w.lo) - na) * perMinor;
1034
1439
  if (slope < 0.0f) swapFloat(m0, m1);