From: Svjatoslav Agejenko
Global illumination radius gating (see + * {@code Documentation/Global illumination/index.org}): {@code + * giStage2Radius} / {@code giStage3Radius} / {@code giStage4Radius} â + * world-unit distance from the camera beyond which entries skip the + * centroid bounce (stage 2), the coarse per-texel lightmap bake + * (stage 3) and the fine per-texel refinement (stage 4). 0 (default) + * means unlimited: every entry gets every stage, the historical + * behavior. {@code giMeshUnitsPerTexel} â units per lightmap texel for + * mesh-block triangles at the FINAL resolution, default 2.1 (the + * stage-3 coarse bake uses {@code e3d.gi.stage3TexelFactor} times + * that). {@code giLightmapCacheEntries} â cap on the baked-lightmap + * composite cache that restores lightmaps after cell stream-out/in, + * default 65536.
+ * *Every key can also be set as a system property * ({@code -De3d.ipd=6.3}, {@code -De3d.bugreport.dir=...}, - * {@code -De3d.log.dir=...}, {@code -De3d.telemetry.interval=...}); - * system properties win over the config file.
+ * {@code -De3d.log.dir=...}, {@code -De3d.telemetry.interval=...}, + * {@code -De3d.gi.stage2Radius=...} and likewise for the other GI + * keys); system properties win over the config file. */ public final class EngineConfig { @@ -69,6 +84,106 @@ public final class EngineConfig { null)), 5); } + /** + * GI stage-2 radius in world units: beyond it, entries skip the + * centroid bounce and keep their stage-1 direct stamp. 0 (default) + * = unlimited. + */ + public static double getGiStage2Radius() { + return parseDouble(System.getProperty("e3d.gi.stage2Radius", + AukioConfig.get().getString("e3d.giStage2Radius", null)), 0); + } + + /** + * GI stage-3 radius in world units: beyond it, triangles never get + * a lightmap (mesh blocks keep their per-triangle shade). 0 + * (default) = unlimited for lightmapped shapes â and mesh blocks + * then never get lightmaps at all: per-texel work on every lean + * triangle of a huge world is exactly what the radius exists to + * avoid, so block lightmapping is enabled by a POSITIVE radius. + */ + public static double getGiStage3Radius() { + return parseDouble(System.getProperty("e3d.gi.stage3Radius", + AukioConfig.get().getString("e3d.giStage3Radius", null)), 0); + } + + /** + * GI stage-4 radius in world units: beyond it, lightmaps are not + * refined to the final texel density and keep the coarse composite. + * 0 (default) = unlimited. + */ + public static double getGiStage4Radius() { + return parseDouble(System.getProperty("e3d.gi.stage4Radius", + AukioConfig.get().getString("e3d.giStage4Radius", null)), 0); + } + + /** + * Units per lightmap texel for mesh-block triangles at the final + * (stage-4) resolution, default 2.1. The stage-3 coarse bake runs + * at {@code e3d.gi.stage3TexelFactor} times this. + */ + public static double getGiMeshUnitsPerTexel() { + return parseDouble(System.getProperty("e3d.gi.meshUnitsPerTexel", + AukioConfig.get().getString("e3d.giMeshUnitsPerTexel", + null)), 2.1); + } + + /** + * Cap on the baked-lightmap composite cache that restores lightmaps + * instantly after a cell streams out and back in, default 65536. + */ + public static int getGiLightmapCacheEntries() { + return (int) parseDouble(System.getProperty( + "e3d.gi.lightmapCacheEntries", + AukioConfig.get().getString("e3d.giLightmapCacheEntries", + null)), 65536); + } + + /** + * Cap on the stage-1/2 centroid-value cache that restores direct + * and first-bounce lighting instantly when a cell streams out and + * back in, default 4 000 000. Sized to hold a full FO4 streamed + * world (~1.8-2.7M triangles) so any region you revisit is a hit; + * worst-case RAM is roughly half a gigabyte (about 120 bytes per + * entry), evicting least-recently-used beyond the cap. + */ + public static int getGiCentroidCacheEntries() { + return (int) parseDouble(System.getProperty( + "e3d.gi.centroidCacheEntries", + AukioConfig.get().getString("e3d.giCentroidCacheEntries", + null)), 4_000_000); + } + + /** + * Master switch for atmospheric distance haze (see + * {@code renderer/raster/lighting/Atmosphere.java}), default false. + * Environment modules may enable it per scene at runtime. + */ + public static boolean isAtmosphereEnabled() { + final String v = System.getProperty("e3d.atmosphere", + AukioConfig.get().getString("e3d.atmosphere", null)); + return v != null && Boolean.parseBoolean(v); + } + + /** + * Atmospheric haze scale in world units: the camera depth at which + * the haze factor reaches ~63% (1 - 1/e), default 100000. + */ + public static double getAtmosphereScale() { + return parseDouble(System.getProperty("e3d.atmosphereScale", + AukioConfig.get().getString("e3d.atmosphereScale", + null)), 100000); + } + + /** + * Atmospheric haze target color as RRGGBB, default empty = fade + * toward the scene's sky color. + */ + public static String getAtmosphereColor() { + return System.getProperty("e3d.atmosphereColor", + AukioConfig.get().getString("e3d.atmosphereColor", "")); + } + private static double parseDouble(final String value, final double fallback) { if (value == null || value.isBlank()) diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/gui/BugReport.java b/src/main/java/eu/svjatoslav/aukio/e3d/gui/BugReport.java index 665b7cb..ab22714 100644 --- a/src/main/java/eu/svjatoslav/aukio/e3d/gui/BugReport.java +++ b/src/main/java/eu/svjatoslav/aukio/e3d/gui/BugReport.java @@ -91,6 +91,14 @@ public final class BugReport { final long used = rt.totalMemory() - rt.freeMemory(); final StringBuilder sb = new StringBuilder(); sb.append("time = ").append(LocalDateTime.now()).append('\n'); + // Which app this report is about: the exact launch command + // (main class + arguments) and the working directory. + sb.append("app.command = ") + .append(System.getProperty("sun.java.command", "unknown")) + .append('\n'); + sb.append("app.user.dir = ") + .append(System.getProperty("user.dir", "unknown")) + .append('\n'); if (viewPanel != null) { final Camera camera = viewPanel.getCamera(); diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/gui/DeveloperToolsPanel.java b/src/main/java/eu/svjatoslav/aukio/e3d/gui/DeveloperToolsPanel.java index 179a4f0..8111aac 100644 --- a/src/main/java/eu/svjatoslav/aukio/e3d/gui/DeveloperToolsPanel.java +++ b/src/main/java/eu/svjatoslav/aukio/e3d/gui/DeveloperToolsPanel.java @@ -86,6 +86,22 @@ public class DeveloperToolsPanel extends JFrame { * The label showing the measured FPS. */ private final JLabel measuredFpsLabel; + /** + * The label showing the GI stage and coverage distance. + */ + private final JLabel giStageLabel; + /** + * The label showing GI queue progress and bubble sizes. + */ + private final JLabel giDetailLabel; + /** + * The label showing per-stage eligible entry counts. + */ + private final JLabel giEligibleLabel; + /** + * The label showing the GI cache size and pending catch-up count. + */ + private final JLabel giCacheLabel; /** * Toggle button switching between target FPS and unlimited FPS. */ @@ -150,6 +166,16 @@ public class DeveloperToolsPanel extends JFrame { targetFpsLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); measuredFpsLabel = new JLabel(" "); measuredFpsLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + + // Global illumination row + giStageLabel = new JLabel(" "); + giStageLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + giDetailLabel = new JLabel(" "); + giDetailLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + giEligibleLabel = new JLabel(" "); + giEligibleLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); + giCacheLabel = new JLabel(" "); + giCacheLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); unlockFpsButton = new JToggleButton("Unlock FPS"); unlockFpsButton.setToolTipText( "Disable the frame rate cap so the application renders as fast as it can (benchmark mode)"); @@ -187,6 +213,7 @@ public class DeveloperToolsPanel extends JFrame { topPanel.add(createSettingsPanel()); topPanel.add(createCameraPanel()); topPanel.add(createCullingPanel()); + topPanel.add(createGiPanel()); topPanel.add(createRenderThreadsPanel()); topPanel.add(createFrameRatePanel()); topPanel.add(createThreadTimelinePanel()); @@ -381,6 +408,37 @@ public class DeveloperToolsPanel extends JFrame { return panel; } + /** + * The Global Illumination row: current bake stage and how far from + * the camera the active stage has covered. The queue drains + * nearest-first, so a coverage distance that stops growing with work + * remaining means the bake is stuck. + */ + private JPanel createGiPanel() { + final JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + panel.setBorder(BorderFactory.createCompoundBorder( + BorderFactory.createEmptyBorder(0, 8, 8, 8), + BorderFactory.createTitledBorder("Global Illumination") + )); + + final JPanel stageRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 2)); + stageRow.add(new JLabel("Stage:")); + stageRow.add(giStageLabel); + stageRow.add(new JLabel(" Covered:")); + stageRow.add(giDetailLabel); + + final JPanel detailRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 2)); + detailRow.add(new JLabel("Eligible S2/S3/S4:")); + detailRow.add(giEligibleLabel); + detailRow.add(new JLabel(" Cache:")); + detailRow.add(giCacheLabel); + + panel.add(stageRow); + panel.add(detailRow); + return panel; + } + private JPanel createRenderThreadsPanel() { final JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); @@ -578,6 +636,7 @@ public class DeveloperToolsPanel extends JFrame { try { updateCameraLabel(); updateCullingStatistics(); + updateGiRow(); updateRenderThreadsLabel(); updateFrameRateLabels(); updateLogDisplay(); @@ -600,6 +659,75 @@ public class DeveloperToolsPanel extends JFrame { pos.x, pos.y, pos.z, angles[0], angles[1], angles[2])); } + /** + * Refreshes the Global Illumination row. Shows the mapped display + * stage (1 = centroid direct, 2 = centroid bounce, 3 = coarse + * lightmaps, 4 = fine refinement), the queue progress within the + * stage, and the camera distance the stage has covered so far vs + * the configured radius cap for that stage. + */ + private void updateGiRow() { + if (viewPanel == null) { + return; + } + final eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination gi = + viewPanel.getGlobalIllumination(); + if (gi == null) { + giStageLabel.setText("disabled"); + giDetailLabel.setText(" "); + giEligibleLabel.setText(" "); + giCacheLabel.setText(" "); + return; + } + final eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination.Status + status = gi.getStatus(); + if (!status.running || status.entries == 0 && !status.baked) { + giStageLabel.setText("startingâ¦"); + giDetailLabel.setText(" "); + giEligibleLabel.setText(" "); + giCacheLabel.setText(" "); + return; + } + + final String stageText; + if (status.baked) + stageText = "done (catch-up watch)"; + else + stageText = status.stage + " (gen " + status.generation + ")"; + + // Radius cap of the active stage (0 = unlimited); effective + // values from the GI system, aware of per-instance overrides. + final double cap; + switch (status.stage) { + case 2: + cap = status.stage2Radius; + break; + case 3: + cap = status.stage3Radius; + break; + case 4: + cap = status.stage4Radius; + break; + default: + cap = 0; + break; + } + final String covered = Double.isNaN(status.coveredDistance) + ? "â" : String.format("%.0f", status.coveredDistance); + final String capText = cap > 0 + ? String.format(" / cap %.0f", cap) : " (no cap)"; + + giStageLabel.setText(String.format("%s queue %d/%d", + stageText, status.queueDone, status.queueLength)); + giDetailLabel.setText(String.format("%s u%s", covered, capText)); + giEligibleLabel.setText(String.format("%d / %d / %d", + status.stage2eligible, status.stage3eligible, + status.stage4eligible)); + giCacheLabel.setText(String.format("%d lm + %d centr. catch-up %d", + status.cacheSize, status.centroidCacheSize, + status.catchUpPending)); + } + private void updateCullingStatistics() { if (viewPanel == null) { return; diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/gui/ViewPanel.java b/src/main/java/eu/svjatoslav/aukio/e3d/gui/ViewPanel.java index daef0ad..f1e31ac 100755 --- a/src/main/java/eu/svjatoslav/aukio/e3d/gui/ViewPanel.java +++ b/src/main/java/eu/svjatoslav/aukio/e3d/gui/ViewPanel.java @@ -497,15 +497,47 @@ public class ViewPanel extends Canvas { */ public synchronized eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination enableGlobalIllumination( final int threadCount) { + return enableGlobalIllumination(threadCount, null); + } + + /** + * Enables progressive global illumination, applying the given + * configurer (radius/density overrides) BEFORE the worker threads + * start â the first eligibility evaluation already sees them. + * Needed when one JVM hosts scenes of different scales (the demo + * launcher): per-instance overrides instead of global -D properties. + * Calling again returns the already-running system (configurer + * ignored). + * + * @param threadCount worker threads for ray tracing + * @param configurer applied to the new GI system before start; + * may be null + * @return the running GI system + */ + public synchronized eu.svjatoslav.aukio.e3d.renderer.raster.gi.GlobalIllumination enableGlobalIllumination( + final int threadCount, + final java.util.function.ConsumerAlso (re)starts the render thread when the component is showable: + * the thread is otherwise started only from componentShown/Resized, + * which under window managers without reparenting (bare Xvfb) can fire + * before the panel is displayable â leaving the view dark forever + * despite pending repaints. Idempotent; the render thread guards on + * {@code renderThread != null}.
*/ public void repaintDuringNextViewUpdate() { viewRepaintNeeded = true; + startRenderThreadIfReady(); } /** @@ -972,6 +1012,12 @@ public class ViewPanel extends Canvas { * @return measured frames per second */ public double getMeasuredFPS() { + // The window rolls over only when a frame is blitted; once frames + // stop (on-demand renderer idling), the stale rate would report + // forever. No blit within two windows => the pipeline is idle. + if (fpsWindowStartNanos != 0 + && System.nanoTime() - fpsWindowStartNanos > 1_000_000_000L) + return 0; return measuredFPS; } diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GiCentroidCache.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GiCentroidCache.java new file mode 100644 index 0000000..722669e --- /dev/null +++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/GiCentroidCache.java @@ -0,0 +1,72 @@ +/* + * Aukio 3D engine. Author: Svjatoslav Agejenko. + * This project is released under Creative Commons Zero (CC0) license. + */ +package eu.svjatoslav.aukio.e3d.renderer.raster.gi; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * RAM cache of per-triangle CENTROID lighting (stage-1 direct plus + * stage-2 first-bounce indirect), keyed by the same 64-bit geometry + * hash as the lightmap cache. Streaming worlds (FO4 cells) rebuild + * the GI snapshot on every cell swap, which used to re-run stage 1 + * (millions of shadow rays) and stage 2 (100k+ centroid bounces) for + * triangles that had not changed at all; a cache hit restores both + * single-color results instantly (bugreport-20261005-220333). + * RAM-only, per GI instance â nothing is persisted to disk. + * + *Values are validated against the light signature: any light or + * sky change misses. Neighboring geometry is NOT part of the key â + * the same tradeoff the lightmap cache already takes: a restored + * shadow/bounce may briefly reflect occluders that streamed away; + * the per-texel stages (3+) still recompute normally.
+ * + *Capacity is capped ({@code e3d.giCentroidCacheEntries}, default + * 4 000 000 â ~120 bytes per entry, sized to hold a full streamed + * FO4 world); eviction is least-recently-used. Thread-safe.
+ */ +final class GiCentroidCache { + + /** One triangle's centroid record. */ + static final class Entry { + float directR, directG, directB; + float indirectR, indirectG, indirectB; + /** Stage-2 delta: the gather source of the next bounce. */ + float deltaPrevR, deltaPrevG, deltaPrevB; + long visibleBits, knownBits; + /** True when the stage-2 centroid bounce had run. */ + boolean bounced; + /** Lighting signature under which the values were computed. */ + double lightSignature; + } + + private final LinkedHashMapGenerations: the scene is lit generation by generation, each - * walking all snapshot entries near-to-far from the camera, with a - * global barrier between generations:
+ *Generations: the scene is lit pass by pass, each walking + * all snapshot entries near-to-far from the camera, with a global + * barrier between passes:
*Two sampling resolutions:
*Radius gating ({@code e3d.giStage2Radius/ giStage3Radius/ + * giStage4Radius} in {@code ~/.config/aukio/config.yaml}, or the + * corresponding {@code -De3d.gi.stage*Radius} properties): in huge + * streaming worlds the full-scene stages would never reach the camera + * area, so each stage past 1 can be limited to a distance bubble around + * the camera. Entries beyond the stage-2 radius keep their stage-1 + * direct stamp; lightmapped triangles beyond the stage-3 radius keep + * the stage-2 display and never allocate texels; lightmaps beyond the + * stage-4 radius are never refined to full density. Eligibility is + * re-evaluated from the LIVE camera position at every generation + * barrier, so the bubble follows the camera; entries that become + * eligible after the bake converged get a local catch-up (one bounce + * against the frozen converged field). Stage 1 stays global on purpose: + * bounce rays read the hit surface's stage-1 visibility bits + * everywhere. Mesh-block triangles additionally gain per-texel + * lightmaps inside the stage-3 bubble (they are the only geometry kind + * in streaming game worlds); their composites carry the block's photo + * texture resampled into lightmap space, and finished composites are + * kept in a geometry-keyed {@link LightmapCache} so a cell that streams + * out and back in restores its lightmaps instantly. A stage-3 radius of + * 0 disables mesh-block lightmapping entirely (the historical + * behavior).
+ * *Usage:
*{@code
* GlobalIllumination gi = viewPanel.enableGlobalIllumination(); // 2 threads
@@ -121,12 +155,33 @@ public class GlobalIllumination implements GiLightProvider {
/** Minimum interval between composite texture updates. */
private static final long COMPOSITE_INTERVAL_MS = 500;
- /** Per-light visibility is tracked for at most this many lights. */
- private static final int MAX_TRACKED_LIGHTS = 16;
+ /**
+ * Per-light visibility is tracked for at most this many lights
+ * (lights beyond the cap are ignored by GI: no shadow rays, no
+ * direct contribution in composites). Read per use so a demo can
+ * size it to its scene before the bake starts.
+ * {@code -De3d.gi.maxLights}.
+ */
+ private static int maxTrackedLights() {
+ return Integer.getInteger("e3d.gi.maxLights", 16);
+ }
/** Debug statistics with {@code -De3d.gi.debug}. */
private static final boolean DEBUG = Boolean.getBoolean("e3d.gi.debug");
+ /**
+ * Sky dome illumination scale: the displayed sky color is usually
+ * picked for looks, and reads far brighter than lamp-lit surfaces
+ * (7AA3D8 ~ 200 vs a sun-lit wall ~ 110) â feeding it raw as dome
+ * radiance floods shadowed faces to near-white. The bounce
+ * contribution of an escaped ray is
+ * {@code BOUNCE_GAIN x sky x this scale}. {@code -De3d.gi.skyScale},
+ * default 0.5 (sky clearly lifts shadowed faces, sun stays dominant;
+ * ~0.65+ starts to look foggy at aerial poses).
+ */
+ private static final double SKY_SCALE =
+ Double.parseDouble(System.getProperty("e3d.gi.skyScale", "0.5"));
+
/** Albedo for snapshot entries that carry no flat color (textured triangles). */
private static final Color FALLBACK_ALBEDO = new Color(128, 128, 128);
@@ -138,6 +193,40 @@ public class GlobalIllumination implements GiLightProvider {
private static final int MAX_GENERATIONS =
Integer.parseInt(System.getProperty("e3d.gi.generations", "6"));
+ // The bake always runs the full staged pipeline (Documentation/
+ // Global illumination, "Polygons are illuminated in the following
+ // order"): stage 1 uniform centroid direct â stage 2 centroid
+ // bounce â stage 3 coarse per-texel lightmap bake â stage 4
+ // full-resolution refine. The coarse bake converges first
+ // (progressive display within seconds), then every radius-eligible
+ // lightmap refine()s and the fine bake converges at the configured
+ // units-per-texel. The coarse field seeds the DISPLAY only, never
+ // the solver: carrying it into the accumulated indirect would
+ // count the Neumann series twice.
+
+ /**
+ * Stage-3 lightmap coarsening: units-per-texel multiplier (4 = 1/16
+ * of the full-resolution texel count, before power-of-two rounding
+ * and the 4-texel floor). {@code -De3d.gi.stage3TexelFactor}.
+ */
+ private static final double STAGE3_TEXEL_FACTOR =
+ Double.parseDouble(System.getProperty("e3d.gi.stage3TexelFactor", "4"));
+
+ /**
+ * Units-per-texel that lightmap construction should use while the
+ * pipeline starts coarse (stage 3): the configured value scaled by
+ * {@link #STAGE3_TEXEL_FACTOR}. Callers pass the fine value when
+ * constructing at final resolution (fine phase, or late entrants
+ * after the bake). Read at {@link LightmappedTriangle} construction
+ * time â changing it takes effect on the next render-list rebuild.
+ *
+ * @param base the composite's configured units per texel
+ * @return the effective units per texel for new lightmaps
+ */
+ public static double lightmapUnitsPerTexel(final double base) {
+ return base * STAGE3_TEXEL_FACTOR;
+ }
+
/**
* Bounce rays per texel (or polygon) per generation, averaged as a
* plain mean. Total rays per texel over a full bake is roughly this
@@ -198,22 +287,157 @@ public class GlobalIllumination implements GiLightProvider {
/** Serializes generation barriers. */
private final Object genLock = new Object();
+ /**
+ * Status snapshot for the developer-tools GI row (also handy in
+ * logs). Distances are in world units, derived from the near-to-far
+ * work queue: the queue drains nearest-first, so
+ * {@link #coveredDistance} grows as the active stage progresses â a
+ * frozen value with work remaining means the bake is stuck.
+ */
+ public static final class Status {
+ /** True after {@link #start()} and before {@link #stop()}. */
+ public boolean running;
+ /** True once the bake converged (workers idle / catch-up watch). */
+ public boolean baked;
+ /** Coarse (stage 3) vs fine (stage 4) phase of the staged pipeline. */
+ public boolean finePhase;
+ /** Raw generation counter (0 = stage 1, 1 = per-texel direct, >=2 = bounces). */
+ public int generation;
+ /** Display stage 1-4 mapped from generation/phase (0 = none yet). */
+ public int stage;
+ /** Triangles in the current snapshot. */
+ public int entries;
+ /** Work items in the active generation's queue. */
+ public int queueLength;
+ /** Items already drained from it (progress within the stage). */
+ public int queueDone;
+ /** Camera distance of the entry the queue cursor sits at; NaN
+ * when distance ordering is disabled. */
+ public double coveredDistance = Double.NaN;
+ /** Entries inside each stage's radius at the last evaluation. */
+ public int stage2eligible, stage3eligible, stage4eligible;
+ /** Late radius entrants waiting for catch-up. */
+ public int catchUpPending;
+ /** Baked lightmaps preserved for stream-out/in restore. */
+ public int cacheSize;
+ /** Stage-1/2 centroid records preserved across snapshot rebuilds. */
+ public int centroidCacheSize;
+ /** Effective (override-aware) stage radii, 0 = unlimited. */
+ public double stage2Radius, stage3Radius, stage4Radius;
+ }
+
+ /**
+ * Reads a consistent-enough status snapshot for display; safe to
+ * call from any thread (UI polls it a few times a second).
+ *
+ * @return the current GI status
+ */
+ public Status getStatus() {
+ final Status status = new Status();
+ status.running = running;
+ status.cacheSize = lightmapCache.size();
+ status.centroidCacheSize = centroidCache.size();
+ status.stage2Radius = stage2Radius();
+ status.stage3Radius = stage3Radius();
+ status.stage4Radius = stage4Radius();
+ final Snapshot snap = snapshot;
+ if (snap == null)
+ return status;
+ status.entries = snap.entries.size();
+ status.baked = snap.baked;
+ status.finePhase = snap.finePhase;
+ status.generation = snap.generation;
+ if (status.baked)
+ status.stage = 0;
+ else if (snap.finePhase)
+ status.stage = 4;
+ else if (snap.generation == 0)
+ status.stage = 1;
+ else if (snap.generation == 2)
+ status.stage = 2;
+ else
+ status.stage = 3;
+ status.queueLength = snap.queue.length;
+ final int cursor = Math.min(snap.cursor.get(), snap.queue.length);
+ status.queueDone = cursor;
+ if (cameraPosition != null && snap.queue.length > 0) {
+ final TriangleBvh.Entry at = snap.queue[
+ cursor < snap.queue.length ? cursor : snap.queue.length - 1];
+ status.coveredDistance = Math.sqrt(at.distance);
+ }
+ status.stage2eligible = snap.eligible2;
+ status.stage3eligible = snap.eligible3;
+ status.stage4eligible = snap.eligible4;
+ status.catchUpPending = snap.catchUpQueue.size();
+ return status;
+ }
+
+ /** Baked-composite cache for radius-created lightmaps (cell stream-out survival). */
+ private final LightmapCache lightmapCache =
+ new LightmapCache(EngineConfig.getGiLightmapCacheEntries());
+ /** Stage-1/2 centroid cache for snapshot-rebuild survival
+ * (bugreport-20261005-220333): single-color values, cheap to keep. */
+ private final GiCentroidCache centroidCache =
+ new GiCentroidCache(EngineConfig.getGiCentroidCacheEntries());
+
+ // --- Catch-up watcher state (baked snapshots, radii active) ---
+ /** Wall time of the last catch-up eligibility evaluation. */
+ private long lastCatchUpEval;
+ /** Camera position at the last catch-up evaluation (NaN = never). */
+ private double lastEvalCamX = Double.NaN, lastEvalCamY, lastEvalCamZ;
+ /** Single-flights the catch-up eligibility scan across idle workers. */
+ private final java.util.concurrent.atomic.AtomicBoolean catchUpScanInFlight =
+ new java.util.concurrent.atomic.AtomicBoolean();
+
private static class Snapshot {
List entries;
TriangleBvh bvh;
List lights;
IdentityHashMap lightIndex;
double ambientR, ambientG, ambientB;
- /** All lightmaps in the snapshot (for composite updates). */
- List lightmaps;
+ /** Sky dome color (bounce rays that escape the scene sample it);
+ * zeroed when sky sampling is off. */
+ double skyR, skyG, skyB;
+ /** True when a non-black sky color is declared for this snapshot. */
+ boolean skyEnabled;
+ /** All lightmaps in the snapshot (for composite updates).
+ * Copy-on-write: the barrier appends radius-created lightmaps
+ * while timed composite updates iterate. */
+ java.util.concurrent.CopyOnWriteArrayList lightmaps;
/** Work queue of the active generation, sorted near-to-far. */
TriangleBvh.Entry[] queue;
+ /** The full distance-sorted candidate list (every entry);
+ * {@link #queue} is the per-generation eligible subset of it. */
+ TriangleBvh.Entry[] queueAll;
/** Next queue index to sample (workers overshoot into nulls once drained). */
final AtomicInteger cursor = new AtomicInteger();
/** Entries currently being sampled (the barrier waits for zero). */
final AtomicInteger inFlight = new AtomicInteger();
- /** The generation currently being sampled: 1 = direct, k = k-th bounce. */
- volatile int generation = 1;
+ /** True once a per-texel direct pass has completed for this
+ * snapshot (late-created lightmaps must trace their own
+ * direct). */
+ volatile boolean directDone;
+ /** Entries that became radius-eligible after the bake converged;
+ * drained by idle workers (local catch-up). */
+ final java.util.concurrent.ConcurrentLinkedQueue
+ catchUpQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
+ /** Entries inside each stage's radius at the last
+ * {@link GlobalIllumination#evalEligibility} (status display). */
+ volatile int eligible2, eligible3, eligible4;
+ /**
+ * The pass currently being sampled: 0 = stage 1 (uniform
+ * centroid direct preview for ALL entries), 1 = per-texel
+ * direct (lightmaps only; never scheduled while stages beyond
+ * 2 are deactivated), k >= 2 = the (k-1)-th bounce.
+ */
+ volatile int generation = 0;
+ /**
+ * Stage 4: false while the COARSE bake runs, true after
+ * {@link Lightmap#refine()} switched the lightmaps to final
+ * resolution and the bake restarted from generation 1. Other
+ * stages: always false.
+ */
+ volatile boolean finePhase;
/** True once the bake has completed; workers idle until the next rebuild. */
volatile boolean baked;
}
@@ -230,6 +454,17 @@ public class GlobalIllumination implements GiLightProvider {
float deltaCurR, deltaCurG, deltaCurB;
volatile long visibleBits; // per-light: shadow ray says visible
volatile long knownBits; // per-light: visibility computed at least once
+ /** True once a centroid bounce (stage 2 or catch-up) has run for
+ * this entry; the catch-up watcher uses it to find entries that
+ * became eligible only after the bake. */
+ volatile boolean bounced;
+ /** True once stage 1 has written the direct stamp (centroid
+ * cache harvests only completed values). */
+ volatile boolean directDone;
+ /** True when stage-1/2 values came from the centroid cache at
+ * snapshot build instead of being traced (bugreport-20261005-220333):
+ * stage 1 and the stage-2 centroid bounce skip this entry. */
+ volatile boolean restored;
}
/**
@@ -276,6 +511,68 @@ public class GlobalIllumination implements GiLightProvider {
this.cameraPosition = cameraPosition;
}
+ /** Per-instance radius-gating overrides (null = EngineConfig value).
+ * Volatile: set by the UI thread before {@link #start()}, read by
+ * the GI workers. */
+ private volatile Double stage2RadiusOverride;
+ private volatile Double stage3RadiusOverride;
+ private volatile Double stage4RadiusOverride;
+ /** Per-instance mesh-block lightmap density override (null =
+ * EngineConfig giMeshUnitsPerTexel). */
+ private volatile Double meshUnitsPerTexelOverride;
+
+ /**
+ * Overrides the radius-gating config values for THIS GI system only
+ * (EngineConfig giStage2/3/4Radius untouched). Needed when one JVM
+ * hosts scenes of wildly different scales (the demo launcher: an FO4
+ * cell at 1 unit = 1.43 cm vs a 48 000-unit procedural district) â
+ * a global -D/config.yaml value cannot fit both. Pass null to keep
+ * the configured value for a stage.
+ *
+ * Call BEFORE {@link #start()} (or via the ViewPanel
+ * enable-overload that applies it pre-start) so the first
+ * eligibility evaluation already uses the overrides.
+ */
+ public void setRadiusOverrides(final Double stage2, final Double stage3,
+ final Double stage4) {
+ stage2RadiusOverride = stage2;
+ stage3RadiusOverride = stage3;
+ stage4RadiusOverride = stage4;
+ }
+
+ /**
+ * Overrides the mesh-block lightmap texel density for THIS GI system
+ * (EngineConfig giMeshUnitsPerTexel untouched). Call before
+ * {@link #start()}; see {@link #setRadiusOverrides}.
+ */
+ public void setMeshUnitsPerTexelOverride(final Double unitsPerTexel) {
+ meshUnitsPerTexelOverride = unitsPerTexel;
+ }
+
+ /** Effective stage-2 radius: override when set, else EngineConfig. */
+ private double stage2Radius() {
+ final Double o = stage2RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage2Radius();
+ }
+
+ /** Effective stage-3 radius: override when set, else EngineConfig. */
+ private double stage3Radius() {
+ final Double o = stage3RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage3Radius();
+ }
+
+ /** Effective stage-4 radius: override when set, else EngineConfig. */
+ private double stage4Radius() {
+ final Double o = stage4RadiusOverride;
+ return o != null ? o : EngineConfig.getGiStage4Radius();
+ }
+
+ /** Effective mesh-block texel density: override, else EngineConfig. */
+ private double meshUnitsPerTexel() {
+ final Double o = meshUnitsPerTexelOverride;
+ return o != null ? o : EngineConfig.getGiMeshUnitsPerTexel();
+ }
+
/** Registers the GI provider and starts the worker threads. */
public void start() {
if (running)
@@ -385,7 +682,16 @@ public class GlobalIllumination implements GiLightProvider {
if (snap.baked) {
// Bake complete: idle until a scene/light change
// rebuilds the snapshot and restarts from generation 1.
- Thread.sleep(IDLE_SLEEP_MS);
+ // With radius gating, idle workers first drain the
+ // catch-up queue (entries that became eligible when
+ // the camera moved into them after convergence).
+ final TriangleBvh.Entry late = snap.catchUpQueue.poll();
+ if (late != null) {
+ runCatchUp(snap, late, hit, pos, target);
+ } else {
+ scanCatchUp(snap);
+ Thread.sleep(IDLE_SLEEP_MS);
+ }
continue;
}
@@ -438,43 +744,81 @@ public class GlobalIllumination implements GiLightProvider {
// The generation cannot advance while this entry is in flight
// (the barrier waits for zero in-flight entries), so the read is
// stable for the whole pass.
- if (snap.generation == 1)
+ final int generation = snap.generation;
+ if (generation == 0) {
+ stage1Pass(snap, entry, pos); // stage 1 is deliberately global
+ return;
+ }
+ // Radius gating: the queue was already filtered to this
+ // generation's eligible subset at the barrier; this is the
+ // belt-and-braces re-check (masks are stable for the whole
+ // generation, re-evaluated only at barriers). Skipped entries
+ // leave their accumulators at zero and do not count toward the
+ // termination mean.
+ if (!generationIncludes(entry, generation, snap.finePhase))
+ return;
+ if (generation == 1)
directPass(snap, entry, pos);
else
- bouncePass(snap, entry, snap.generation, hit, pos, target);
+ bouncePass(snap, entry, generation, hit, pos, target);
+ }
+
+ /**
+ * Would {@link #processEntry} do real work for this entry in the
+ * given generation? Single source of truth for radius gating: the
+ * barrier filters the work queue with it AND the worker re-checks
+ * with it. Generation 0 (stage 1) is deliberately global.
+ */
+ private static boolean generationIncludes(final TriangleBvh.Entry entry,
+ final int generation,
+ final boolean finePhase) {
+ if (generation == 0)
+ return true;
+ final Lightmap lightmap = entry.lightmap;
+ final boolean perTexel = lightmap != null
+ && (generation >= 3 || finePhase && generation >= 2);
+ if (perTexel || generation == 1)
+ // Per-texel pass: stage-3 bit in the coarse phase,
+ // stage-4 bit in the fine phase.
+ return (entry.eligibleStages & (finePhase ? 4 : 2)) != 0;
+ return (entry.eligibleStages & 1) != 0; // centroid bounce: stage-2 bit
+ }
+
+ /**
+ * The work list for one generation: the full distance-sorted
+ * candidate array filtered down to the entries the generation will
+ * actually process ({@link #generationIncludes}). Beyond-radius
+ * entries were previously queued anyway and skipped one by one at
+ * consume time â a million-entry no-op scan per generation that
+ * also made the dev-panel "queue x/y" read the whole scene instead
+ * of the eligible subset (bugreport-20261005-212907).
+ */
+ private static TriangleBvh.Entry[] eligibleQueue(final Snapshot snap,
+ final int generation,
+ final boolean finePhase) {
+ if (generation == 0)
+ return snap.queueAll; // stage 1 is deliberately global
+ return java.util.Arrays.stream(snap.queueAll)
+ .filter(e -> generationIncludes(e, generation, finePhase))
+ .toArray(TriangleBvh.Entry[]::new);
}
// ------------------------------------------------------------------
- // Generation 1: direct light. Lightmaps trace every texel against
- // every light and cache the visibility bytes; plain polygons and
- // mesh blocks get one centroid evaluation (their final resolution).
+ // Stage 1 (generation 0): uniform centroid direct preview for EVERY
+ // entry â the whole scene shows per-polygon direct light with
+ // shadows before any per-texel work begins. Lightmapped triangles
+ // display it through the per-triangle GI shade stamped on the
+ // triangle (no texel work); plain polygons and mesh blocks record
+ // their final-resolution state exactly as before.
// ------------------------------------------------------------------
- private void directPass(final Snapshot snap, final TriangleBvh.Entry entry,
+ private void stage1Pass(final Snapshot snap, final TriangleBvh.Entry entry,
final double[] pos) {
- final int lightCount = snap.lights.size();
- final int tracked = Math.min(lightCount, MAX_TRACKED_LIGHTS);
+ final GiState cached = states.get(stateKey(entry));
+ if (cached != null && cached.restored)
+ return; // restored at snapshot build; display already written
final Lightmap lightmap = entry.lightmap;
- if (lightmap != null) {
- lightmap.ensureArrays(lightCount);
- for (final int texel : lightmap.validTexels) {
- lightmap.texelWorldPosition(texel, pos);
- final double ox = pos[0] + lightmap.normalX * ORIGIN_EPSILON;
- final double oy = pos[1] + lightmap.normalY * ORIGIN_EPSILON;
- final double oz = pos[2] + lightmap.normalZ * ORIGIN_EPSILON;
- for (int i = 0; i < tracked; i++)
- lightmap.lightVisibility[texel * lightCount + i] =
- shadowTest(snap, ox, oy, oz,
- lightmap.normalX, lightmap.normalY, lightmap.normalZ,
- snap.lights.get(i))
- ? Lightmap.VISIBILITY_VISIBLE : Lightmap.VISIBILITY_OCCLUDED;
- }
- lightmap.generation = 1;
- return;
- }
-
- // Plain polygon / mesh-block triangle: one centroid evaluation.
final double nx = entry.normal[0];
final double ny = entry.normal[1];
final double nz = entry.normal[2];
@@ -482,8 +826,9 @@ public class GlobalIllumination implements GiLightProvider {
final double oy = entry.centroidY + ny * ORIGIN_EPSILON;
final double oz = entry.centroidZ + nz * ORIGIN_EPSILON;
- double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
+ final int tracked = Math.min(snap.lights.size(), maxTrackedLights());
final boolean[] visible = new boolean[tracked];
+ double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
for (int i = 0; i < tracked; i++) {
final LightSource light = snap.lights.get(i);
visible[i] = shadowTest(snap, ox, oy, oz, nx, ny, nz, light);
@@ -526,10 +871,59 @@ public class GlobalIllumination implements GiLightProvider {
state.deltaPrevR = 0;
state.deltaPrevG = 0;
state.deltaPrevB = 0;
+ state.bounced = false;
+ state.directDone = true;
}
if (entry.block != null)
entry.block.setGiLight(entry.blockTri,
state.directR, state.directG, state.directB);
+ // The uniform stamp is the lightmapped triangle's ONLY
+ // lighting display until the first composite lands (stage 3),
+ // so stamp it from the recorded stage-1 state â the same
+ // centroid direct value, plus the per-lamp visibility bits
+ // that stage-2 bounce rays read at hits on this triangle.
+ if (lightmap != null && !lightmap.everComposited && lightmap.owner != null)
+ lightmap.owner.setGiShade(state.directR, state.directG, state.directB);
+ }
+
+ // ------------------------------------------------------------------
+ // Generation 1: per-texel direct light for lightmaps. Every texel
+ // casts shadow rays against every light and caches the visibility
+ // bytes. Plain polygons and mesh-block triangles were already
+ // evaluated at their (final) centroid resolution in stage 1.
+ // ------------------------------------------------------------------
+
+ private void directPass(final Snapshot snap, final TriangleBvh.Entry entry,
+ final double[] pos) {
+ final int lightCount = snap.lights.size();
+ final int tracked = Math.min(lightCount, maxTrackedLights());
+ final Lightmap lightmap = entry.lightmap;
+
+ if (lightmap == null)
+ return; // centroid-evaluated in stage 1: final resolution
+ if (lightmap.directBaked)
+ // Cache-restored or already traced this phase: finished
+ // lightmaps stay out of the bake. (Guard on directBaked,
+ // not baked: a lightmap that sat outside the stage-3
+ // radius all bake long is baked=true from the terminal
+ // freeArrays yet still needs its direct trace.)
+ return;
+
+ lightmap.ensureArrays(lightCount);
+ for (final int texel : lightmap.validTexels) {
+ lightmap.texelWorldPosition(texel, pos);
+ final double ox = pos[0] + lightmap.normalX * ORIGIN_EPSILON;
+ final double oy = pos[1] + lightmap.normalY * ORIGIN_EPSILON;
+ final double oz = pos[2] + lightmap.normalZ * ORIGIN_EPSILON;
+ for (int i = 0; i < tracked; i++)
+ lightmap.lightVisibility[texel * lightCount + i] =
+ shadowTest(snap, ox, oy, oz,
+ lightmap.normalX, lightmap.normalY, lightmap.normalZ,
+ snap.lights.get(i))
+ ? Lightmap.VISIBILITY_VISIBLE : Lightmap.VISIBILITY_OCCLUDED;
+ }
+ lightmap.generation = 1;
+ lightmap.directBaked = true;
}
// ------------------------------------------------------------------
@@ -543,7 +937,13 @@ public class GlobalIllumination implements GiLightProvider {
final int generation, final TriangleBvh.Hit hit,
final double[] pos, final double[] target) {
final Lightmap lightmap = entry.lightmap;
- if (lightmap != null) {
+ // Per-texel bounce: coarse phase from generation 3 on, fine
+ // phase (stage 4) from its generation 2 on â the coarse
+ // phase's generation 2 is a CENTROID bounce for every entry.
+ if (lightmap != null && (generation >= 3
+ || snap.finePhase && generation >= 2)) {
+ if (lightmap.baked)
+ return; // cache-restored: finished lightmaps stay out of the bake
final double nx = lightmap.normalX;
final double ny = lightmap.normalY;
final double nz = lightmap.normalZ;
@@ -566,6 +966,21 @@ public class GlobalIllumination implements GiLightProvider {
return;
}
+ // Plain polygons and mesh blocks finish at stage 2 â coarse
+ // generations 3+ and the ENTIRE fine phase are lightmap-only
+ // work. Skipping also freezes their deltaPrev at zero (the
+ // barrier publishes the untouched zero accumulator), so later
+ // bounce generations never re-gather their exhausted stage-2
+ // delta.
+ if (lightmap == null && (generation >= 3 || snap.finePhase))
+ return;
+
+ // Centroid bounce (generation 2 â the pipeline's stage 2 is
+ // per-polygon uniform): every plain polygon, mesh-block
+ // triangle and lightmapped entry.
+ final GiState prior = states.get(stateKey(entry));
+ if (prior != null && prior.restored && prior.bounced)
+ return; // stage-2 value restored at snapshot build; keep deltaCur zero
final double nx = entry.normal[0];
final double ny = entry.normal[1];
final double nz = entry.normal[2];
@@ -585,6 +1000,7 @@ public class GlobalIllumination implements GiLightProvider {
state.deltaCurR = meanR;
state.deltaCurG = meanG;
state.deltaCurB = meanB;
+ state.bounced = true;
}
}
@@ -595,7 +1011,9 @@ public class GlobalIllumination implements GiLightProvider {
* hit surface's previous-generation delta, so each generation adds
* exactly one more light bounce.
*
- * @param out receives the radiance contribution {r, g, b}; zeros on a miss
+ * @param out receives the radiance contribution {r, g, b}; the sky
+ * dome color on an escape (miss) when sky sampling is
+ * on, zeros otherwise
*/
private void gatherTarget(final Snapshot snap, final int generation,
final double nx, final double ny, final double nz,
@@ -605,19 +1023,52 @@ public class GlobalIllumination implements GiLightProvider {
out[1] = 0;
out[2] = 0;
final double[] dir = cosineHemisphere(nx, ny, nz, ThreadLocalRandom.current());
- if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit))
+ if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit)) {
+ // Ray escaped the scene: the sky dome emits its displayed
+ // color â the same convention as a white surface irradiated
+ // to that color (radiance = BOUNCE_GAIN x color), tamed by
+ // SKY_SCALE because display-picked sky colors read far
+ // brighter than lamp-lit surfaces.
+ if (snap.skyEnabled) {
+ out[0] = BOUNCE_GAIN * snap.skyR * SKY_SCALE;
+ out[1] = BOUNCE_GAIN * snap.skyG * SKY_SCALE;
+ out[2] = BOUNCE_GAIN * snap.skyB * SKY_SCALE;
+ }
return;
+ }
final double eR, eG, eB;
- if (generation == 2) {
+ // Coarse phase's first per-texel bounce (generation 3) gathers
+ // the stage-2 TOTAL at the hit â direct + stage-2 indirect â
+ // folding bounces 1 and 2 into one coarse generation. The fine
+ // phase runs the plain generation chain (its generation 2
+ // gathers fine direct only); its plain-polygon hits read the
+ // polygon's frozen total once (direct + stage-2 indirect), then
+ // never again. Lightmapped hits in the fine phase never read the
+ // stale stage-2 GiState â the coarse field lives on in their
+ // seeded arrays, and re-adding it would double-count.
+ final boolean gathersStage2Total = !snap.finePhase && generation == 3;
+ final boolean gathersPlainTotal = gathersStage2Total
+ || snap.finePhase && generation == 2
+ && hit.entry.lightmap == null;
+ if (generation == 2 || gathersStage2Total) {
// Direct irradiance at the hit point (clamped to display
// range): light near a lamp can sum far beyond 255, and
// feeding unbounded energy into the bounce loop saturates
// the scene.
- final double[] irr = directIrradiance(snap, hit);
- eR = irr[0];
- eG = irr[1];
- eB = irr[2];
+ final double[] irr = directIrradiance(snap, hit, generation);
+ double r = irr[0], g = irr[1], b = irr[2];
+ if (gathersPlainTotal) {
+ final GiState hitState = states.get(stateKey(hit.entry));
+ if (hitState != null) {
+ r += hitState.indirectR;
+ g += hitState.indirectG;
+ b += hitState.indirectB;
+ }
+ }
+ eR = r;
+ eG = g;
+ eB = b;
} else {
final TriangleBvh.Entry hitEntry = hit.entry;
if (hitEntry.lightmap != null) {
@@ -670,15 +1121,34 @@ public class GlobalIllumination implements GiLightProvider {
double energy = 0;
long units = 0;
if (finished >= 2) {
+ // Lightmap texel arrays only exist once the per-texel
+ // direct pass has run (generation 1 is scheduled AFTER
+ // the stage-2 centroid bounce). Skip lightmaps whose
+ // arrays were never allocated â rollover() would
+ // dereference null.
+ // Per-texel passes of the finished generation were
+ // gated by this eligibility bit (radius gating).
+ final int bit = snap.finePhase ? 4 : 2;
for (final Lightmap lightmap : snap.lightmaps) {
+ if (lightmap.deltaCurR == null)
+ continue;
energy += lightmap.rollover();
- units += lightmap.validTexels.length;
+ // Radius-skipped lightmaps contribute no units:
+ // their zero deltas must not dilute the
+ // termination mean.
+ if ((lightmap.eligibleStages & bit) != 0)
+ units += lightmap.validTexels.length;
}
- for (final GiState state : states.values()) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final GiState state = states.get(stateKey(entry));
+ if (state == null)
+ continue;
synchronized (state) {
energy += Math.max(Math.abs(state.deltaCurR),
Math.max(Math.abs(state.deltaCurG), Math.abs(state.deltaCurB)));
- units++;
+ if (centroidWorked(finished, entry, snap.finePhase)
+ && (entry.eligibleStages & 1) != 0)
+ units++;
state.indirectR += state.deltaCurR;
state.indirectG += state.deltaCurG;
state.indirectB += state.deltaCurB;
@@ -702,10 +1172,22 @@ public class GlobalIllumination implements GiLightProvider {
state.directG + state.indirectG,
state.directB + state.indirectB);
}
+ // Stage 2 done: raise every lightmapped triangle's
+ // uniform stamp to the stage-2 display (direct +
+ // first-bounce indirect) until its first composite
+ // lands.
+ if (finished == 2)
+ publishStage2Display(snap);
}
+ if (finished == 1)
+ snap.directDone = true;
+ // Refresh the radius-gating masks from the LIVE camera
+ // position: what comes next (refine set, next generation's
+ // skips, new lightmap creation) follows the camera.
+ evalEligibility(snap);
final double meanDelta = units == 0 ? 0 : energy / units;
- if (finished >= MAX_GENERATIONS || (finished >= 2 && meanDelta < DELTA_THRESHOLD)) {
+ if (finished >= generationCap() || (finished >= 2 && meanDelta < DELTA_THRESHOLD)) {
// Final composite with no sampling in flight, then free
// all per-texel state. Holding the composite single-flight
// keeps a concurrent timed updateComposites from racing
@@ -713,29 +1195,610 @@ public class GlobalIllumination implements GiLightProvider {
while (!compositeUpdateInFlight.compareAndSet(false, true))
Thread.yield();
try {
- for (final Lightmap lightmap : snap.lightmaps) {
- compositeLightmap(snap, lightmap);
- lightmap.freeArrays();
+ if (!snap.finePhase) {
+ // Stage 4: the coarse bake converged â switch
+ // radius-eligible lightmaps to their final
+ // resolution and restart the bake from
+ // generation 1 (direct). refine() upscales the
+ // shown composite, so the display does not
+ // regress at the transition; the solver itself
+ // restarts from zero. Lightmaps beyond the
+ // stage-4 radius finalize at coarse resolution:
+ // the coarse composite is their terminal display
+ // (re-armed for a fine catch-up if the camera
+ // approaches later).
+ for (final Lightmap lightmap : snap.lightmaps) {
+ if ((lightmap.eligibleStages & 4) != 0) {
+ lightmap.refine();
+ } else {
+ compositeLightmap(snap, lightmap);
+ cacheStore(lightmap);
+ lightmap.freeArrays();
+ }
+ }
+ snap.finePhase = true;
+ snap.generation = 1;
+ snap.directDone = false;
+ // Queue BEFORE the cursor reset: workers see the
+ // new cursor only via the AtomicInteger's
+ // volatile write, which publishes the queue
+ // assignment that precedes it.
+ snap.queue = eligibleQueue(snap, 1, true);
+ snap.cursor.set(0);
+ createBlockLightmaps(snap);
+ if (DEBUG)
+ System.out.println("[GI] coarse bake done after generation "
+ + finished + " â refining to final resolution");
+ } else {
+ for (final Lightmap lightmap : snap.lightmaps) {
+ compositeLightmap(snap, lightmap);
+ cacheStore(lightmap);
+ lightmap.freeArrays();
+ }
+ snap.baked = true;
}
- snap.baked = true;
} finally {
compositeUpdateInFlight.set(false);
}
- if (DEBUG)
+ if (DEBUG && snap.baked)
System.out.println("[GI] bake done after generation " + finished
+ ", mean delta " + String.format("%.3f", meanDelta)
+ " â texel arrays freed");
} else {
- snap.generation = finished + 1;
+ final int next = nextGeneration(finished, snap.finePhase);
+ snap.generation = next;
+ // Queue BEFORE the cursor reset (visibility ordering,
+ // see the fine-phase restart above).
+ snap.queue = eligibleQueue(snap, next, snap.finePhase);
snap.cursor.set(0);
+ // Newly radius-eligible block triangles get their
+ // lightmaps now, so the upcoming generations see them.
+ createBlockLightmaps(snap);
if (DEBUG)
- System.out.println("[GI] generation " + finished + " done, mean delta "
+ System.out.println("[GI] " + (finished == 0 ? "stage 1 (uniform direct preview)"
+ : "generation " + finished) + " done, mean delta "
+ String.format("%.3f", meanDelta)
- + " -> generation " + (finished + 1));
+ + " -> generation " + next);
}
}
}
+ /**
+ * Generation at which each phase's bake stops. Applies per phase:
+ * the coarse bake and the fine bake each get the full allowance;
+ * either may stop earlier on the delta threshold.
+ */
+ private static int generationCap() {
+ return MAX_GENERATIONS;
+ }
+
+ /**
+ * The pass to schedule after {@code finished}. The coarse phase
+ * inserts the centroid bounce before the per-texel work: 0 -> 2
+ * -> 1 -> 3 -> 4 -> ... (generation 3 is the first
+ * per-texel bounce). The fine phase runs plain 0 -> 1 -> 2
+ * -> ....
+ */
+ private static int nextGeneration(final int finished, final boolean finePhase) {
+ if (finePhase)
+ return finished + 1;
+ if (finished == 0)
+ return 2; // stage 2: centroid bounce, every entry
+ if (finished == 2)
+ return 1; // per-texel direct (lightmaps)
+ if (finished == 1)
+ return 3; // first per-texel bounce
+ return finished + 1;
+ }
+
+ /**
+ * Stage-2 display hand-off: at the generation-2 barrier every
+ * lightmapped triangle's uniform stamp is raised from its stage-1
+ * direct triplet to direct + first-bounce indirect â the stage-2
+ * display, texture x (ambient + direct + first bounce). Lightmaps
+ * that once showed a real composite keep it.
+ */
+ private void publishStage2Display(final Snapshot snap) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap == null || lightmap.owner == null || lightmap.everComposited)
+ continue;
+ final GiState state = states.get(stateKey(entry));
+ if (state == null)
+ continue;
+ lightmap.owner.setGiShade(
+ state.directR + state.indirectR,
+ state.directG + state.indirectG,
+ state.directB + state.indirectB);
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // Radius gating (stage radii from EngineConfig / -De3d.gi.stage*Radius)
+ // ------------------------------------------------------------------
+
+ /**
+ * Whether the finished generation did centroid-bounce work for this
+ * entry (the termination mean must count only such entries). Mirrors
+ * the dispatch conditions in {@link #processEntry}.
+ */
+ private static boolean centroidWorked(final int finished,
+ final TriangleBvh.Entry entry,
+ final boolean finePhase) {
+ if (finePhase)
+ return false; // fine phase is lightmap-only work
+ return finished == 2; // coarse phase: generation 2 for all
+ }
+
+ /**
+ * Re-evaluates every entry's radius-gating mask from the current
+ * camera position. Called at snapshot build and at each generation
+ * barrier (the masks are stable while a generation runs), plus by
+ * the catch-up watcher on camera movement after convergence. Radius
+ * 0 means unlimited for that stage. Without a camera supplier, or
+ * with all radii at 0, every entry stays eligible for everything.
+ */
+ private void evalEligibility(final Snapshot snap) {
+ final double r2 = stage2Radius();
+ final double r3 = stage3Radius();
+ final double r4 = stage4Radius();
+ final Point3D cam = cameraPosition == null ? null : cameraPosition.get();
+ if (cam == null || (r2 <= 0 && r3 <= 0 && r4 <= 0)) {
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ entry.eligibleStages = 7;
+ if (entry.lightmap != null)
+ entry.lightmap.eligibleStages = 7;
+ }
+ snap.eligible2 = snap.entries.size();
+ snap.eligible3 = snap.entries.size();
+ snap.eligible4 = snap.entries.size();
+ return;
+ }
+ final double r2sq = r2 > 0 ? r2 * r2 : Double.POSITIVE_INFINITY;
+ final double r3sq = r3 > 0 ? r3 * r3 : Double.POSITIVE_INFINITY;
+ final double r4sq = r4 > 0 ? r4 * r4 : Double.POSITIVE_INFINITY;
+ int count2 = 0, count3 = 0, count4 = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final double dx = entry.centroidX - cam.x;
+ final double dy = entry.centroidY - cam.y;
+ final double dz = entry.centroidZ - cam.z;
+ final double distSq = dx * dx + dy * dy + dz * dz;
+ final int mask = (distSq <= r2sq ? 1 : 0)
+ | (distSq <= r3sq ? 2 : 0)
+ | (distSq <= r4sq ? 4 : 0);
+ entry.eligibleStages = mask;
+ if (entry.lightmap != null)
+ entry.lightmap.eligibleStages = mask;
+ if ((mask & 1) != 0) count2++;
+ if ((mask & 2) != 0) count3++;
+ if ((mask & 4) != 0) count4++;
+ }
+ snap.eligible2 = count2;
+ snap.eligible3 = count3;
+ snap.eligible4 = count4;
+ if (DEBUG)
+ System.out.println("[GI] eligibility from " + cam + ": stage2 "
+ + count2 + "/" + snap.entries.size() + ", stage3 " + count3
+ + ", stage4 " + count4);
+ }
+
+ /**
+ * Creates lightmaps for mesh-block triangles inside the active
+ * radius bubble that don't have one yet. In the coarse phase every
+ * stage-3-eligible triangle gets one; in the fine phase only
+ * stage-4-eligible ones (stage-3-only work is over by then).
+ */
+ private void createBlockLightmaps(final Snapshot snap) {
+ if (stage3Radius() <= 0)
+ return;
+ final double[] pos = new double[3];
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ if (entry.block == null)
+ continue;
+ final int mask = entry.eligibleStages;
+ final boolean want = snap.finePhase ? (mask & 4) != 0 : (mask & 2) != 0;
+ if (!want || entry.block.lightmapAt(entry.blockTri) != null)
+ continue;
+ attachBlockLightmap(snap, entry, pos);
+ }
+ }
+
+ /**
+ * Attaches a fresh per-triangle lightmap to a mesh-block triangle
+ * (or re-attaches the existing one to this snapshot's entry) and
+ * either restores its baked composite from the {@link LightmapCache}
+ * or â when the bake's per-texel direct pass has already run â
+ * traces its direct light immediately so it can join the current
+ * generation. Post-bake creations are queued for a catch-up bounce.
+ */
+ private void attachBlockLightmap(final Snapshot snap,
+ final TriangleBvh.Entry entry,
+ final double[] pos) {
+ final TriangleMeshBlock block = entry.block;
+ if (block == null)
+ return;
+ final Lightmap existing = block.lightmapAt(entry.blockTri);
+ if (existing != null) {
+ entry.lightmap = existing;
+ return;
+ }
+ final double[] w9 = new double[9];
+ block.triangleWorld(entry.blockTri, w9);
+ // Cutout foliage & co: alpha textures keep per-triangle shading.
+ // A lightmap composite is opaque â resampling the texture's
+ // transparent-black regions into it would render the card as a
+ // solid dark slab.
+ final Texture baseTexture = block.texture(entry.blockTri);
+ if (baseTexture == null || baseTexture.hasAlpha)
+ return;
+ final double baseUpt = meshUnitsPerTexel();
+ // Mirror LightmappedTriangle: coarse resolution while the
+ // pipeline starts coarse. Post-bake, a late entrant matches its
+ // ring: stage-4-eligible joins at the final density, a
+ // stage-3-only entrant gets the coarse stage-3 density (the
+ // needsRefine catch-up upgrades it if the camera approaches).
+ final boolean coarseNow = !snap.finePhase && !snap.baked
+ || snap.baked && (entry.eligibleStages & 4) == 0;
+ final double upt = coarseNow ? lightmapUnitsPerTexel(baseUpt) : baseUpt;
+ final Lightmap lightmap = new Lightmap(
+ new Point3D(w9[0], w9[1], w9[2]),
+ new Point3D(w9[3], w9[4], w9[5]),
+ new Point3D(w9[6], w9[7], w9[8]),
+ block.albedo(entry.blockTri), upt,
+ entry.normal[0], entry.normal[1], entry.normal[2]);
+ lightmap.fineUnitsPerTexel = baseUpt;
+ final double[] uv6 = new double[6];
+ block.triangleUv(entry.blockTri, uv6);
+ lightmap.setBaseTextureMapping(baseTexture, uv6);
+ if (block.attachLightmapIfAbsent(entry.blockTri, lightmap) != lightmap) {
+ // Lost a creation race: adopt the winner (same geometry).
+ entry.lightmap = block.lightmapAt(entry.blockTri);
+ return;
+ }
+ entry.lightmap = lightmap;
+ snap.lightmaps.add(lightmap);
+
+ final long key = lightmapKey(lightmap);
+ final LightmapCache.Entry cached = lightmapCache.get(key);
+ if (cached != null && cached.lightSignature == lastLightSignature) {
+ // The cache may hold the FINE composite while a rebuild
+ // re-creates the lightmap at coarse dims: switch resolution
+ // first, then restore.
+ if (cached.width != lightmap.width || cached.height != lightmap.height)
+ lightmap.refine();
+ if (cached.width == lightmap.width && cached.height == lightmap.height) {
+ lightmap.restoreComposite(cached.pixels);
+ if (DEBUG)
+ System.out.println("[GI] lightmap cache hit (" + lightmap.width
+ + "x" + lightmap.height + ") â restored without bake");
+ return;
+ }
+ }
+ if (snap.directDone || snap.baked) {
+ // The global per-texel direct pass already ran: this lightmap
+ // must trace its own direct light before any bounce work.
+ directPass(snap, entry, pos);
+ if (snap.baked)
+ snap.catchUpQueue.add(entry);
+ }
+ }
+
+ /**
+ * Geometry signature for the lightmap cache: origin and edge vectors
+ * (the same 9 doubles the constructor derives from the triangle
+ * vertices, so the key is bit-stable across block rebuilds).
+ */
+ private static long lightmapKey(final Lightmap lightmap) {
+ return LightmapCache.key(new double[]{
+ lightmap.originX, lightmap.originY, lightmap.originZ,
+ lightmap.edge1X, lightmap.edge1Y, lightmap.edge1Z,
+ lightmap.edge2X, lightmap.edge2Y, lightmap.edge2Z});
+ }
+
+ /**
+ * Stores a finished mesh-block lightmap's composite in the cache.
+ * Only the shown composite pixels survive; bake state is transient.
+ */
+ private void cacheStore(final Lightmap lightmap) {
+ if (lightmap.owner != null)
+ return; // cache scope is mesh-block lightmaps
+ if (!lightmap.everComposited)
+ return;
+ if (!lightmap.directBaked)
+ // Shade-only composite (the lightmap sat outside the stage-3
+ // radius for the whole bake): not a GI solution â caching it
+ // would resurrect the unlit fill as "final" on rebuilds.
+ return;
+ final int[] pixels = lightmap.shownTexture().primaryBitmap.pixels;
+ lightmapCache.put(lightmapKey(lightmap), lightmap.width, lightmap.height,
+ java.util.Arrays.copyOf(pixels, pixels.length),
+ lastLightSignature);
+ }
+
+ // ------------------------------------------------------------------
+ // Catch-up: late radius entrants after the bake converged
+ // ------------------------------------------------------------------
+
+ /**
+ * Idle-time scan on a baked snapshot (throttled to the idle cadence):
+ * when the camera moved more than a quarter of the smallest active
+ * radius since the last evaluation, re-evaluate eligibility and queue
+ * every entry that newly entered its bubble. Stage-2 entrants get a
+ * single local bounce against the frozen converged field; new
+ * stage-3 block triangles get a lightmap (cache-restored when known);
+ * coarse-baked lightmaps entering the stage-4 radius refine and
+ * re-bake at fine resolution.
+ */
+ private void scanCatchUp(final Snapshot snap) {
+ if (cameraPosition == null)
+ return;
+ final double r2 = stage2Radius();
+ final double r3 = stage3Radius();
+ final double r4 = stage4Radius();
+ if (r2 <= 0 && r3 <= 0 && r4 <= 0)
+ return;
+ final long now = System.currentTimeMillis();
+ if (now - lastCatchUpEval < IDLE_SLEEP_MS)
+ return;
+ final Point3D cam = cameraPosition.get();
+ if (cam == null)
+ return;
+ if (!Double.isNaN(lastEvalCamX)) {
+ double smallest = Double.POSITIVE_INFINITY;
+ if (r2 > 0) smallest = Math.min(smallest, r2);
+ if (r3 > 0) smallest = Math.min(smallest, r3);
+ if (r4 > 0) smallest = Math.min(smallest, r4);
+ final double threshold = Math.max(1.0, smallest / 4);
+ final double dx = cam.x - lastEvalCamX;
+ final double dy = cam.y - lastEvalCamY;
+ final double dz = cam.z - lastEvalCamZ;
+ if (dx * dx + dy * dy + dz * dz <= threshold * threshold) {
+ lastCatchUpEval = now;
+ return;
+ }
+ }
+ if (!catchUpScanInFlight.compareAndSet(false, true))
+ return;
+ try {
+ if (snap != snapshot || !snap.baked)
+ return;
+ lastCatchUpEval = now;
+ lastEvalCamX = cam.x;
+ lastEvalCamY = cam.y;
+ lastEvalCamZ = cam.z;
+ evalEligibility(snap);
+ final double[] pos = new double[3];
+ int queued = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final int mask = entry.eligibleStages;
+ final Lightmap lightmap = entry.lightmap;
+ if (entry.block != null && lightmap == null && (mask & 2) != 0) {
+ attachBlockLightmap(snap, entry, pos);
+ // Fresh (cache-missed) lightmaps queue themselves for
+ // the bounce catch-up inside attachBlockLightmap.
+ if (entry.lightmap != null && !entry.lightmap.baked)
+ queued++;
+ } else if (lightmap != null && lightmap.baked
+ && (mask & 4) != 0 && lightmap.needsRefine()) {
+ snap.catchUpQueue.add(entry);
+ queued++;
+ } else if (lightmap != null && !lightmap.directBaked
+ && (mask & 2) != 0) {
+ // Has a lightmap that sat outside the stage-3 radius
+ // for the whole bake (standalone lightmapped
+ // triangles, or block lightmaps created but never
+ // reached): it still shows only the stage-1 shade.
+ // Queue it for direct + one bounce.
+ snap.catchUpQueue.add(entry);
+ queued++;
+ } else if (lightmap == null && (mask & 1) != 0) {
+ final GiState state = states.get(stateKey(entry));
+ if (state == null || !state.bounced) {
+ snap.catchUpQueue.add(entry);
+ queued++;
+ }
+ }
+ }
+ if (DEBUG && queued > 0)
+ System.out.println("[GI] catch-up: " + queued
+ + " entries entered the radius bubble");
+ } finally {
+ catchUpScanInFlight.set(false);
+ }
+ }
+
+ /**
+ * Runs the local catch-up for one late-entrant entry, reading only
+ * the frozen converged field (never restarting global generations â
+ * re-running a generation would double-count its energy in entries
+ * that already received it).
+ */
+ private void runCatchUp(final Snapshot snap, final TriangleBvh.Entry entry,
+ final TriangleBvh.Hit hit, final double[] pos,
+ final double[] target) {
+ if (snap != snapshot)
+ return; // snapshot replaced while queued
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap != null) {
+ if (lightmap.baked && lightmap.needsRefine()
+ && (entry.eligibleStages & 4) != 0) {
+ // Approached a coarse-baked lightmap: switch to the
+ // final texel density and re-bake at it.
+ lightmap.refine();
+ directPass(snap, entry, pos);
+ } else if (!lightmap.directBaked
+ && (entry.eligibleStages & 2) != 0) {
+ // Outside the stage-3 radius for the whole bake: the
+ // lightmap shows only the stage-1 shade. Trace its
+ // per-texel direct now; the bounce against the
+ // converged field follows below.
+ directPass(snap, entry, pos);
+ }
+ if (!lightmap.baked && lightmap.generation >= 1) {
+ // One bounce against the converged field, then finalize.
+ catchUpBounce(snap, entry, lightmap, hit, pos, target);
+ lightmap.rollover();
+ while (!compositeUpdateInFlight.compareAndSet(false, true))
+ Thread.yield();
+ try {
+ compositeLightmap(snap, lightmap);
+ } finally {
+ compositeUpdateInFlight.set(false);
+ }
+ lightmap.freeArrays();
+ cacheStore(lightmap);
+ }
+ return;
+ }
+ // Centroid catch-up for plain polygons and mesh-block triangles.
+ if ((entry.eligibleStages & 1) == 0)
+ return;
+ final GiState state = states.get(stateKey(entry));
+ if (state == null || state.bounced)
+ return;
+ final double nx = entry.normal[0];
+ final double ny = entry.normal[1];
+ final double nz = entry.normal[2];
+ final double ox = entry.centroidX + nx * ORIGIN_EPSILON;
+ final double oy = entry.centroidY + ny * ORIGIN_EPSILON;
+ final double oz = entry.centroidZ + nz * ORIGIN_EPSILON;
+ float meanR = 0, meanG = 0, meanB = 0;
+ for (int s = 1; s <= SAMPLES_PER_GENERATION; s++) {
+ gatherTotal(snap, nx, ny, nz, ox, oy, oz, hit, target);
+ meanR += (target[0] - meanR) / s;
+ meanG += (target[1] - meanG) / s;
+ meanB += (target[2] - meanB) / s;
+ }
+ synchronized (state) {
+ state.indirectR += meanR;
+ state.indirectG += meanG;
+ state.indirectB += meanB;
+ state.bounced = true;
+ }
+ if (entry.block != null)
+ entry.block.setGiLight(entry.blockTri,
+ state.directR + state.indirectR,
+ state.directG + state.indirectG,
+ state.directB + state.indirectB);
+ }
+
+ /**
+ * Per-texel catch-up bounce for a late lightmap: every texel
+ * averages one sample generation against the converged total field
+ * (direct + indirect at the hit). A single generation: the sampled
+ * field is frozen, so further iterations would re-read it unchanged.
+ */
+ private void catchUpBounce(final Snapshot snap, final TriangleBvh.Entry entry,
+ final Lightmap lightmap, final TriangleBvh.Hit hit,
+ final double[] pos, final double[] target) {
+ final double nx = lightmap.normalX;
+ final double ny = lightmap.normalY;
+ final double nz = lightmap.normalZ;
+ for (final int texel : lightmap.validTexels) {
+ lightmap.texelWorldPosition(texel, pos);
+ final double ox = pos[0] + nx * ORIGIN_EPSILON;
+ final double oy = pos[1] + ny * ORIGIN_EPSILON;
+ final double oz = pos[2] + nz * ORIGIN_EPSILON;
+ float meanR = 0, meanG = 0, meanB = 0;
+ for (int s = 1; s <= SAMPLES_PER_GENERATION; s++) {
+ gatherTotal(snap, nx, ny, nz, ox, oy, oz, hit, target);
+ meanR += (target[0] - meanR) / s;
+ meanG += (target[1] - meanG) / s;
+ meanB += (target[2] - meanB) / s;
+ }
+ lightmap.deltaCurR[texel] = meanR;
+ lightmap.deltaCurG[texel] = meanG;
+ lightmap.deltaCurB[texel] = meanB;
+ }
+ }
+
+ /**
+ * One cosine-weighted bounce ray from the given surface point,
+ * gathering the hit surface's converged TOTAL (direct + indirect).
+ * The catch-up variant of {@link #gatherTarget}: baked lightmaps are
+ * read through their composite texture (irradiance estimated as
+ * composite x 255 / base color), plain entries through their
+ * recorded direct + indirect totals.
+ *
+ * @param out receives the radiance contribution {r, g, b}; the sky
+ * dome color on an escape (miss) when sky sampling is
+ * on, zeros otherwise
+ */
+ private void gatherTotal(final Snapshot snap,
+ final double nx, final double ny, final double nz,
+ final double ox, final double oy, final double oz,
+ final TriangleBvh.Hit hit, final double[] out) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ final double[] dir = cosineHemisphere(nx, ny, nz, ThreadLocalRandom.current());
+ if (!snap.bvh.nearest(ox, oy, oz, dir[0], dir[1], dir[2], hit)) {
+ if (snap.skyEnabled) {
+ out[0] = BOUNCE_GAIN * snap.skyR * SKY_SCALE;
+ out[1] = BOUNCE_GAIN * snap.skyG * SKY_SCALE;
+ out[2] = BOUNCE_GAIN * snap.skyB * SKY_SCALE;
+ }
+ return;
+ }
+
+ final TriangleBvh.Entry hitEntry = hit.entry;
+ final Lightmap hitLightmap = hitEntry.lightmap;
+ double eR = snap.ambientR, eG = snap.ambientG, eB = snap.ambientB;
+ if (hitLightmap != null && hitLightmap.everComposited) {
+ // Sample the shown composite at ITS OWN dimensions. The GI
+ // catch-up runs this on one worker while another worker's
+ // runCatchUp refine()s this very lightmap: width/height and
+ // the composite buffers are swapped non-atomically, and
+ // indexing by lightmap dims tore against the buffer swap
+ // (ArrayIndexOutOfBounds, bugreport-20261005-153054). The
+ // parametric (u, v) is resolution-independent, and the
+ // captured Texture reference is immutable â always in
+ // bounds, possibly at the pre-refine resolution, which
+ // carries the same irradiance content.
+ final TextureBitmap shown = hitLightmap.shownTexture().primaryBitmap;
+ final double[] uv = new double[2];
+ hitLightmap.uvAt(hit.pointX, hit.pointY, hit.pointZ, uv);
+ int i = (int) (uv[0] * shown.width);
+ int j = (int) (uv[1] * shown.height);
+ if (i < 0) i = 0;
+ if (i >= shown.width) i = shown.width - 1;
+ if (j < 0) j = 0;
+ if (j >= shown.height) j = shown.height - 1;
+ final int px = shown.pixels[j * shown.width + i];
+ final int base = hitLightmap.baseColorAtUv(uv[0], uv[1]);
+ eR = irradianceFromComposite((px >> 16) & 255, (base >> 16) & 255, eR);
+ eG = irradianceFromComposite((px >> 8) & 255, (base >> 8) & 255, eG);
+ eB = irradianceFromComposite(px & 255, base & 255, eB);
+ } else {
+ final GiState state = states.get(stateKey(hitEntry));
+ if (state != null) {
+ eR = state.directR + state.indirectR;
+ eG = state.directG + state.indirectG;
+ eB = state.directB + state.indirectB;
+ }
+ }
+
+ final Color hitColor = colorOf(hitEntry);
+ out[0] = BOUNCE_GAIN * hitColor.r * Math.min(255, eR) / 255.0;
+ out[1] = BOUNCE_GAIN * hitColor.g * Math.min(255, eG) / 255.0;
+ out[2] = BOUNCE_GAIN * hitColor.b * Math.min(255, eB) / 255.0;
+ }
+
+ /**
+ * Irradiance estimate from a composite texel: the composite is
+ * base x irradiance / 255, so irradiance ~= pixel x 255 / base.
+ * Near-black bases carry no reliable signal; fall back to the
+ * ambient level there (the albedo multiply at the gatherer kills
+ * the contribution anyway).
+ */
+ private static double irradianceFromComposite(final int pixelChannel,
+ final int baseChannel,
+ final double fallback) {
+ if (baseChannel < 8)
+ return fallback;
+ return Math.min(255, pixelChannel * 255.0 / baseChannel);
+ }
+
// ------------------------------------------------------------------
// Ray primitives
// ------------------------------------------------------------------
@@ -766,22 +1829,33 @@ public class GlobalIllumination implements GiLightProvider {
/**
* Direct irradiance at a ray hit point, same scale as LightingManager,
* clamped to display range. Uses the hit surface's CACHED visibility
- * (no new shadow rays).
+ * (no new shadow rays): per-texel bytes once the per-texel direct
+ * pass has run at that surface (coarse phase from generation 3 on,
+ * fine phase from its generation 2 on), the stage-1 per-polygon
+ * bits before that.
*/
- private double[] directIrradiance(final Snapshot snap, final TriangleBvh.Hit hit) {
+ private double[] directIrradiance(final Snapshot snap, final TriangleBvh.Hit hit,
+ final int generation) {
final TriangleBvh.Entry entry = hit.entry;
final Lightmap lightmap = entry.lightmap;
double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
final int lightCount = snap.lights.size();
- final int hitTexel = lightmap != null
+ // Per-texel visibility bytes only exist once the per-texel
+ // direct pass has run at the hit surface's current resolution:
+ // coarse phase from generation 3 on, fine phase from its
+ // generation 2 on. Earlier generations (stage 2's centroid
+ // bounce) read the stage-1 per-polygon bits at ALL hits.
+ final boolean perTexel = lightmap != null
+ && (generation >= 3 || snap.finePhase && generation >= 2);
+ final int hitTexel = perTexel
? lightmap.texelAt(hit.pointX, hit.pointY, hit.pointZ) : -1;
- final GiState hitState = lightmap == null ? states.get(stateKey(entry)) : null;
+ final GiState hitState = perTexel ? null : states.get(stateKey(entry));
- for (int i = 0; i < lightCount && i < MAX_TRACKED_LIGHTS; i++) {
+ for (int i = 0; i < lightCount && i < maxTrackedLights(); i++) {
final LightSource light = snap.lights.get(i);
- if (lightmap != null) {
+ if (perTexel) {
if (lightmap.lightVisibility != null
&& lightmap.lightVisibility[hitTexel * lightCount + i] == Lightmap.VISIBILITY_OCCLUDED)
continue;
@@ -888,7 +1962,7 @@ public class GlobalIllumination implements GiLightProvider {
for (final int texel : lightmap.validTexels) {
lightmap.texelWorldPosition(texel, pos);
double r = snap.ambientR, g = snap.ambientG, b = snap.ambientB;
- for (int i = 0; i < lightCount && i < MAX_TRACKED_LIGHTS; i++) {
+ for (int i = 0; i < lightCount && i < maxTrackedLights(); i++) {
if (lightmap.lightVisibility[texel * lightCount + i] == Lightmap.VISIBILITY_OCCLUDED)
continue;
final LightSource light = snap.lights.get(i);
@@ -958,14 +2032,21 @@ public class GlobalIllumination implements GiLightProvider {
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++) {
final int t = j * width + i;
- pixels[t] = compositePixel(lightmap, irrR[t], irrG[t], irrB[t]);
+ pixels[t] = compositePixel(lightmap, t, irrR[t], irrG[t], irrB[t]);
}
back.resetResampledBitmapCache();
if (lightmap.owner != null) {
lightmap.owner.setTexture(back);
- lightmap.swapBuffers();
+ // The composite now carries real traced lighting; the
+ // stage-1 uniform preview multiply must go away.
+ lightmap.owner.clearGiShade();
}
+ // Mesh-block lightmaps have no owner: the paint path reads
+ // shownTexture() per frame, so the swap must happen here for
+ // every lightmap kind, not just owned ones.
+ lightmap.swapBuffers();
+ lightmap.everComposited = true;
// Debug: -De3d.gi.dumpLightmaps=/tmp/lm dumps composites as PNGs.
if (DUMP_DIR != null)
@@ -1019,17 +2100,16 @@ public class GlobalIllumination implements GiLightProvider {
}
private static boolean isValid(final Lightmap lightmap, final int texel) {
- final double u = ((texel % lightmap.width) + 0.5) / lightmap.width;
- final double v = ((texel / lightmap.width) + 0.5) / lightmap.height;
- return u + v <= 1.0;
+ return lightmap.isValidTexel(texel % lightmap.width, texel / lightmap.width);
}
- /** Composite texel: baseColor scaled by total irradiance, clamped. */
- private static int compositePixel(final Lightmap lightmap,
+ /** Composite texel: per-texel base color scaled by total irradiance, clamped. */
+ private static int compositePixel(final Lightmap lightmap, final int texel,
final double irrR, final double irrG, final double irrB) {
- final int r = Math.min(255, (int) (irrR * lightmap.baseColor.r / 255));
- final int g = Math.min(255, (int) (irrG * lightmap.baseColor.g / 255));
- final int b = Math.min(255, (int) (irrB * lightmap.baseColor.b / 255));
+ final int base = lightmap.baseColorAt(texel);
+ final int r = Math.min(255, (int) (irrR * ((base >> 16) & 255) / 255));
+ final int g = Math.min(255, (int) (irrG * ((base >> 8) & 255) / 255));
+ final int b = Math.min(255, (int) (irrB * (base & 255) / 255));
return 0xFF000000 | (r << 16) | (g << 8) | b;
}
@@ -1064,6 +2144,11 @@ public class GlobalIllumination implements GiLightProvider {
private void rebuildSnapshot(final int version,
final double lightSignature,
final long now) {
+ // Captured up front: harvestCentroids tags the OLD snapshot's
+ // values with the signature they were baked under, and the
+ // field moves to the new signature during this build.
+ final Snapshot old = snapshot;
+ final double oldSignature = lastLightSignature;
if (DEBUG)
System.out.println("[GI] rebuild trigger: renderListVersion "
+ lastSeenRenderListVersion + " -> " + version
@@ -1085,7 +2170,7 @@ public class GlobalIllumination implements GiLightProvider {
final Snapshot snap = new Snapshot();
snap.entries = new ArrayList<>(triangles.size());
- snap.lightmaps = new ArrayList<>();
+ snap.lightmaps = new java.util.concurrent.CopyOnWriteArrayList<>();
for (final AbstractCoordinateShape triangle : triangles) {
if (triangle.vertices.size() < 3)
continue;
@@ -1097,8 +2182,12 @@ public class GlobalIllumination implements GiLightProvider {
for (final eu.svjatoslav.aukio.e3d.renderer.raster.shapes
.basic.texturedpolygon.TriangleMeshBlock block : meshBlocks) {
block.ensureGiLight();
- for (int t = 0; t < block.triCount(); t++)
- snap.entries.add(buildBlockEntry(block, t));
+ for (int t = 0; t < block.triCount(); t++) {
+ final TriangleBvh.Entry entry = buildBlockEntry(block, t);
+ snap.entries.add(entry);
+ if (entry.lightmap != null)
+ snap.lightmaps.add(entry.lightmap);
+ }
}
if (!snap.entries.isEmpty())
snap.bvh = new TriangleBvh(snap.entries);
@@ -1110,6 +2199,13 @@ public class GlobalIllumination implements GiLightProvider {
snap.ambientR = ambient.r;
snap.ambientG = ambient.g;
snap.ambientB = ambient.b;
+ final Color sky = skyColor();
+ snap.skyEnabled = sky != null && (sky.r | sky.g | sky.b) != 0;
+ if (snap.skyEnabled) {
+ snap.skyR = sky.r;
+ snap.skyG = sky.g;
+ snap.skyB = sky.b;
+ }
// Near-to-far bake order from the camera position at build time.
final Point3D cam = cameraPosition == null ? null : cameraPosition.get();
@@ -1120,17 +2216,36 @@ public class GlobalIllumination implements GiLightProvider {
final double dz = entry.centroidZ - cam.z;
entry.distance = (float) (dx * dx + dy * dy + dz * dz);
}
- snap.queue = snap.entries.stream()
+ snap.queueAll = snap.entries.stream()
.sorted(Comparator.comparingDouble(e -> e.distance))
.toArray(TriangleBvh.Entry[]::new);
+ snap.queue = snap.queueAll; // generation 0 is deliberately global
} else {
- snap.queue = snap.entries.toArray(new TriangleBvh.Entry[0]);
+ snap.queueAll = snap.entries.toArray(new TriangleBvh.Entry[0]);
+ snap.queue = snap.queueAll;
}
- snapshot = snap;
+ // Radius gating: masks from the build-time camera position, then
+ // lightmaps for block triangles already inside the bubble (they
+ // join the bake from generation 0; the per-texel direct pass
+ // reaches them in generation 1). The light signature must be
+ // current before creation: cache restores compare against it.
+ evalEligibility(snap);
+ lastLightSignature = lightSignature;
+ createBlockLightmaps(snap);
+
+ // Harvest stage-1/2 centroid values of the OLD snapshot under
+ // the OLD signature (both captured at method entry), then
+ // restore what the new snapshot recognizes: streamed cells
+ // re-enter with identical geometry, so their direct light and
+ // first bounce come back for free (bugreport-20261005-220333).
+ // The state map is rebuilt BEFORE the snapshot is published,
+ // so workers never race the swap.
+ harvestCentroids(old, oldSignature);
states.clear();
+ restoreCentroids(snap);
+ snapshot = snap;
lastSeenRenderListVersion = version;
- lastLightSignature = lightSignature;
lastRebuildTime = now;
if (DEBUG)
@@ -1139,6 +2254,89 @@ public class GlobalIllumination implements GiLightProvider {
+ snap.lights.size() + " lights, generation bake");
}
+ /**
+ * Saves the old snapshot's completed centroid values (stage-1
+ * direct; stage-2 bounce when it ran) into {@link #centroidCache}
+ * before the rebuild drops the state map.
+ *
+ * @param old the snapshot being replaced, null on the first build
+ * @param oldSignature the light signature the old values were baked under
+ */
+ private void harvestCentroids(final Snapshot old, final double oldSignature) {
+ if (old == null)
+ return;
+ for (final TriangleBvh.Entry entry : old.entries) {
+ final GiState s = states.get(stateKey(entry));
+ if (s == null || !s.directDone)
+ continue;
+ final GiCentroidCache.Entry c = new GiCentroidCache.Entry();
+ c.directR = s.directR;
+ c.directG = s.directG;
+ c.directB = s.directB;
+ c.indirectR = s.indirectR;
+ c.indirectG = s.indirectG;
+ c.indirectB = s.indirectB;
+ c.deltaPrevR = s.deltaPrevR;
+ c.deltaPrevG = s.deltaPrevG;
+ c.deltaPrevB = s.deltaPrevB;
+ c.visibleBits = s.visibleBits;
+ c.knownBits = s.knownBits;
+ c.bounced = s.bounced;
+ c.lightSignature = oldSignature;
+ centroidCache.put(LightmapCache.key(entry.v), c);
+ }
+ }
+
+ /**
+ * Pre-populates {@link #states} with cached stage-1/2 centroid
+ * values for entries whose geometry is known from a previous
+ * snapshot (cell stream-out/in with an unchanged light field) and
+ * applies their display write-backs immediately, so streamed-in
+ * blocks never show an unlit frame. Runs before the snapshot is
+ * published; workers see the restored states from the start and
+ * skip the corresponding passes.
+ */
+ private void restoreCentroids(final Snapshot snap) {
+ int restored = 0;
+ for (final TriangleBvh.Entry entry : snap.entries) {
+ final GiCentroidCache.Entry c =
+ centroidCache.get(LightmapCache.key(entry.v));
+ if (c == null || c.lightSignature != lastLightSignature)
+ continue;
+ final GiState s = new GiState();
+ s.directR = c.directR;
+ s.directG = c.directG;
+ s.directB = c.directB;
+ s.indirectR = c.indirectR;
+ s.indirectG = c.indirectG;
+ s.indirectB = c.indirectB;
+ s.deltaPrevR = c.deltaPrevR;
+ s.deltaPrevG = c.deltaPrevG;
+ s.deltaPrevB = c.deltaPrevB;
+ s.visibleBits = c.visibleBits;
+ s.knownBits = c.knownBits;
+ s.directDone = true;
+ s.bounced = c.bounced;
+ s.restored = true;
+ states.put(stateKey(entry), s);
+ // Display write-back (stage 1 is skipped for this entry):
+ // the stage-2 display formula is direct + first bounce.
+ final float dr = c.bounced ? s.directR + s.indirectR : s.directR;
+ final float dg = c.bounced ? s.directG + s.indirectG : s.directG;
+ final float db = c.bounced ? s.directB + s.indirectB : s.directB;
+ if (entry.block != null)
+ entry.block.setGiLight(entry.blockTri, dr, dg, db);
+ final Lightmap lightmap = entry.lightmap;
+ if (lightmap != null && lightmap.owner != null
+ && !lightmap.everComposited)
+ lightmap.owner.setGiShade(dr, dg, db);
+ restored++;
+ }
+ if (DEBUG && restored > 0)
+ System.out.println("[GI] centroid cache: restored " + restored
+ + "/" + snap.entries.size() + " stage-1/2 values");
+ }
+
private double lightSignature() {
double signature = 0;
for (final LightSource light : lightingManager.getLights()) {
@@ -1146,9 +2344,30 @@ public class GlobalIllumination implements GiLightProvider {
final Color c = light.getColor();
signature += p.x + p.y + p.z + c.r + c.g + c.b + light.getIntensity() * 31.0;
}
+ // Sky color feeds the bounce field, so a sky change rebakes.
+ // Black sky contributes nothing either way â keep the signature
+ // identical for unset and black.
+ final Color sky = skyColor();
+ if (sky != null && (sky.r | sky.g | sky.b) != 0)
+ signature += sky.r * 3.0 + sky.g * 5.0 + sky.b * 7.0 + 1.0;
return signature;
}
+ /**
+ * Sky dome color for bounce rays that escape the scene:
+ * {@code -De3d.gi.sky=RRGGBB} wins, else the scene's
+ * {@link LightingManager#getSkyColor()}. May be null (no sky
+ * sampling â the historical behavior).
+ *
+ * @return the sky color or null
+ */
+ private Color skyColor() {
+ final String prop = System.getProperty("e3d.gi.sky");
+ if (prop != null)
+ return Color.hex(prop);
+ return lightingManager.getSkyColor();
+ }
+
private TriangleBvh.Entry buildEntry(final AbstractCoordinateShape triangle) {
final TriangleBvh.Entry entry = new TriangleBvh.Entry(triangle);
if (triangle instanceof LightmappedShape)
@@ -1180,6 +2399,9 @@ public class GlobalIllumination implements GiLightProvider {
entry.v[0], entry.v[1], entry.v[2],
entry.v[3], entry.v[4], entry.v[5],
entry.v[6], entry.v[7], entry.v[8]);
+ // Re-attach a lightmap that survives on the block from an
+ // earlier snapshot (snapshot rebuilds recreate all entries).
+ entry.lightmap = block.lightmapAt(tri);
return entry;
}
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.java
index 41f3973..4bf6d45 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/Lightmap.java
@@ -7,13 +7,21 @@ package eu.svjatoslav.aukio.e3d.renderer.raster.gi;
import eu.svjatoslav.aukio.e3d.geometry.Point3D;
import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
+import eu.svjatoslav.aukio.e3d.renderer.raster.texture.TextureBitmap;
/**
* Per-triangle lightmap: a small generated texture whose texels map onto the
- * triangle surface. The triangle's UVs (in texture pixel units) are
- * (0,0), (width,0), (0,height), so the valid texel region is the half
- * where u+v <= 1 in normalized coordinates; the other half is filled
- * by mirroring to keep mipmaps and edge sampling clean.
+ * triangle surface. The grid is an ORTHOGONAL frame on the triangle's
+ * plane, not the triangle's own edge frame (that sheared texels into
+ * diamonds on acute triangles â bugreport-20261005-192002): the longest
+ * edge is the u-axis, the v-axis is the in-plane perpendicular, and the
+ * texture covers the triangle's bounding rectangle in that frame. The
+ * triangle's UVs (texture pixel units) are (0,0), (width,0),
+ * (apexU*width, height); texels outside the triangle are filled from
+ * valid neighbors to keep mipmaps and edge sampling clean. Texels are
+ * square in world space on every triangle, and the bounding rect is
+ * exactly 2x the triangle's area â the same overhead class as the old
+ * half-empty edge-frame texture.
*
* What you trace is what you see: the composite texture the painter
* samples IS the lightmap, at native texel resolution. Shadow-edge
@@ -60,21 +68,23 @@ public class Lightmap {
/** Visibility value: shadow ray was blocked. */
public static final byte VISIBILITY_OCCLUDED = 2;
- /** Texture size limits, power of two. */
+ /** Texel-count limits per axis. */
private static final int MIN_SIZE = 4;
private static final int MAX_SIZE = 128;
/**
- * Uniform irradiance the composite texture starts at (light units,
- * display scale 0..255): the world begins medium-lit and visible,
- * then each lightmap flips to its traced direct light when the bake
- * reaches it. {@code -De3d.gi.initialIrradiance}.
+ * Irradiance the composite texture starts at (light units, display
+ * scale 0..255): the default 255 shows every lightmapped triangle in
+ * its true base color from frame one ("unlit, as-is"), then each
+ * lightmap flips to its traced lighting when the bake reaches it.
+ * Lower values make un-baked surfaces visibly dimmer placeholders.
+ * {@code -De3d.gi.initialIrradiance}.
*/
public static final double INITIAL_IRRADIANCE =
- Double.parseDouble(System.getProperty("e3d.gi.initialIrradiance", "128"));
+ Double.parseDouble(System.getProperty("e3d.gi.initialIrradiance", "255"));
- public final int width;
- public final int height;
+ public int width;
+ public int height;
/** Unlit surface color of the triangle. */
public final Color baseColor;
@@ -86,8 +96,32 @@ public class Lightmap {
/** Unit surface normal. */
public final double normalX, normalY, normalZ;
- /** Valid (u+v <= 1) texel indices, for generation sampling. */
- public final int[] validTexels;
+ /** Valid (inside-the-triangle) texel indices, for generation sampling. */
+ public int[] validTexels;
+
+ /**
+ * Frame-space (u, v) of each CONSTRUCTOR vertex (a, b, c order),
+ * 0..1: one is (0,0), one is (1,0), one is ({@link #apexU}, 1).
+ * Painters pin per-vertex UVs to (cornerU[k]*width,
+ * cornerV[k]*height).
+ */
+ public final double[] cornerU = new double[3];
+ public final double[] cornerV = new double[3];
+ /** Parametric u of the apex vertex in the bounding-rect frame. */
+ public double apexU;
+
+ // Frame-space barycentric solver for base-texture resampling:
+ // P=(u,v) -> weights along input edges a->b and a->c, via the
+ // precomputed inverse of the 2x2 [Fb-Fa | Fc-Fa] system.
+ private double baryU0, baryV0, bary11, bary12, bary21, bary22;
+
+ /** Units-per-texel of the FINAL (stage-4) resolution: the raw
+ * configured value, before the stage-3 coarsening factor.
+ * {@link LightmappedTriangle} overwrites this after construction
+ * with the composite's configured value; defaults to the
+ * construction value (no coarsening -> {@link #refine()} is a
+ * no-op). */
+ public double fineUnitsPerTexel;
/**
* Accumulated indirect irradiance total, pre-albedo light units: the
@@ -136,6 +170,36 @@ public class Lightmap {
/** True once the bake has finished and the texel arrays are freed. */
public volatile boolean baked;
+ /**
+ * True once this lightmap has traced its per-texel direct light
+ * (engine {@code directPass}) or had a fully-baked composite
+ * restored from the lightmap cache. False for lightmaps that only
+ * ever received the stage-1 uniform shade (outside the stage-3
+ * radius for the whole bake): the catch-up watcher uses it to give
+ * them their direct + bounce when the radius bubble reaches them,
+ * and the cache refuses to store their shade-only composites.
+ */
+ public volatile boolean directBaked;
+
+ /**
+ * Radius-gating mask of the owning triangle, mirroring
+ * {@code TriangleBvh.Entry.eligibleStages} (set at every generation
+ * barrier from the live camera position). Read at the coarseâfine
+ * transition (bit 2 = stage-4 eligible) and in termination
+ * accounting (current-phase bit).
+ */
+ public volatile int eligibleStages = 7;
+
+ /**
+ * True once a real composite (traced lighting) has been swapped in.
+ * Until then the texture still holds the initial base-color fill,
+ * and the stage-1 uniform preview may stamp the owner's per-triangle
+ * GI shade on top of it. Sticky across rebakes: a lightmap that has
+ * shown traced lighting keeps its old composite until the new
+ * direct pass lands â no uniform preview on rebake.
+ */
+ public volatile boolean everComposited;
+
/** Double-buffered composite textures; the triangle shows one, GI fills the other. */
private final Texture[] buffers = new Texture[2];
private int shownBuffer;
@@ -143,6 +207,162 @@ public class Lightmap {
/** The triangle currently displaying this lightmap (for texture swaps). */
public volatile LightmappedTriangle owner;
+ /**
+ * Mesh-block lightmaps: the triangle's base texture and its UVs
+ * (primary-texture pixel units, as stored in the block). When set,
+ * the composite is generated from {@link #baseTexels} â the photo
+ * texture resampled into lightmap space â instead of the flat
+ * {@link #baseColor}, preserving texture detail under GI.
+ */
+ private Texture baseTexture;
+ private final double[] baseUv = new double[6];
+ /** Per-texel base color sampled from {@link #baseTexture}; null in flat-color mode.
+ * Held as an immutable (pixels, width, height) triple so cross-thread
+ * readers (GI catch-up gathering on one worker while another
+ * {@link #refine()}s this lightmap) never see a torn resize. */
+ private volatile BaseTexels baseTexels;
+
+ /** Immutable base-texel array with its dimensions. */
+ private static final class BaseTexels {
+ final int[] pixels;
+ final int width;
+ final int height;
+
+ BaseTexels(final int[] pixels, final int width, final int height) {
+ this.pixels = pixels;
+ this.width = width;
+ this.height = height;
+ }
+ }
+
+ /**
+ * UV perimeter of this lightmap in primary-texture pixels â the
+ * mipmap metric's texture side for triangles painted from this
+ * lightmap (UVs (0,0), (width,0), (0,height)).
+ *
+ * @return width + height + hypot(width, height)
+ */
+ public double uvPerimeter() {
+ return width + height + Math.sqrt(width * width + height * height);
+ }
+
+ /**
+ * Base color of one texel for compositing: the photo-texture sample
+ * when {@link #baseTexels} exists (mesh-block lightmaps), the flat
+ * {@link #baseColor} otherwise.
+ *
+ * @param texel texel index (j * width + i)
+ * @return ARGB base color
+ */
+ public int baseColorAt(final int texel) {
+ final BaseTexels bt = baseTexels;
+ return bt != null ? bt.pixels[texel]
+ : 0xFF000000 | (baseColor.r << 16) | (baseColor.g << 8) | baseColor.b;
+ }
+
+ /**
+ * Base color at a parametric (u, v), sampled at the base array's
+ * OWN dimensions. Race-safe against a concurrent {@link #refine()}:
+ * the (pixels, width, height) triple is swapped atomically, so the
+ * sample is always in bounds â possibly at the pre-refine
+ * resolution, which carries the same photo content.
+ *
+ * @param u parametric u, 0..1
+ * @param v parametric v, 0..1
+ * @return ARGB base color
+ */
+ public int baseColorAtUv(final double u, final double v) {
+ final BaseTexels bt = baseTexels;
+ if (bt == null)
+ return 0xFF000000 | (baseColor.r << 16) | (baseColor.g << 8) | baseColor.b;
+ int i = (int) (u * bt.width);
+ int j = (int) (v * bt.height);
+ if (i < 0) i = 0;
+ if (i >= bt.width) i = bt.width - 1;
+ if (j < 0) j = 0;
+ if (j >= bt.height) j = bt.height - 1;
+ return bt.pixels[j * bt.width + i];
+ }
+
+ /**
+ * Switches this lightmap to photo-texture compositing (mesh-block
+ * triangles): samples the base texture into per-texel base colors
+ * at the current resolution. Bilinear with wrap-aware fetch, over
+ * ALL texels â the mirrored (u+v > 1) half maps to the mirrored
+ * triangle region and is filled by the compositor's neighbor fill,
+ * so it must carry plausible colors too.
+ *
+ * @param texture the block triangle's base texture
+ * @param uv 6 UV doubles (u0,v0,u1,v1,u2,v2), primary-texture pixels
+ */
+ public void setBaseTextureMapping(final Texture texture, final double[] uv) {
+ baseTexture = texture;
+ System.arraycopy(uv, 0, baseUv, 0, 6);
+ resampleBaseTexels();
+ }
+
+ /** Resamples {@link #baseTexels} at the current dimensions. */
+ private void resampleBaseTexels() {
+ if (baseTexture == null)
+ return;
+ final TextureBitmap bitmap = baseTexture.primaryBitmap;
+ final int tw = bitmap.width, th = bitmap.height;
+ final int[] src = bitmap.pixels;
+ final boolean wrap = baseTexture.wrap;
+ final double u0 = baseUv[0], v0 = baseUv[1];
+ final double du1 = baseUv[2] - u0, dv1 = baseUv[3] - v0;
+ final double du2 = baseUv[4] - u0, dv2 = baseUv[5] - v0;
+ baseTexels = null;
+ final int[] out = new int[width * height];
+ for (int j = 0; j < height; j++)
+ for (int i = 0; i < width; i++) {
+ final double u = (i + 0.5) / width;
+ final double v = (j + 0.5) / height;
+ // Frame (u, v) -> barycentric weights along the input
+ // edges a->b and a->c (the base UVs are per input
+ // vertex, and the bounding-rect frame reorders them).
+ final double pu = u - baryU0, pv = v - baryV0;
+ final double beta1 = bary11 * pu + bary12 * pv;
+ final double beta2 = bary21 * pu + bary22 * pv;
+ double tx = u0 + du1 * beta1 + du2 * beta2 - 0.5;
+ double ty = v0 + dv1 * beta1 + dv2 * beta2 - 0.5;
+ if (wrap) {
+ tx = ((tx % tw) + tw) % tw;
+ ty = ((ty % th) + th) % th;
+ } else {
+ tx = Math.min(tw - 1.001, Math.max(0.0, tx));
+ ty = Math.min(th - 1.001, Math.max(0.0, ty));
+ }
+ final int x0 = (int) tx, y0 = (int) ty;
+ final int x1 = wrap ? (x0 + 1) % tw : Math.min(tw - 1, x0 + 1);
+ final int y1 = wrap ? (y0 + 1) % th : Math.min(th - 1, y0 + 1);
+ out[j * width + i] = bilinear(src[y0 * tw + x0],
+ src[y0 * tw + x1], src[y1 * tw + x0], src[y1 * tw + x1],
+ tx - x0, ty - y0);
+ }
+ baseTexels = new BaseTexels(out, width, height);
+ }
+
+ /**
+ * Cache restore: replaces both composite buffers with the given
+ * baked pixels (dimensions must match â the cache checks before
+ * calling) and marks the lightmap baked. No texel arrays are
+ * allocated; the lightmap is display-complete without any bake.
+ *
+ * @param pixels ARGB composite, width * height ints
+ */
+ public void restoreComposite(final int[] pixels) {
+ System.arraycopy(pixels, 0, buffers[0].primaryBitmap.pixels, 0,
+ width * height);
+ System.arraycopy(pixels, 0, buffers[1].primaryBitmap.pixels, 0,
+ width * height);
+ buffers[0].resetResampledBitmapCache();
+ buffers[1].resetResampledBitmapCache();
+ everComposited = true;
+ directBaked = true; // the cache only holds fully-baked composites
+ baked = true;
+ }
+
/**
* Creates a lightmap for a triangle.
*
@@ -159,50 +379,300 @@ public class Lightmap {
final Color baseColor, final double unitsPerTexel,
final double normalX, final double normalY, final double normalZ) {
this.baseColor = baseColor;
- originX = a.x;
- originY = a.y;
- originZ = a.z;
- edge1X = b.x - a.x;
- edge1Y = b.y - a.y;
- edge1Z = b.z - a.z;
- edge2X = c.x - a.x;
- edge2Y = c.y - a.y;
- edge2Z = c.z - a.z;
this.normalX = normalX;
this.normalY = normalY;
this.normalZ = normalZ;
- final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
- final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
- width = powerOfTwo(len1 / unitsPerTexel);
- height = powerOfTwo(len2 / unitsPerTexel);
+ // Orthogonal bounding-rect frame (see the class javadoc): the
+ // LONGEST edge becomes the u-axis â that keeps the apex's
+ // projection inside the base segment, so the bounding rect is
+ // tight (exactly 2x the triangle area).
+ final double abx = b.x - a.x, aby = b.y - a.y, abz = b.z - a.z;
+ final double bcx = c.x - b.x, bcy = c.y - b.y, bcz = c.z - b.z;
+ final double cax = a.x - c.x, cay = a.y - c.y, caz = a.z - c.z;
+ final double lenAB = Math.sqrt(abx * abx + aby * aby + abz * abz);
+ final double lenBC = Math.sqrt(bcx * bcx + bcy * bcy + bcz * bcz);
+ final double lenCA = Math.sqrt(cax * cax + cay * cay + caz * caz);
- final int[] valid = new int[width * height];
- int count = 0;
- for (int j = 0; j < height; j++)
- for (int i = 0; i < width; i++) {
- final double u = (i + 0.5) / width;
- final double v = (j + 0.5) / height;
- if (u + v <= 1.0)
- valid[count++] = j * width + i;
- }
- validTexels = new int[count];
- System.arraycopy(valid, 0, validTexels, 0, count);
+ final int oi, ui, pi; // input-order indices: origin, u-end, apex
+ if (lenAB >= lenBC && lenAB >= lenCA) { oi = 0; ui = 1; pi = 2; }
+ else if (lenBC >= lenCA) { oi = 1; ui = 2; pi = 0; }
+ else { oi = 2; ui = 0; pi = 1; }
+ final double[] vx = {a.x, b.x, c.x};
+ final double[] vy = {a.y, b.y, c.y};
+ final double[] vz = {a.z, b.z, c.z};
- // Both buffers start at the uniform medium INITIAL_IRRADIANCE:
- // the world is visible from frame one; each lightmap flips to
- // its traced lighting when the bake reaches it.
+ originX = vx[oi];
+ originY = vy[oi];
+ originZ = vz[oi];
+ // u-axis: the base vector itself (u in 0..1 spans the base).
+ edge1X = vx[ui] - vx[oi];
+ edge1Y = vy[ui] - vy[oi];
+ edge1Z = vz[ui] - vz[oi];
+ final double baseLen = Math.max(lenAB, Math.max(lenBC, lenCA));
+
+ // Apex decomposition: s along the base, remainder perpendicular.
+ final double apx = vx[pi] - vx[oi];
+ final double apy = vy[pi] - vy[oi];
+ final double apz = vz[pi] - vz[oi];
+ final double s = baseLen > 1e-12
+ ? (apx * edge1X + apy * edge1Y + apz * edge1Z) / (baseLen * baseLen)
+ : 0;
+ // v-axis: the perpendicular remainder (v in 0..1 spans the height).
+ edge2X = apx - s * edge1X;
+ edge2Y = apy - s * edge1Y;
+ edge2Z = apz - s * edge1Z;
+ final double heightLen = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ apexU = Math.min(1, Math.max(0, s));
+
+ cornerU[oi] = 0; cornerV[oi] = 0;
+ cornerU[ui] = 1; cornerV[ui] = 0;
+ cornerU[pi] = apexU; cornerV[pi] = 1;
+
+ // Frame-space barycentric solver for base-texture resampling
+ // (input vertices a, b, c sit at cornerU/V; the matrix is a
+ // permutation of [(1,0)-(0,0) | (apexU,1)-(0,0)], |det| = 1).
+ baryU0 = cornerU[0];
+ baryV0 = cornerV[0];
+ final double m11 = cornerU[1] - baryU0, m12 = cornerU[2] - baryU0;
+ final double m21 = cornerV[1] - baryV0, m22 = cornerV[2] - baryV0;
+ final double det = m11 * m22 - m12 * m21;
+ if (Math.abs(det) > 1e-12) {
+ bary11 = m22 / det;
+ bary12 = -m12 / det;
+ bary21 = -m21 / det;
+ bary22 = m11 / det;
+ }
+
+ final int[] dims = dimsFor(baseLen, heightLen, unitsPerTexel);
+ width = dims[0];
+ height = dims[1];
+ fineUnitsPerTexel = unitsPerTexel;
+
+ validTexels = computeValidTexels(width, height, apexU);
+
+ // Both buffers start at the uniform INITIAL_IRRADIANCE (255 =
+ // true base color, "as-is"): each lightmap flips to its traced
+ // lighting when the bake reaches it.
buffers[0] = createTexture();
buffers[1] = createTexture();
}
- private static int powerOfTwo(final double size) {
- int result = MIN_SIZE;
- while (result < size && result < MAX_SIZE)
- result <<= 1;
+ /**
+ * Lightmap dimensions for a {@code len1 x len2} bounding rect at the
+ * given density. Aspect comes FIRST (texels must be square on every
+ * triangle shape): the height rounds to a whole texel count and the
+ * width is then fitted to the ROUNDED height's aspect, and a small
+ * neighborhood search picks the best (w, h) pair. The ideal aspect
+ * is scaled into the [1, {@link #MAX_SIZE}] bounds and the
+ * {@link #MIN_SIZE}-texel long-axis floor BEFORE integer fitting,
+ * so bounds never distort the aspect â they change density, not
+ * shape. Residual anisotropy is the width's own rounding error,
+ * ~half a texel (<= ~1.1:1 above 5 texels, better as counts grow).
+ */
+ private static int[] dimsFor(final double len1, final double len2,
+ final double unitsPerTexel) {
+ if (len1 < 1e-12 || len2 < 1e-12)
+ return new int[]{MIN_SIZE, 1};
+ double b = len1 / unitsPerTexel; // ideal width in texels
+ double hh = len2 / unitsPerTexel; // ideal height in texels
+ double s = 1;
+ if (b < MIN_SIZE)
+ s = MIN_SIZE / b; // tiny triangle: raise density to the floor
+ if (b * s > MAX_SIZE)
+ s = MAX_SIZE / b; // huge triangle: lower density to the cap
+ if (hh * s > MAX_SIZE)
+ s = Math.min(s, MAX_SIZE / hh);
+ if (hh * s < 1)
+ s = Math.min(1 / hh, MAX_SIZE / b); // at least one texel high
+ b *= s;
+ hh *= s;
+
+ // Integer fit: for each candidate height near the ideal, fit the
+ // width to that height's aspect. Score = aspect deviation plus a
+ // small penalty for drifting from the ideal texel count (breaks
+ // aspect ties away from degenerate strips).
+ int bestW = MIN_SIZE, bestH = 1;
+ double bestScore = Double.MAX_VALUE;
+ final double idealArea = b * hh;
+ final int h0 = Math.max(1, (int) Math.round(hh));
+ for (int h = Math.max(1, h0 - 1); h <= Math.min(MAX_SIZE, h0 + 1); h++) {
+ final int w = Math.min(MAX_SIZE, Math.max(1,
+ (int) Math.round(b * h / hh)));
+ final double aspect = (len1 / w) / (len2 / h);
+ final double score = Math.abs(Math.log(aspect))
+ + 0.05 * Math.abs(Math.log(w * h / idealArea));
+ if (score < bestScore - 1e-9) {
+ bestScore = score;
+ bestW = w;
+ bestH = h;
+ }
+ }
+ return new int[]{bestW, bestH};
+ }
+
+ /**
+ /**
+ * Inside-triangle test in texture space for smoothing/neighborhood
+ * queries â the same region {@link #validTexels} was built from
+ * (bounding-rect frame: NOT the whole texture, NOT the old
+ * half-square).
+ */
+ public boolean isValidTexel(final int i, final int j) {
+ if (i < 0 || i >= width || j < 0 || j >= height)
+ return false;
+ final double u = (i + 0.5) / width;
+ final double v = (j + 0.5) / height;
+ return insideTriangle(u, v, apexU);
+ }
+
+ /** Valid texel indices for a w x h lightmap: texel centers inside
+ * the triangle, which sits in the bounding-rect frame at
+ * (0,0), (1,0), ({@code apexU},1).
+ */
+ private static int[] computeValidTexels(final int w, final int h, final double apexU) {
+ final int[] valid = new int[w * h];
+ int count = 0;
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) {
+ final double u = (i + 0.5) / w;
+ final double v = (j + 0.5) / h;
+ if (insideTriangle(u, v, apexU))
+ valid[count++] = j * w + i;
+ }
+ final int[] result = new int[count];
+ System.arraycopy(valid, 0, result, 0, count);
return result;
}
+ /**
+ * Point-in-triangle test in frame space, triangle (0,0), (1,0),
+ * (apexU,1). Inside = right of the left edge (u >= apexU*v), left
+ * of the right edge (u <= 1-(1-apexU)*v), above the base. A right
+ * triangle with apexU=0 or 1 collapses one constraint, matching the
+ * old u+v<=1 half-square region.
+ */
+ private static boolean insideTriangle(final double u, final double v, final double apexU) {
+ if (u < 0 || u > 1 || v < 0 || v > 1)
+ return false;
+ return u >= apexU * v - 1e-9 && u <= 1.0 - (1.0 - apexU) * v + 1e-9;
+ }
+
+ /**
+ * Stage 4: reallocates this lightmap at {@link #fineUnitsPerTexel}
+ * after the coarse bake converged. The shown composite is upscaled
+ * into the new buffers (the display does not regress at the
+ * transition itself), then the texel arrays drop to null and the
+ * fine bake rebuilds them from direct. Visibility is dropped:
+ * generation 1 re-traces shadow rays at the final resolution.
+ * No-op when the coarse and fine resolutions coincide (tiny
+ * lightmaps at the 4-texel floor).
+ *
+ *
The coarse field seeds the DISPLAY only, never the solver:
+ * the fine Neumann chain rebuilds every bounce path at fine
+ * resolution, and carrying the coarse total into the accumulated
+ * indirect would count the whole series twice (measured: floor
+ * probes at 44.0 instead of the correct 27.7).
+ */
+ public void refine() {
+ final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
+ final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ final int[] dims = dimsFor(len1, len2, fineUnitsPerTexel);
+ final int newW = dims[0], newH = dims[1];
+ if (newW == width && newH == height)
+ return;
+
+ final int oldW = width, oldH = height;
+ final Texture oldShown = shownTexture();
+
+ width = newW;
+ height = newH;
+ validTexels = computeValidTexels(newW, newH, apexU);
+ buffers[0] = upscale(oldShown.primaryBitmap.pixels, oldW, oldH, newW, newH);
+ buffers[1] = upscale(oldShown.primaryBitmap.pixels, oldW, oldH, newW, newH);
+ shownBuffer = 0;
+
+ // Texel arrays drop to null: ensureArrays re-allocates them at
+ // fine size when generation 1 reaches this lightmap, and the
+ // fine bake accumulates its own series from zero. The coarse
+ // total is deliberately NOT carried into the solver: the fine
+ // Neumann chain rebuilds paths 1..N at fine resolution, and
+ // adding them onto the coarse total would count the indirect
+ // twice (measured: floor probes 44.0 vs the correct 27.7).
+ // The coarse solution survives ONLY in the upscaled composite
+ // texture above â display continuity, never solver input.
+ indirectR = null;
+ indirectG = null;
+ indirectB = null;
+ deltaPrevR = null;
+ deltaPrevG = null;
+ deltaPrevB = null;
+ deltaCurR = null;
+ deltaCurG = null;
+ deltaCurB = null;
+ lightVisibility = null;
+ generation = 0;
+ baked = false; // a resize invalidates the bake: fine pass pending
+ directBaked = false; // fine-phase generation 1 re-traces direct
+ resampleBaseTexels();
+ if (owner != null) {
+ // The triangle's UVs are pinned to the lightmap corners in
+ // TEXTURE PIXELS â re-pin them to the fine dimensions or
+ // the painter would sample only the coarse-sized corner of
+ // the fine texture.
+ owner.repinUvToLightmap();
+ owner.setTexture(buffers[0]);
+ }
+ }
+
+ /**
+ * True when this lightmap still runs at a coarser resolution than
+ * {@link #fineUnitsPerTexel} implies (i.e. {@link #refine()} would
+ * reallocate). Used by the GI catch-up watcher: a coarse-baked
+ * lightmap whose triangle enters the stage-4 radius gets refined
+ * and re-baked at the final density.
+ *
+ * @return true when a refine would change the dimensions
+ */
+ public boolean needsRefine() {
+ final double len1 = Math.sqrt(edge1X * edge1X + edge1Y * edge1Y + edge1Z * edge1Z);
+ final double len2 = Math.sqrt(edge2X * edge2X + edge2Y * edge2Y + edge2Z * edge2Z);
+ final int[] dims = dimsFor(len1, len2, fineUnitsPerTexel);
+ return dims[0] != width || dims[1] != height;
+ }
+
+ /** Bilinear upscale of a composite texture into a new w x h texture. */
+ private static Texture upscale(final int[] sp, final int sw, final int sh,
+ final int w, final int h) {
+ final Texture out = new Texture(w, h, 0);
+ final int[] dp = out.primaryBitmap.pixels;
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) {
+ final double sx = Math.min(sw - 1.0, Math.max(0.0, (i + 0.5) * sw / w - 0.5));
+ final double sy = Math.min(sh - 1.0, Math.max(0.0, (j + 0.5) * sh / h - 0.5));
+ final int x0 = (int) sx, y0 = (int) sy;
+ final int x1 = Math.min(sw - 1, x0 + 1), y1 = Math.min(sh - 1, y0 + 1);
+ final double fx = sx - x0, fy = sy - y0;
+ dp[j * w + i] = bilinear(sp[y0 * sw + x0], sp[y0 * sw + x1],
+ sp[y1 * sw + x0], sp[y1 * sw + x1], fx, fy);
+ }
+ return out;
+ }
+
+ /** Bilinear mix of four ARGB pixels, per channel. */
+ private static int bilinear(final int p00, final int p10, final int p01, final int p11,
+ final double fx, final double fy) {
+ final double w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy);
+ final double w01 = (1 - fx) * fy, w11 = fx * fy;
+ final int r = Math.min(255, (int) (w00 * ((p00 >> 16) & 255) + w10 * ((p10 >> 16) & 255)
+ + w01 * ((p01 >> 16) & 255) + w11 * ((p11 >> 16) & 255)));
+ final int g = Math.min(255, (int) (w00 * ((p00 >> 8) & 255) + w10 * ((p10 >> 8) & 255)
+ + w01 * ((p01 >> 8) & 255) + w11 * ((p11 >> 8) & 255)));
+ final int b = Math.min(255, (int) (w00 * (p00 & 255) + w10 * (p10 & 255)
+ + w01 * (p01 & 255) + w11 * (p11 & 255)));
+ return 0xFF000000 | (r << 16) | (g << 8) | b;
+ }
+
private Texture createTexture() {
final Texture texture = new Texture(width, height, 0);
final int r = Math.min(255, (int) (INITIAL_IRRADIANCE * baseColor.r / 255));
@@ -236,6 +706,31 @@ public class Lightmap {
* @return texel index, clamped into the texture
*/
public int texelAt(final double px, final double py, final double pz) {
+ final double[] uv = new double[2];
+ uvAt(px, py, pz, uv);
+ int i = (int) (uv[0] * width);
+ int j = (int) (uv[1] * height);
+ if (i < 0) i = 0;
+ if (i >= width) i = width - 1;
+ if (j < 0) j = 0;
+ if (j >= height) j = height - 1;
+ return j * width + i;
+ }
+
+ /**
+ * Parametric (u, v) of a world-space point on this lightmap's quad.
+ * Resolution-independent: callers sampling a texture whose size can
+ * change under them (GI catch-up reading a composite while another
+ * worker {@link #refine()}s this lightmap) scale (u, v) by the
+ * texture's own dimensions and stay in bounds. Values may fall
+ * slightly outside 0..1 for edge hits; callers clamp after scaling.
+ *
+ * @param px world x
+ * @param py world y
+ * @param pz world z
+ * @param out receives {u, v}
+ */
+ public void uvAt(final double px, final double py, final double pz, final double[] out) {
final double dx = px - originX;
final double dy = py - originY;
final double dz = pz - originZ;
@@ -245,17 +740,13 @@ public class Lightmap {
final double dp1 = dx * edge1X + dy * edge1Y + dz * edge1Z;
final double dp2 = dx * edge2X + dy * edge2Y + dz * edge2Z;
final double denom = d11 * d22 - d12 * d12;
- if (denom < 1e-12)
- return 0;
- final double u = (dp1 * d22 - dp2 * d12) / denom;
- final double v = (dp2 * d11 - dp1 * d12) / denom;
- int i = (int) (u * width);
- int j = (int) (v * height);
- if (i < 0) i = 0;
- if (i >= width) i = width - 1;
- if (j < 0) j = 0;
- if (j >= height) j = height - 1;
- return j * width + i;
+ if (denom < 1e-12) {
+ out[0] = 0;
+ out[1] = 0;
+ return;
+ }
+ out[0] = (dp1 * d22 - dp2 * d12) / denom;
+ out[1] = (dp2 * d11 - dp1 * d12) / denom;
}
/**
@@ -298,6 +789,10 @@ public class Lightmap {
}
generation = 0;
baked = false;
+ // Visibility bytes were just (re)allocated blank: the direct
+ // pass that follows re-traces them. Until it completes, the
+ // catch-up watcher must treat this lightmap as never-baked.
+ directBaked = false;
}
/**
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmapCache.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmapCache.java
new file mode 100644
index 0000000..4a25eef
--- /dev/null
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmapCache.java
@@ -0,0 +1,104 @@
+/*
+ * Aukio 3D engine. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
+ */
+package eu.svjatoslav.aukio.e3d.renderer.raster.gi;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * RAM cache of baked lightmap composite textures, keyed by a 64-bit
+ * hash of the triangle's three world-space vertices. Streaming worlds
+ * (FO4 cells) discard and rebuild their mesh blocks as the camera
+ * travels; a cache hit rebuilds the lightmap's display textures
+ * instantly, without re-running the bake. RAM-only, per GI instance â
+ * nothing is persisted to disk.
+ *
+ * Only the final COMPOSITE pixels are cached (plus dimensions);
+ * bake-state texel arrays are transient by design. A dimension mismatch
+ * (different texel density configuration) is a miss.
+ *
+ * Capacity is capped ({@code e3d.giLightmapCacheEntries}); eviction
+ * is least-recently-used. Thread-safe.
+ */
+final class LightmapCache {
+
+ /** One cached composite. */
+ static final class Entry {
+ final int width;
+ final int height;
+ final int[] pixels;
+ /** Lighting signature under which the composite was baked; a
+ * light change invalidates the entry (restore compares). */
+ final double lightSignature;
+
+ Entry(final int width, final int height, final int[] pixels,
+ final double lightSignature) {
+ this.width = width;
+ this.height = height;
+ this.pixels = pixels;
+ this.lightSignature = lightSignature;
+ }
+ }
+
+ private final LinkedHashMap map;
+
+ LightmapCache(final int capacity) {
+ map = new LinkedHashMap<>(256, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(
+ final Map.Entry e) {
+ return size() > capacity;
+ }
+ };
+ }
+
+ /**
+ * Geometry key for a triangle: splitmix64-mixed double bits of the
+ * 9 world-space vertex coordinates. Deterministic across block
+ * rebuilds from identical source data.
+ */
+ static long key(final double[] world9) {
+ long h = 0x9E3779B97F4A7C15L;
+ for (int i = 0; i < 9; i++) {
+ long z = Double.doubleToLongBits(world9[i]) + 0x9E3779B97F4A7C15L
+ + (h << 6) + (h >>> 2);
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ h ^= z ^ (z >>> 31);
+ }
+ return h;
+ }
+
+ /**
+ * Geometry key over float vertex bits (TriangleBvh.Entry.v).
+ * Deterministic across block rebuilds from identical source data.
+ */
+ static long key(final float[] world9) {
+ long h = 0x9E3779B97F4A7C15L;
+ for (int i = 0; i < 9; i++) {
+ long z = Float.floatToIntBits(world9[i]) + 0x9E3779B97F4A7C15L
+ + (h << 6) + (h >>> 2);
+ z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
+ z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
+ h ^= z ^ (z >>> 31);
+ }
+ return h;
+ }
+
+ /** Looks up a cached composite; marks it recently used. */
+ synchronized Entry get(final long key) {
+ return map.get(key);
+ }
+
+ /** Stores a composite (the pixel array is adopted, not copied). */
+ synchronized void put(final long key, final int width, final int height,
+ final int[] pixels, final double lightSignature) {
+ map.put(key, new Entry(width, height, pixels, lightSignature));
+ }
+
+ synchronized int size() {
+ return map.size();
+ }
+}
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmappedTriangle.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmappedTriangle.java
index 0df0d60..8d7ae9e 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmappedTriangle.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/LightmappedTriangle.java
@@ -43,21 +43,38 @@ public class LightmappedTriangle extends TexturedTriangle implements Lightmapped
new Vertex(b, new Point2D(1, 0)),
new Vertex(c, new Point2D(0, 1)),
null);
- lightmap = new Lightmap(a, b, c, baseColor, unitsPerTexel,
+ lightmap = new Lightmap(a, b, c, baseColor,
+ GlobalIllumination.lightmapUnitsPerTexel(unitsPerTexel),
normalX, normalY, normalZ);
+ // The raw configured resolution is where stage 4 refines to.
+ lightmap.fineUnitsPerTexel = unitsPerTexel;
lightmap.owner = this;
// UVs are in PRIMARY TEXTURE PIXELS in this engine (multiplication
// factor scales them into the selected mip level), so the triangle
// corners map to the lightmap corners directly.
- vertices.get(0).textureCoordinate = new Point2D(0, 0);
- vertices.get(1).textureCoordinate = new Point2D(lightmap.width, 0);
- vertices.get(2).textureCoordinate = new Point2D(0, lightmap.height);
- refreshTextureDistance();
+ repinUvToLightmap();
setTexture(lightmap.shownTexture());
}
+ /**
+ * Pins the corner UVs to the lightmap's CURRENT dimensions and
+ * refreshes the texture-distance estimate. Called at construction
+ * and by {@link Lightmap#refine()} (stage 4 changes the texture
+ * size â without re-pinning, the painter would sample only the
+ * coarse-sized corner of the fine texture). Each vertex gets its
+ * own frame-space corner ({@link Lightmap#cornerU}/{@code cornerV})
+ * â the bounding-rect frame may assign any corner to any vertex.
+ */
+ public void repinUvToLightmap() {
+ for (int k = 0; k < 3; k++)
+ vertices.get(k).textureCoordinate = new Point2D(
+ lightmap.cornerU[k] * lightmap.width,
+ lightmap.cornerV[k] * lightmap.height);
+ refreshTextureDistance();
+ }
+
@Override
public Lightmap getLightmap() {
return lightmap;
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/TriangleBvh.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/TriangleBvh.java
index 323a6fe..4782954 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/TriangleBvh.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/gi/TriangleBvh.java
@@ -43,6 +43,15 @@ public class TriangleBvh {
/** Squared distance from the camera at snapshot build (near-to-far bake order). */
public float distance;
+ /**
+ * Radius-gating mask, re-evaluated from the live camera position
+ * at every generation barrier: bit 0 = eligible for stage 2
+ * (centroid bounce), bit 1 = stage 3 (coarse per-texel), bit 2 =
+ * stage 4 (fine refinement). All bits set when no radius is
+ * configured (the historical global bake).
+ */
+ public volatile int eligibleStages = 7;
+
public Entry(final AbstractCoordinateShape polygon) {
this.polygon = polygon;
this.block = null;
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/Atmosphere.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/Atmosphere.java
new file mode 100644
index 0000000..71f291e
--- /dev/null
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/Atmosphere.java
@@ -0,0 +1,182 @@
+/*
+ * Aukio 3D engine. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
+ */
+package eu.svjatoslav.aukio.e3d.renderer.raster.lighting;
+
+import eu.svjatoslav.aukio.e3d.diag.EngineConfig;
+import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
+
+/**
+ * Optional distance haze ("atmospheric perspective"): geometry fades
+ * toward the sky color as camera-space depth grows, factor
+ * {@code f = 1 - exp(-depth / scale)}. Disabled by default; enable per
+ * scene ({@link #setEnabled}, the Fallout 4 environment does) or
+ * globally with {@code -De3d.atmosphere=true} /
+ * {@code e3d.atmosphere: true} in the config file
+ * (bugreport-20261006-000922).
+ *
+ * Cost model: the factor is evaluated once per polygon per frame and
+ * folded into the same per-polygon light multiplier the span loops
+ * already apply â {@code texel * (light*(1-f)) + sky*f} â so the
+ * per-pixel price on textured triangles is one ADD per channel and no
+ * additional multiplication. Solid polygons precompute one shaded color
+ * per polygon, so their per-pixel cost is exactly zero. Lightmapped
+ * triangles sit inside the stage-3 bubble a few hundred units from the
+ * camera, where the factor rounds to zero for any practical scale; that
+ * path is deliberately left untouched.
+ *
+ * The haze target color is the configured {@code e3d.atmosphereColor}
+ * when set, otherwise the scene's sky color
+ * ({@link LightingManager#getSkyColor()}), so the horizon blends into
+ * the backdrop seamlessly. With neither, haze is inert.
+ */
+public final class Atmosphere {
+
+ /** Runtime enable override from environment modules; null = config. */
+ private static volatile Boolean enabledOverride;
+ /** Runtime scale override; NaN = config. */
+ private static volatile double scaleOverride = Double.NaN;
+ /** Runtime haze color override; null = config or scene sky color. */
+ private static volatile Color colorOverride;
+
+ /**
+ * Resolved file/property configuration, read once per JVM: the
+ * getters below run per TRIANGLE per frame, so they must never
+ * re-navigate the config file (bugreport-20261006-000922: a
+ * per-call AukioConfig lookup made a 649k-shape frame render 15x
+ * slower).
+ */
+ private static volatile Resolved config;
+
+ /** Immutable resolved configuration triple. */
+ private record Resolved(boolean enabled, double scale, Color color) {
+ }
+
+ private static Resolved config() {
+ Resolved r = config;
+ if (r == null) {
+ synchronized (Atmosphere.class) {
+ r = config;
+ if (r == null) {
+ final String hex = EngineConfig.getAtmosphereColor();
+ r = new Resolved(EngineConfig.isAtmosphereEnabled(),
+ EngineConfig.getAtmosphereScale(),
+ hex == null || hex.isEmpty()
+ ? null : Color.hex(hex));
+ config = r;
+ }
+ }
+ }
+ return r;
+ }
+
+ private Atmosphere() {
+ }
+
+ /**
+ * Enables or disables the haze at runtime (environment modules).
+ * Wins over {@code e3d.atmosphere}; see {@link #resetOverrides()}.
+ *
+ * @param enabled true to haze distant geometry toward the sky color
+ */
+ public static void setEnabled(final boolean enabled) {
+ enabledOverride = enabled;
+ }
+
+ /**
+ * Sets the haze scale at runtime: the camera depth at which the haze
+ * factor reaches ~63% (1 - 1/e). Wins over
+ * {@code e3d.atmosphereScale}.
+ *
+ * @param scale world units
+ */
+ public static void setScale(final double scale) {
+ scaleOverride = scale;
+ }
+
+ /**
+ * Sets the haze target color at runtime. Wins over
+ * {@code e3d.atmosphereColor} and the scene sky color.
+ *
+ * @param color haze color, or null to fall back to configuration
+ */
+ public static void setColor(final Color color) {
+ colorOverride = color;
+ }
+
+ /** Drops all runtime overrides; configuration applies again. */
+ public static void resetOverrides() {
+ enabledOverride = null;
+ scaleOverride = Double.NaN;
+ colorOverride = null;
+ }
+
+ /** Returns whether distance haze is active. */
+ public static boolean enabled() {
+ final Boolean o = enabledOverride;
+ return o != null ? o : config().enabled();
+ }
+
+ /** Returns the haze scale in world units. */
+ public static double scale() {
+ final double o = scaleOverride;
+ return Double.isNaN(o) ? config().scale() : o;
+ }
+
+ /**
+ * The haze factor for a camera-space depth: 0 at the camera,
+ * approaching 1 at infinity. Returns 0 when the haze is disabled or
+ * the depth is behind the near plane.
+ *
+ * @param cameraDepth camera-space Z of the polygon
+ * @return haze blend factor in [0, 1)
+ */
+ public static float factor(final double cameraDepth) {
+ if (cameraDepth <= 0 || !enabled())
+ return 0f;
+ final double s = scale();
+ if (s <= 0)
+ return 0f;
+ final float f = (float) (1.0 - Math.exp(-cameraDepth / s));
+ // Sub-perceptible factors round to zero so near geometry keeps
+ // the bit-identical haze-free span path.
+ return f < 1.0e-4f ? 0f : Math.min(f, 1f);
+ }
+
+ /**
+ * Resolves the haze target color: runtime override, then the
+ * configured {@code e3d.atmosphereColor}, then the scene's sky color.
+ *
+ * @param lighting the scene lighting manager, or null
+ * @return the color to fade toward, or null when none is known
+ * (haze stays inert)
+ */
+ public static Color targetColor(final LightingManager lighting) {
+ final Color o = colorOverride;
+ if (o != null)
+ return o;
+ final Color configured = config().color();
+ if (configured != null)
+ return configured;
+ return lighting == null ? null : lighting.getSkyColor();
+ }
+
+ /**
+ * Blends a per-polygon shaded color toward the haze target in place:
+ * {@code c = c*(1-f) + target*f}. Called once per polygon per frame
+ * â the span loops keep painting the constant result, so solid
+ * polygons pay zero per-pixel cost for the haze.
+ *
+ * @param shaded the polygon's lit color, mutated
+ * @param f haze factor from {@link #factor(double)}
+ * @param target haze target color from {@link #targetColor}
+ */
+ public static void applyHaze(final Color shaded, final float f,
+ final Color target) {
+ final float keep = 1f - f;
+ shaded.r = Color.clamp((int) (shaded.r * keep + target.r * f + 0.5f));
+ shaded.g = Color.clamp((int) (shaded.g * keep + target.g * f + 0.5f));
+ shaded.b = Color.clamp((int) (shaded.b * keep + target.b * f + 0.5f));
+ }
+}
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/LightingManager.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/LightingManager.java
index 6ec3972..dd75841 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/LightingManager.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/LightingManager.java
@@ -58,6 +58,13 @@ public class LightingManager {
*/
private volatile GiLightProvider giProvider;
+ /**
+ * Sky dome color for GI bounce rays that escape the scene; see
+ * {@link #setSkyColor(Color)}. Volatile: the GI workers read it at
+ * snapshot (re)build time on their own threads.
+ */
+ private volatile Color skyColor;
+
/**
* Creates a new lighting manager with no light sources.
*/
@@ -258,6 +265,29 @@ public class LightingManager {
this.ambientLight = ambientLight;
}
+ /**
+ * Sky dome color sampled by global-illumination bounce rays that
+ * escape the scene (hit nothing). Null (default) = no sky
+ * contribution: misses contribute zero, the historical behavior.
+ * Set this to the same color the app clears its background with, so
+ * shadowed surfaces pick up a sky-tinted first bounce instead of
+ * going black.
+ *
+ * @return the sky dome color, or null when sky sampling is off
+ */
+ public Color getSkyColor() {
+ return skyColor;
+ }
+
+ /**
+ * Sets the sky dome color for GI bounce rays that escape the scene.
+ *
+ * @param skyColor the sky color, or null to disable sky sampling
+ */
+ public void setSkyColor(final Color skyColor) {
+ this.skyColor = skyColor;
+ }
+
/**
* Returns all light sources in the scene.
*
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/solidpolygon/SolidPolygon.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/solidpolygon/SolidPolygon.java
index e8d315d..bb28b93 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/solidpolygon/SolidPolygon.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/solidpolygon/SolidPolygon.java
@@ -13,6 +13,7 @@ import eu.svjatoslav.aukio.e3d.math.TransformStack;
import eu.svjatoslav.aukio.e3d.renderer.raster.Vertex;
import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderAggregator;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractCoordinateShape;
import java.util.ArrayList;
@@ -844,6 +845,21 @@ public class SolidPolygon extends AbstractCoordinateShape {
renderingContext.lightingManager.computeLighting(
this, cachedCenter, cachedBackNormal, color, backShadedColor);
}
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // folded into the per-polygon shaded color itself, so the
+ // span loops keep painting one constant color â zero
+ // per-pixel cost.
+ if (Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderingContext));
+ final Color hazeTarget = f > 0f
+ ? Atmosphere.targetColor(
+ renderingContext.lightingManager) : null;
+ if (hazeTarget != null) {
+ Atmosphere.applyHaze(shadedColor, f, hazeTarget);
+ if (!backfaceCulling)
+ Atmosphere.applyHaze(backShadedColor, f, hazeTarget);
+ }
+ }
}
}
}
\ No newline at end of file
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/MeshTriangle.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/MeshTriangle.java
index 897a12b..0b187dc 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/MeshTriangle.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/MeshTriangle.java
@@ -3,6 +3,7 @@ package eu.svjatoslav.aukio.e3d.renderer.raster.shapes.basic.texturedpolygon;
import eu.svjatoslav.aukio.e3d.geometry.Point2D;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderingContext;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderAggregator;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.math.TransformStack;
/**
@@ -75,19 +76,67 @@ final class MeshTriangle extends TexturedTriangle {
final Point2D[] screen = SCREEN_SCRATCH.get();
final Point2D[] uvs = UV_SCRATCH.get();
+ // Per-texel GI lightmap (attached when this triangle sits inside
+ // the stage-3 radius bubble): once a real composite has landed,
+ // the composite texture IS the paint source â base texture and
+ // lighting premultiplied â so the per-triangle shade multiply
+ // must go away. Before the first composite the triangle keeps
+ // the base texture + per-triangle shade (progressive, never a
+ // flat-color regression).
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmap =
+ block.lightmapAt(index);
+ final int clip = block.clipOffset(slot, index);
+ // Near-plane straddlers keep base texture + shade this frame:
+ // the clip store carries base-texture UVs, not lightmap UVs.
+ final boolean useLightmap = lightmap != null && lightmap.everComposited
+ && clip < 0;
+
// Per-triangle GI light (null while no GI system traces this
// block): the span loops multiply texels by it. Values are read
// racily from the GI threads â fine for converging estimates.
- final float[] giLight = block.giLight();
- if (giLight != null) {
- final int i = index * 3;
- giShadeR = giLight[i];
- giShadeG = giLight[i + 1];
- giShadeB = giLight[i + 2];
- giShaded = true;
+ if (!useLightmap) {
+ final float[] giLight = block.giLight();
+ if (giLight != null) {
+ final int i = index * 3;
+ giShadeR = giLight[i];
+ giShadeG = giLight[i + 1];
+ giShadeB = giLight[i + 2];
+ giShaded = true;
+ }
+ } else {
+ // Composite carries all light; no shade multiply.
+ giShaded = false;
+ }
+
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // evaluated once per triangle and folded into the same
+ // per-triangle multiplier the span loops already apply â
+ // texel * (shade*(1-f)) + sky*f â so the per-pixel price is one
+ // add per channel, no extra multiplication. Lightmapped
+ // triangles sit inside the stage-3 bubble, a few hundred units
+ // from the camera: the factor rounds to zero there for any
+ // practical atmosphere scale, so the composite path is left
+ // untouched.
+ if (!useLightmap && Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderBuffer));
+ final eu.svjatoslav.aukio.e3d.renderer.raster.Color sky =
+ f > 0f ? Atmosphere.targetColor(
+ renderBuffer.lightingManager) : null;
+ if (sky == null) {
+ hazed = false;
+ } else {
+ final float att = 1f - f;
+ if (giShaded)
+ setHaze(giShadeR * att, giShadeG * att, giShadeB * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ else
+ setHaze(255f * att, 255f * att, 255f * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ }
+ } else {
+ hazed = false;
}
- final int clip = block.clipOffset(slot, index);
if (clip >= 0) {
// Near-plane straddler: the block clipped to a loop of 3-4
// vertices, stored as (x, y, z, u, v, sx, sy) tuples. Paint
@@ -125,6 +174,29 @@ final class MeshTriangle extends TexturedTriangle {
block.loadScreenVertex(screen[0], uvs[0], slot, index, 0, renderBuffer);
block.loadScreenVertex(screen[1], uvs[1], slot, index, 1, renderBuffer);
block.loadScreenVertex(screen[2], uvs[2], slot, index, 2, renderBuffer);
+ if (useLightmap) {
+ // Pin UVs to the lightmap corners (texture pixels), exactly
+ // like LightmappedTriangle. The lightmap's own UV perimeter
+ // drives mipmap selection (texel density differs from the
+ // base texture's). UVs come from the lightmap's frame
+ // corners: the bounding-rect frame may assign any corner
+ // of the rect to any vertex of the triangle.
+ final int w = lightmap.width, h = lightmap.height;
+ for (int k = 0; k < 3; k++) {
+ uvs[k].x = lightmap.cornerU[k] * w;
+ uvs[k].y = lightmap.cornerV[k] * h;
+ }
+ paintFlat(renderBuffer, lightmap.shownTexture(),
+ block.backfaceCull(),
+ screen[0], screen[1], screen[2],
+ uvs[0], uvs[1], uvs[2],
+ block.camZ(slot, index, 0),
+ block.camZ(slot, index, 1),
+ block.camZ(slot, index, 2),
+ block.screenPerim(slot, index),
+ lightmap.uvPerimeter());
+ return;
+ }
paintFlat(renderBuffer, block.texture(index), block.backfaceCull(),
screen[0], screen[1], screen[2],
uvs[0], uvs[1], uvs[2],
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TexturedTriangle.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TexturedTriangle.java
index 06ae952..b2eaf12 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TexturedTriangle.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TexturedTriangle.java
@@ -7,6 +7,7 @@ package eu.svjatoslav.aukio.e3d.renderer.raster.shapes.basic.texturedpolygon;
import eu.svjatoslav.aukio.e3d.geometry.Point2D;
import eu.svjatoslav.aukio.e3d.renderer.raster.RenderingContext;
import eu.svjatoslav.aukio.e3d.renderer.raster.Vertex;
+import eu.svjatoslav.aukio.e3d.renderer.raster.lighting.Atmosphere;
import eu.svjatoslav.aukio.e3d.renderer.raster.shapes.AbstractCoordinateShape;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.Texture;
import eu.svjatoslav.aukio.e3d.renderer.raster.texture.TextureBitmap;
@@ -122,18 +123,46 @@ public class TexturedTriangle extends AbstractCoordinateShape {
private boolean backfaceCulling = Boolean.getBoolean("e3d.backface");
- // ---- per-triangle GI shading (mesh-block path only) ----
+ // ---- per-triangle GI shading ----
/**
* Per-triangle light total in light units (255 = full texture
- * brightness), written by {@code MeshTriangle.paint} from the owning
- * block's GI arrays before the paint core runs. Object-backed
- * triangles never touch these: {@link #giShaded} stays false and the
- * span loops render bit-identically to the unlit path.
+ * brightness). Two writers: {@code MeshTriangle.paint} copies it
+ * from the owning block's GI arrays before the paint core runs, and
+ * the GI system stamps it on a {@code LightmappedTriangle} for the
+ * stage-1 uniform preview (cleared when the first real composite
+ * lands). While {@link #giShaded} is false the span loops render
+ * bit-identically to the unlit path.
*/
float giShadeR, giShadeG, giShadeB;
- /** True while {@link #giShadeR/G/B} carry a GI light total. */
- boolean giShaded;
+ /**
+ * True while {@link #giShadeR/G/B} carry a GI light total. Volatile:
+ * the GI worker threads stamp/clear it on lightmapped triangles
+ * while render threads read it in the span loops; the float triplet
+ * piggybacks on this flag's happens-before edge.
+ */
+ volatile boolean giShaded;
+
+ /**
+ * Stamps a uniform GI light triplet on this triangle (stage-1
+ * preview): the span loops multiply every sampled texel by
+ * triplet / 255 until {@link #clearGiShade()} is called.
+ *
+ * @param r red light units (255 = full)
+ * @param g green light units
+ * @param b blue light units
+ */
+ public void setGiShade(final float r, final float g, final float b) {
+ giShadeR = r;
+ giShadeG = g;
+ giShadeB = b;
+ giShaded = true; // last: volatile release publishes the triplet
+ }
+
+ /** Returns to painting the bare texture (stage-1 preview over). */
+ public void clearGiShade() {
+ giShaded = false;
+ }
/**
* Multiplies a sampled texel by the per-triangle GI light, clamped.
@@ -149,6 +178,68 @@ public class TexturedTriangle extends AbstractCoordinateShape {
return (texel & 0xFF000000) | (r << 16) | (g << 8) | b;
}
+ // ---- per-triangle atmospheric haze ----
+
+ /**
+ * Per-triangle atmospheric haze in light units: {@code hazeMul*}
+ * is the shade multiplier with the (1-f) attenuation ALREADY folded
+ * in (GI shade à (1-f), or 255Ã(1-f) when no GI shades this
+ * triangle), {@code hazeAdd*} is the additive sky term skyÃf.
+ * Stamped once per triangle per frame from the paint path when the
+ * atmosphere is enabled (bugreport-20261006-000922). While
+ * {@link #hazed} is false the span loops render bit-identically to
+ * the haze-free path.
+ */
+ float hazeMulR, hazeMulG, hazeMulB, hazeAddR, hazeAddG, hazeAddB;
+ /** True while the haze sextet carries an active haze blend. */
+ boolean hazed;
+
+ /**
+ * Stamps this triangle's haze blend: the span loops compute
+ * {@code texel * mul / 255 + add} per channel â the attenuation half
+ * of the haze rides the light multiply that already exists, so the
+ * per-pixel price is one add per channel, no extra multiplication.
+ *
+ * @param mulR red shade multiplier including (1-f) (255 = full)
+ * @param mulG green multiplier
+ * @param mulB blue multiplier
+ * @param addR red additive sky term (sky à f)
+ * @param addG green additive term
+ * @param addB blue additive term
+ */
+ public void setHaze(final float mulR, final float mulG,
+ final float mulB, final float addR,
+ final float addG, final float addB) {
+ hazeMulR = mulR;
+ hazeMulG = mulG;
+ hazeMulB = mulB;
+ hazeAddR = addR;
+ hazeAddG = addG;
+ hazeAddB = addB;
+ hazed = true;
+ }
+
+ /** Returns to the haze-free span path (atmosphere off or too near). */
+ public void clearHaze() {
+ hazed = false;
+ }
+
+ /**
+ * Applies the haze blend to a sampled texel, clamped. Called only on
+ * the {@link #hazed} path.
+ */
+ private int shadeHaze(final int texel) {
+ final int r = Math.min(255,
+ (int) (((texel >> 16) & 0xff) * hazeMulR / 255f
+ + hazeAddR));
+ final int g = Math.min(255,
+ (int) (((texel >> 8) & 0xff) * hazeMulG / 255f
+ + hazeAddG));
+ final int b = Math.min(255,
+ (int) ((texel & 0xff) * hazeMulB / 255f + hazeAddB));
+ return (texel & 0xFF000000) | (r << 16) | (g << 8) | b;
+ }
+
// --- ad-hoc frame profiling (-De3d.prof=true; dead code when off)
/** Master switch, constant-folded when false. */
private static final boolean PROF =
@@ -396,7 +487,8 @@ public class TexturedTriangle extends AbstractCoordinateShape {
}
final int sampledPixel = texPixels[ity * texW + itx];
- final int srcPixel = giShaded ? shadeGi(sampledPixel) : sampledPixel;
+ final int srcPixel = hazed ? shadeHaze(sampledPixel)
+ : giShaded ? shadeGi(sampledPixel) : sampledPixel;
final int srcAlpha = (srcPixel >> 24) & 0xff;
if (srcAlpha == 255) {
@@ -438,6 +530,33 @@ public class TexturedTriangle extends AbstractCoordinateShape {
@Override
public void paint(final RenderingContext renderBuffer) {
+ // Atmospheric haze (optional, bugreport-20261006-000922):
+ // stamped once per triangle per frame, folded into the same
+ // multiplier the span loops already apply â see MeshTriangle.
+ // LightmappedTriangle flows through here too: it lives inside
+ // the stage-3 bubble a few hundred units out, where the factor
+ // rounds to zero for any practical scale, so composites stay
+ // untouched in practice.
+ if (Atmosphere.enabled()) {
+ final float f = Atmosphere.factor(getZ(renderBuffer));
+ // java.awt.* is wildcard-imported in this file â qualify
+ final eu.svjatoslav.aukio.e3d.renderer.raster.Color sky =
+ f > 0f ? Atmosphere.targetColor(
+ renderBuffer.lightingManager) : null;
+ if (sky == null) {
+ hazed = false;
+ } else {
+ final float att = 1f - f;
+ if (giShaded)
+ setHaze(giShadeR * att, giShadeG * att, giShadeB * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ else
+ setHaze(255f * att, 255f * att, 255f * att,
+ sky.r * f, sky.g * f, sky.b * f);
+ }
+ } else {
+ hazed = false;
+ }
// Near-plane clip output takes precedence: a straddling triangle
// clips to a triangle or a quad (one corner cut off). The quad is
// painted as a 2-triangle fan â the clip of a convex polygon stays
@@ -1477,7 +1596,8 @@ public class TexturedTriangle extends AbstractCoordinateShape {
}
final int sampledPixel = texPixels[ity * texW + itx];
- final int srcPixel = giShaded ? shadeGi(sampledPixel) : sampledPixel;
+ final int srcPixel = hazed ? shadeHaze(sampledPixel)
+ : giShaded ? shadeGi(sampledPixel) : sampledPixel;
final int srcAlpha = (srcPixel >> 24) & 0xff;
if (srcAlpha == 255) {
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.java
index ad92dba..af0ff53 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/basic/texturedpolygon/TriangleMeshBlock.java
@@ -40,8 +40,9 @@ import eu.svjatoslav.aukio.e3d.math.TransformStack;
* dedicated GI threads.
*
* Limitations vs object-backed triangles: no mouse picking, no SDF
- * textures (rejected at build), no per-texel lightmaps (GI lands per
- * triangle â the right granularity for game meshes).
+ * textures (rejected at build). Per-texel lightmaps exist only inside
+ * the GI stage-3 radius bubble (see {@link #lightmapAt}); outside it GI
+ * lands per triangle â the right granularity for far game meshes.
*/
public final class TriangleMeshBlock extends AbstractShape {
@@ -67,6 +68,17 @@ public final class TriangleMeshBlock extends AbstractShape {
*/
private volatile float[] giLight;
+ /**
+ * Per-triangle lightmaps, attached lazily by the GI system for
+ * triangles inside the stage-3 radius bubble ({@code
+ * e3d.giStage3Radius}); null slots keep the per-triangle
+ * {@link #giLight} shade as their terminal display. The paint path
+ * switches to the lightmap's composite texture once a real
+ * composite has landed ({@code Lightmap.everComposited}). Null until
+ * the first attach.
+ */
+ private volatile eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] lightmaps;
+
/**
* Lazy per-texture average color (albedo source for GI bounce rays),
* keyed by texture because a block's triangles share few textures.
@@ -301,6 +313,78 @@ public final class TriangleMeshBlock extends AbstractShape {
out[i] = (float) world[w + i];
}
+ /**
+ * Copies the triangle's 9 world-space vertex coordinates at full
+ * double precision (GI lightmap construction and cache keys).
+ *
+ * @param tri triangle index
+ * @param out destination array of at least 9 doubles
+ */
+ public void triangleWorld(final int tri, final double[] out) {
+ final int w = tri * 9;
+ System.arraycopy(world, w, out, 0, 9);
+ }
+
+ /**
+ * Copies the triangle's 6 UV coordinates (primary-texture pixels).
+ * Used by the GI system when attaching a lightmap.
+ *
+ * @param tri triangle index
+ * @param out destination array of at least 6 doubles
+ */
+ public void triangleUv(final int tri, final double[] out) {
+ final int u = tri * 6;
+ System.arraycopy(uv, u, out, 0, 6);
+ }
+
+ // ---- per-triangle lightmaps (GI stage 3/4, radius-gated) ----
+
+ /**
+ * The lightmap attached to a triangle, or null when the triangle is
+ * outside the stage-3 bubble (or GI has not reached it yet).
+ *
+ * @param tri triangle index
+ * @return the lightmap or null
+ */
+ public eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmapAt(
+ final int tri) {
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] maps =
+ lightmaps;
+ return maps == null ? null : maps[tri];
+ }
+
+ /**
+ * Attaches a lightmap to a triangle unless one is already attached.
+ * Called from GI threads; idempotent and thread-safe.
+ *
+ * @param tri triangle index
+ * @param lightmap the candidate lightmap
+ * @return the lightmap actually attached to the slot (the argument,
+ * or the pre-existing one on a lost race)
+ */
+ public eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap attachLightmapIfAbsent(
+ final int tri,
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap lightmap) {
+ eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap[] maps = lightmaps;
+ if (maps == null) {
+ synchronized (this) {
+ if (lightmaps == null)
+ lightmaps = new eu.svjatoslav.aukio.e3d.renderer.raster
+ .gi.Lightmap[triCount];
+ maps = lightmaps;
+ }
+ }
+ final eu.svjatoslav.aukio.e3d.renderer.raster.gi.Lightmap existing =
+ maps[tri];
+ if (existing != null)
+ return existing;
+ synchronized (this) {
+ if (maps[tri] == null)
+ maps[tri] = lightmap;
+ return maps[tri];
+ }
+ }
+
@Override
public Box getBoundingBox() {
return boundingBox;
@@ -588,7 +672,12 @@ public final class TriangleMeshBlock extends AbstractShape {
return camZ[slot][tri * 3 + vertex];
}
- Texture texture(final int tri) {
+ /**
+ * The triangle's base texture (also read by the GI system when it
+ * attaches a lightmap: the composite resamples this texture into
+ * lightmap space).
+ */
+ public Texture texture(final int tri) {
return textures[tri];
}
diff --git a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/composite/LightmappedCompositeShape.java b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/composite/LightmappedCompositeShape.java
index b03e1e7..41b3c40 100644
--- a/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/composite/LightmappedCompositeShape.java
+++ b/src/main/java/eu/svjatoslav/aukio/e3d/renderer/raster/shapes/composite/LightmappedCompositeShape.java
@@ -146,15 +146,14 @@ public class LightmappedCompositeShape extends AbstractCompositeShape {
/**
* Emits one lightmapped triangle for the front side. When the source
- * polygon is two-sided (backface culling off), also emits a plain
- * solid triangle with reversed winding for the back side, and turns
- * culling on for both halves: a lightmap only knows its front side,
- * so without a real back surface the camera would see the front
- * side's light through the polygon (undersides glowing with the
- * top's light). The reversed solid renders with ordinary one-sided
- * direct lighting â correctly dark where the front is lit â and each
- * side's pixels are owned by exactly one surface, so nothing
- * z-fights.
+ * polygon is two-sided (backface culling off), also emits a SECOND
+ * lightmapped triangle with reversed winding for the back side â
+ * its own lightmap with the negated normal â and turns culling on
+ * for both halves: each side's pixels are owned by exactly one
+ * surface, so nothing z-fights, and both sides bake their own
+ * lighting (exteriors catch street lamps and moonlight instead of
+ * showing the interior's light through the wall or staying plain
+ * per-polygon).
*/
private void emitWrapped(final SolidPolygon triangle, final List out) {
final LightmappedTriangle front = wrapTriangle(triangle);
@@ -163,16 +162,25 @@ public class LightmappedCompositeShape extends AbstractCompositeShape {
return;
}
front.setBackfaceCulling(true);
- final SolidPolygon back = new SolidPolygon(
- triangle.vertices.get(0).coordinate,
- triangle.vertices.get(2).coordinate,
- triangle.vertices.get(1).coordinate,
- triangle.getColor());
- back.setShadingEnabled(triangle.isShadingEnabled());
- back.setBackfaceCulling(true);
- back.setMouseInteractionController(triangle.mouseInteractionController);
out.add(front);
- out.add(back);
+ out.add(wrapReversedTriangle(triangle));
+ }
+
+ /**
+ * Wraps the reversed-winding back side of a two-sided source into
+ * its own lightmapped triangle: the reversed winding makes
+ * {@link #wrapTriangle} compute the negated normal and build the
+ * back side's own lightmap parameterization.
+ */
+ private LightmappedTriangle wrapReversedTriangle(final SolidPolygon polygon) {
+ final SolidPolygon reversed = new SolidPolygon(
+ polygon.vertices.get(0).coordinate,
+ polygon.vertices.get(2).coordinate,
+ polygon.vertices.get(1).coordinate,
+ polygon.getColor());
+ reversed.setBackfaceCulling(true);
+ reversed.setMouseInteractionController(polygon.mouseInteractionController);
+ return wrapTriangle(reversed);
}
/**
diff --git a/src/test/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/AtmosphereTest.java b/src/test/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/AtmosphereTest.java
new file mode 100644
index 0000000..bcbd65a
--- /dev/null
+++ b/src/test/java/eu/svjatoslav/aukio/e3d/renderer/raster/lighting/AtmosphereTest.java
@@ -0,0 +1,91 @@
+package eu.svjatoslav.aukio.e3d.renderer.raster.lighting;
+
+import eu.svjatoslav.aukio.e3d.renderer.raster.Color;
+
+import org.junit.After;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Verifies the atmospheric haze factor math and the in-place color
+ * blend (bugreport-20261006-000922).
+ */
+public class AtmosphereTest {
+
+ @After
+ public void resetOverrides() {
+ Atmosphere.resetOverrides();
+ }
+
+ @Test
+ public void disabledByDefaultOverrideOff() {
+ Atmosphere.setEnabled(false);
+ assertEquals(0f, Atmosphere.factor(1_000_000), 0f);
+ }
+
+ @Test
+ public void factorCurve() {
+ Atmosphere.setEnabled(true);
+ Atmosphere.setScale(100_000);
+ // At the camera and behind it: no haze.
+ assertEquals(0f, Atmosphere.factor(0), 0f);
+ assertEquals(0f, Atmosphere.factor(-50), 0f);
+ // At one scale depth: 1 - 1/e â 0.6321.
+ assertEquals(0.6321f, Atmosphere.factor(100_000), 1e-3f);
+ // At five scale depths: nearly fully hazed.
+ assertEquals(0.9933f, Atmosphere.factor(500_000), 1e-3f);
+ // Monotonic increase.
+ assertTrue(Atmosphere.factor(10_000) < Atmosphere.factor(50_000));
+ assertTrue(Atmosphere.factor(50_000) < Atmosphere.factor(200_000));
+ // Sub-perceptible factors round to zero (bit-identical near path).
+ assertEquals(0f, Atmosphere.factor(1), 0f);
+ }
+
+ @Test
+ public void targetColorPrefersOverrideThenSky() {
+ final LightingManager lighting = new LightingManager();
+ lighting.setSkyColor(Color.hex("7AA3D8"));
+ // No override and no configured color: the scene sky wins.
+ final Color resolved = Atmosphere.targetColor(lighting);
+ assertEquals(0x7A, resolved.r);
+ assertEquals(0xA3, resolved.g);
+ assertEquals(0xD8, resolved.b);
+ // An explicit override wins over the sky.
+ Atmosphere.setColor(Color.hex("C0C0C0"));
+ assertEquals(0xC0, Atmosphere.targetColor(lighting).r);
+ }
+
+ @Test
+ public void applyHazeBlends() {
+ final Color target = new Color(200, 100, 50);
+ // f = 0: unchanged.
+ final Color c0 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c0, 0f, target);
+ assertEquals(40, c0.r);
+ assertEquals(80, c0.g);
+ assertEquals(120, c0.b);
+ // f = 1: fully the target.
+ final Color c1 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c1, 1f, target);
+ assertEquals(200, c1.r);
+ assertEquals(100, c1.g);
+ assertEquals(50, c1.b);
+ // f = 0.5: midpoint (rounded).
+ final Color c5 = new Color(40, 80, 120);
+ Atmosphere.applyHaze(c5, 0.5f, target);
+ assertEquals(120, c5.r);
+ assertEquals(90, c5.g);
+ assertEquals(85, c5.b);
+ }
+
+ @Test
+ public void enabledReadsOverride() {
+ Atmosphere.setEnabled(true);
+ assertTrue(Atmosphere.enabled());
+ Atmosphere.setEnabled(false);
+ assertFalse(Atmosphere.enabled());
+ }
+}