Compare commits

...
9 Commits
Author SHA1 Message Date
Jason Mitchell b2f597a73a SDL presenter fixes and frame pacer adjustments (#2025) 2026-08-16 17:59:33 -07:00
Jason Mitchell 553dec5b6d Mark tiles at transform time instead of using reflection (#2024) 2026-08-16 16:05:04 -07:00
Jason Mitchell bc8116006c Tracy 0.14 (#2019) 2026-08-15 19:09:36 -07:00
Jason Mitchell bf9492dffb Defer ticking on TEs we eagerly create until they get a description packet (#2018) 2026-08-15 17:04:50 -07:00
Jason Mitchell 69aed42b89 Sign Fix (#2016) 2026-08-15 14:32:50 -07:00
KAMKEELandJason Mitchell ffe54f61b9 Fixes World Lighting to Text Rendering so its not Fullbright (#1976)
* Fixes World Lighting to Text Rendering so its not Fullbright

* Carry lightmap state per text segment

* Text lighting: per-segment lightmap uniform, fix GL_RESCALE_NORMAL
* per segment uniform instead of stride increase
* Shade text based on GL light state
* fix u_NormalScale
* GL_LIGHT > 1 usage warnings (not currently handled)

---------

Co-authored-by: Jason Mitchell <[email protected]>
2026-08-14 21:34:58 -07:00
Jason Mitchell c86e1de9f6 TE and world access thread safety for rendering, and remesh on first TE update packet. (#2014) 2026-08-14 20:21:13 -07:00
brandyn 6af401c834 fix starminer rotation & optimize starminer rotateCorpseByGravity (#2005)
* fix starminer rotation & optimize starminer rotateCorpseByGravity

fixes #487

* remove Object[] allocation

* add shared helper,  fix NPEs, fallbacks
2026-08-13 11:27:43 -07:00
Jason Mitchell b17bb42c49 vsync adjustments: on/mailbox/off + windows input lag fix + glsl parsing optimizations (#2009) 2026-08-12 21:20:10 -07:00
131 changed files with 5482 additions and 1233 deletions

No files matched your search

+5 -3
View File
@@ -2,7 +2,8 @@
# Builds the libTracyClient shared library for the tracy-client module.
set -euo pipefail
TRACY_VERSION="${TRACY_VERSION:-v0.13.1}"
TRACY_VERSION="${TRACY_VERSION:-v0.14.0}"
TRACY_VERSION_BARE="${TRACY_VERSION#v}"
OUT_DIR="${OUT_DIR:-dist/tracy-natives}"
TRACY_REPO="https://github.com/wolfpld/tracy"
@@ -16,7 +17,7 @@ case "$(uname -m)" in
arm64|aarch64) PLAT_ARCH="arm64" ;;
*) PLAT_ARCH="x64" ;;
esac
RES_DIR="${RES_DIR:-$REPO_ROOT/tracy-client/src/main/resources/natives/tracy/$PLAT_OS-$PLAT_ARCH}"
RES_DIR="${RES_DIR:-$REPO_ROOT/tracy-client/src/main/resources/natives/tracy/$TRACY_VERSION_BARE/$PLAT_OS-$PLAT_ARCH}"
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
@@ -33,7 +34,8 @@ fi
BUILD_DIR="$WORK_DIR/build"
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-11.0}"
cmake -S "$SRC_DIR" -B "$BUILD_DIR" \
cmake -S "$REPO_ROOT/tracy-client/src/main/native" -B "$BUILD_DIR" \
-DTRACY_SRC_DIR="$SRC_DIR" \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=ON \
-DTRACY_STATIC=OFF \
+12 -23
View File
@@ -6,10 +6,6 @@ on:
- "tracy-v*"
workflow_dispatch:
inputs:
tracy-version:
description: Tracy git tag to build
required: false
default: v0.13.1
publish:
description: Publish angelica-tracy.jar to the GTNH maven
type: boolean
@@ -20,25 +16,25 @@ jobs:
build:
strategy:
matrix:
platform: [linux-x64, windows-x64, macos-x64, macos-arm64]
include:
- os: ubuntu-22.04
platform: linux-x64
- os: windows-2025
platform: windows-x64
- os: macos-15-intel
platform: macos-x64
- os: macos-15
platform: macos-arm64
- platform: linux-x64
os: ubuntu-22.04
- platform: windows-x64
os: windows-2025
- platform: macos-x64
os: macos-15-intel
- platform: macos-arm64
os: macos-15
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- name: Build libTracyClient
shell: bash
env:
RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }}
OUT_DIR: dist/tracy-natives
run: |
export TRACY_VERSION="${RAW_VERSION#tracy-}"
export TRACY_VERSION="v$(sed -nE 's/^tracy = "(.*)"$/\1/p' gradle/libs.versions.toml)"
bash .github/scripts/build-tracy-natives.sh
- uses: actions/upload-artifact@v4
with:
@@ -56,14 +52,6 @@ jobs:
distribution: temurin
java-version: 21
- uses: gradle/actions/setup-gradle@v4
- name: Check tracy version matches the version catalog
shell: bash
env:
RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }}
run: |
ver="${RAW_VERSION#tracy-}"
grep -q "^tracy = \"${ver#v}\"$" gradle/libs.versions.toml \
|| { echo "libs.versions.toml tracy does not match $ver" >&2; exit 1; }
- uses: actions/download-artifact@v5
with:
pattern: tracy-natives-*
@@ -71,8 +59,9 @@ jobs:
- name: Stage natives into tracy-client resources
shell: bash
run: |
version="$(sed -nE 's/^tracy = "(.*)"$/\1/p' gradle/libs.versions.toml)"
for d in staging/tracy-natives-*; do
dest="tracy-client/src/main/resources/natives/tracy/${d#staging/tracy-natives-}"
dest="tracy-client/src/main/resources/natives/tracy/$version/${d#staging/tracy-natives-}"
mkdir -p "$dest"
cp "$d"/* "$dest/"
done
+3
View File
@@ -40,5 +40,8 @@ addon.late.local.gradle
addon.late.local.gradle.kts
local/
tracy-client/src/main/resources/natives/
tracy-client/angelica/
dist/tracy-natives/
*.tracy
tracy-client/angelica/
+3 -2
View File
@@ -52,8 +52,8 @@ configurations.configureEach {
}
DependencyHandlerScope.of(dependencies).apply {
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev")
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.187:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.187:dev")
runtimeOnlyNonPublishable(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612"))
@@ -202,6 +202,7 @@ afterEvaluate {
glsmTestFixtures(testFixtures(project(":glsm")) as ModuleDependency) { isTransitive = false }
testCompileOnly(testFixtures(project(":glsm")))
testImplementation("mega:fluidlogged-mc1.7.10:0.1.2")
testRuntimeOnly(libs.fastutil)
testRuntimeOnly(libs.joml)
@@ -35,6 +35,8 @@ public final class SystemProperties {
public static final boolean SDL_ENCODER_ASSERTIONS_FATAL = ENCODER_ASSERTIONS == SdlAssertionMode.FATAL;
public static final boolean SDL_VERIFY_STATE_SYNC = Boolean.getBoolean("angelica.sdlgpu.verifyStateSync");
public static final boolean SDL_VERIFY_PER_FRAME_UNIFORM_BLOCK = Boolean.getBoolean("angelica.sdlgpu.verifyPerFrameUniformBlock");
public static final int SDL_FRAMES_IN_FLIGHT = Integer.getInteger("angelica.sdlgpu.framesInFlight", 2);
public static final boolean DISABLE_SDL_PRESENTER_THREAD = Boolean.getBoolean("angelica.sdlgpu.disablePresenterThread");
// Tracy
public static final boolean TRACY = Boolean.getBoolean("angelica.tracy");
@@ -56,7 +58,7 @@ public final class SystemProperties {
public static final boolean DEBUG_F3_DETAIL = Boolean.getBoolean("angelica.debug.f3Detail");
public static final boolean ENABLE_TEST_BLOCKS = Boolean.getBoolean("angelica.debug.testBlocks");
public static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.debug.dumpClass");
public static final boolean DUMP_SHADERS = Boolean.getBoolean("angelica.debug.dumpShaders") || isDeobf();
private static final boolean DUMP_SHADERS_PROP = Boolean.getBoolean("angelica.debug.dumpShaders");
public static final boolean REDIRECTOR_LOGSPAM = Boolean.getBoolean("angelica.debug.redirectorLogspam");
public static final boolean DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debug.displayLists");
public static final boolean LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.debug.displayLists.compilation");
@@ -66,8 +68,12 @@ public final class SystemProperties {
// Set by us, read by celeritas
public static final String KEY_CELERITAS_ENABLE_GL_DEBUG = "celeritas.enableGLDebug";
public static boolean dumpShaders() {
return DUMP_SHADERS_PROP || isDeobf();
}
public static Path shaderDumpDir(String phase) {
return DUMP_SHADERS ? Paths.get(SHADER_DUMP_ROOT, phase) : null;
return dumpShaders() ? Paths.get(SHADER_DUMP_ROOT, phase) : null;
}
public enum UnmappedGLMode {
@@ -116,7 +122,7 @@ public final class SystemProperties {
}
}
private static boolean isDeobf() {
public static boolean isDeobf() {
return Launch.blackboard != null && Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment"));
}
@@ -11,10 +11,10 @@ import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.ffp.VertexKey;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler;
@@ -3058,9 +3058,15 @@ public class GLStateManager {
return;
}
}
if (light >= VertexKey.FFP_LIGHT_COUNT && (warnedFfpLightMask & (1 << light)) == 0 && ShaderManager.getInstance().isEnabled()) {
warnedFfpLightMask |= (1 << light);
LOGGER.warn("GL_LIGHT{} enabled, but FFP shader emulation implements only GL_LIGHT0..{}", light, VertexKey.FFP_LIGHT_COUNT - 1, new Throwable("call site"));
}
ctx().lightStates[light].enable();
}
private static int warnedFfpLightMask = 0;
public static void enableColorMaterial() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
@@ -3383,14 +3389,11 @@ public class GLStateManager {
}
public static boolean isCurrent() {
if (BackendManager.RENDER_BACKEND == null) {
return Thread.currentThread() == MainThread;
}
return BackendManager.RENDER_BACKEND.isCurrent();
return RENDER_BACKEND.isCurrent();
}
public static void swapBuffers() throws LWJGLException {
if (BackendManager.RENDER_BACKEND != null && BackendManager.RENDER_BACKEND.handleSwapBuffers()) {
if (RENDER_BACKEND.handleSwapBuffers()) {
return;
}
Display.swapBuffers();
@@ -3406,7 +3409,14 @@ public class GLStateManager {
if (processMessages) Display.processMessages();
return;
}
if (!RENDER_BACKEND.wantsDisplayUpdateGateTiming()) {
Display.update(processMessages);
return;
}
final long start = System.nanoTime();
Display.update(processMessages);
final long end = System.nanoTime();
RENDER_BACKEND.recordFrameGate(end - start, end);
}
/**
@@ -5048,41 +5058,57 @@ public class GLStateManager {
}
public static void setVSyncEnabled(boolean enabled) {
setVSyncMode(RENDER_BACKEND.getPreferredVSyncMode(), enabled);
RENDER_BACKEND.setVSyncEnabled(enabled);
}
public static void setVSyncMode(VSyncMode preferred, boolean vsyncEnabled) {
RENDER_BACKEND.setVSyncMode(preferred, vsyncEnabled);
public static void setVSyncMode(VSyncMode mode) {
RENDER_BACKEND.setVSyncMode(mode);
}
public static void setVSyncPreference(VSyncMode mode) {
RENDER_BACKEND.setVSyncPreference(mode);
}
public static boolean supportsVSyncMode(VSyncMode mode) {
return RENDER_BACKEND.supportsVSyncMode(mode);
}
public static VSyncMode preferredTearFreeMode() {
return RENDER_BACKEND.preferredTearFreeMode();
}
public static String getRenderBackendName() {
return RENDER_BACKEND.getName();
}
public static VSyncMode getEffectiveVSyncMode() {
return RENDER_BACKEND.getEffectiveVSyncMode();
}
public static List<VSyncMode> getSelectableVSyncModes() {
return VSyncMode.selectable(RENDER_BACKEND::supportsVSyncMode);
}
public static int getMinRenderAhead() {
return RENDER_BACKEND.getMinRenderAhead();
}
public static int getMaxRenderAhead() {
return RENDER_BACKEND.getMaxRenderAhead();
}
public static int renderAheadLimit(int configured) {
return RenderBackend.clampRenderAhead(configured, RENDER_BACKEND.getMinRenderAhead(), RENDER_BACKEND.getMaxRenderAhead());
}
public static void applyRenderAheadLimit(int configured) {
RENDER_BACKEND.setRenderAheadLimit(renderAheadLimit(configured));
}
public static int getDisplayRefreshRateHz() {
return RENDER_BACKEND.getDisplayRefreshRateHz();
}
public static boolean gateAnchorsNextFrameStart() {
return RENDER_BACKEND.gateAnchorsNextFrameStart();
}
public static long lastFrameGateNanos() {
return RENDER_BACKEND.lastFrameGateNanos();
}
public static long lastFrameGateEndNanos() {
return RENDER_BACKEND.lastFrameGateEndNanos();
}
public static boolean hasSwapchainBackpressure() {
return RENDER_BACKEND.hasSwapchainBackpressure();
}
public static void pumpDisplayMessages() {
Display.processMessages();
}
public static int glGetError() {
if (!RENDER_BACKEND.hasContext()) return 0;
if (initConfig.isNoErrorChecks()) return 0;
@@ -2,8 +2,10 @@ package com.gtnewhorizons.angelica.glsm;
import org.antlr.v4.runtime.BufferedTokenStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.WritableToken;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.taumc.glsl.grammar.GLSLLexer;
@@ -88,6 +90,23 @@ public class GlslTransformUtils {
return source;
}
public static void restoreReservedWordsInTree(ParseTree tree) {
if (tree instanceof TerminalNode terminal) {
final Token token = terminal.getSymbol();
final String text = token.getText();
if (text != null && text.startsWith(RENAMED_PREFIX) && token instanceof WritableToken writable) {
final String rest = text.substring(RENAMED_PREFIX.length());
if (rest.startsWith("texture") || rest.startsWith("sample")) {
writable.setText(rest);
}
}
return;
}
for (int i = 0; i < tree.getChildCount(); i++) {
restoreReservedWordsInTree(tree.getChild(i));
}
}
public record QuietParse(GLSLParser.Translation_unitContext full, GLSLPreParser.Translation_unitContext pre) {}
public static GLSLParser.Translation_unitContext parseFullQuiet(String source) {
@@ -162,21 +181,32 @@ public class GlslTransformUtils {
public static String getFormattedShader(ParseTree tree, String header) {
final StringBuilder sb = new StringBuilder(header + "\n");
final String[] tabHolder = {""};
getFormattedShader(tree, sb, tabHolder);
getFormattedShader(tree, sb, tabHolder, false);
return sb.toString();
}
private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder) {
if (tree instanceof TerminalNode) {
public static String getFormattedShaderRebased(ParseTree tree, String header) {
final StringBuilder sb = new StringBuilder(header + "\n");
final String[] tabHolder = {""};
getFormattedShader(tree, sb, tabHolder, true);
return sb.toString();
}
private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder, boolean rebaseOffsets) {
if (tree instanceof TerminalNode terminal) {
final String text = tree.getText();
if (text.equals("<EOF>")) {
return;
}
if (text.equals("#")) {
stringBuilder.append("\n#");
rebaseAt(terminal, stringBuilder.length() - 1, text, rebaseOffsets);
return;
}
stringBuilder.append(text);
if (!text.equals("}")) {
rebaseAt(terminal, stringBuilder.length() - text.length(), text, rebaseOffsets);
}
if (text.equals("{")) {
stringBuilder.append(" \n\t");
tabHolder[0] = "\t";
@@ -186,6 +216,7 @@ public class GlslTransformUtils {
if (stringBuilder.length() >= 2) {
stringBuilder.deleteCharAt(stringBuilder.length() - 2);
}
rebaseAt(terminal, stringBuilder.length() - 1, text, rebaseOffsets);
tabHolder[0] = "";
stringBuilder.append(" \n");
} else {
@@ -193,8 +224,17 @@ public class GlslTransformUtils {
}
} else {
for (int i = 0; i < tree.getChildCount(); ++i) {
getFormattedShader(tree.getChild(i), stringBuilder, tabHolder);
getFormattedShader(tree.getChild(i), stringBuilder, tabHolder, rebaseOffsets);
}
}
}
private static void rebaseAt(TerminalNode terminal, int startIndex, String text, boolean rebaseOffsets) {
if (!rebaseOffsets) return;
if (terminal.getSymbol() instanceof CommonToken common) {
common.setText(text);
common.setStartIndex(startIndex);
common.setStopIndex(startIndex + text.length() - 1);
}
}
}
@@ -9,6 +9,7 @@ import com.gtnewhorizons.angelica.glsm.dsa.DSAEXT;
import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.mitchej123.lwjgl.LWJGLServiceProvider;
import lombok.Getter;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
@@ -111,6 +112,13 @@ public class RenderSystem {
BackendManager.init();
try {
// Force init on client thread
GLStateManager.LOGGER.info("Celeritas LWJGL service: {}", LWJGLServiceProvider.LWJGL.getClass().getName());
} catch (Throwable t) {
GLStateManager.LOGGER.debug("Could not resolve the celeritas LWJGL service: {}", t.toString());
}
supportsCompute = supportsCompute();
supportsTesselation = GLStateManager.capabilities.GL_ARB_tessellation_shader || GLStateManager.capabilities.OpenGL40;
@@ -115,10 +115,14 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend {
public int getMinGLSLVersion() {return 330;}
@Override
protected void setSwapInterval(boolean vsync) {Display.setVSyncEnabled(vsync);}
protected VSyncMode applyVSyncMode(VSyncMode preferred) {
final boolean enabled = preferred.tearFree();
Display.setVSyncEnabled(enabled);
return enabled ? VSyncMode.ON : VSyncMode.OFF;
}
@Override
public int getDisplayRefreshRateHz() {
protected int queryDisplayRefreshRateHz() {
final DisplayMode mode = Display.getDisplayMode();
if (mode != null && mode.getFrequency() > 0) return mode.getFrequency();
final DisplayMode desktop = Display.getDesktopDisplayMode();
@@ -12,6 +12,7 @@ import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
/**
* Abstract rendering backend.
@@ -62,47 +63,77 @@ public abstract class RenderBackend {
public abstract void flush();
public abstract void finish();
protected abstract void setSwapInterval(boolean vsync);
private VSyncMode preferredVSyncMode = VSyncMode.AUTO;
private VSyncMode effectiveVSyncMode = VSyncMode.ON;
private VSyncMode preferredTearFreeMode;
public final void setVSyncMode(VSyncMode preferred, boolean vsyncEnabled) {
preferredVSyncMode = preferred == null ? VSyncMode.AUTO : preferred;
effectiveVSyncMode = applyVSyncMode(preferredVSyncMode, vsyncEnabled);
public final void setVSyncEnabled(boolean enabled) {
setVSyncMode(enabled ? preferredTearFreeMode() : VSyncMode.OFF);
}
protected VSyncMode applyVSyncMode(VSyncMode preferred, boolean vsyncEnabled) {
final VSyncMode mode = preferred.resolve(vsyncEnabled).swapIntervalEquivalent();
setSwapInterval(mode.usesVSyncSwapInterval());
return mode;
public final void setVSyncMode(VSyncMode preferred) {
setVSyncPreference(preferred);
publishVSyncMode(applyVSyncMode(preferred));
}
public final void setVSyncPreference(VSyncMode preferred) {
if (preferred.tearFree()) preferredTearFreeMode = preferred;
}
public final VSyncMode preferredTearFreeMode() {
return resolveTearFreeMode(preferredTearFreeMode, this::supportsVSyncMode);
}
static VSyncMode resolveTearFreeMode(VSyncMode preferred, Predicate<VSyncMode> supported) {
if (preferred != null && preferred.tearFree() && supported.test(preferred)) return preferred;
return supported.test(VSyncMode.MAILBOX) ? VSyncMode.MAILBOX : VSyncMode.ON;
}
protected abstract VSyncMode applyVSyncMode(VSyncMode preferred);
public boolean supportsVSyncMode(VSyncMode mode) { return mode != VSyncMode.MAILBOX; }
public int getMinRenderAhead() { return 0; }
public int getMaxRenderAhead() { return 9; }
public void setRenderAheadLimit(int frames) {}
public static int clampRenderAhead(int value, int min, int max) {
if (value <= 0) return min <= 0 ? 0 : max;
return Math.min(Math.max(value, Math.max(min, 1)), max);
}
public final VSyncMode getPreferredVSyncMode() { return preferredVSyncMode; }
protected final void publishVSyncMode(VSyncMode mode) { effectiveVSyncMode = mode; }
public final VSyncMode getEffectiveVSyncMode() { return effectiveVSyncMode; }
public int getDisplayRefreshRateHz() { return 0; }
private static final long REFRESH_POLL_NANOS = 1_000_000_000L;
private long refreshPollNanos;
private int cachedRefreshHz;
public final int getDisplayRefreshRateHz() {
final long now = System.nanoTime();
if (refreshPollNanos == 0L || now - refreshPollNanos >= REFRESH_POLL_NANOS) {
refreshPollNanos = now;
cachedRefreshHz = queryDisplayRefreshRateHz();
}
return cachedRefreshHz;
}
protected int queryDisplayRefreshRateHz() { return 0; }
public static int refreshHzFrom(int numerator, int denominator, float fallbackHz) {
if (numerator > 0 && denominator > 0) return (numerator + denominator - 1) / denominator;
return fallbackHz > 0.0f ? (int) Math.ceil(fallbackHz) : 0;
}
public String getPresentDebugInfo() { return null; }
public boolean hasSwapchainBackpressure() { return false; }
private long frameGateNanos;
private long frameGateEndNanos;
public boolean gateAnchorsNextFrameStart() { return false; }
public boolean wantsDisplayUpdateGateTiming() { return true; }
public void recordFrameGate(long durationNanos, long endNanos) {
frameGateNanos = durationNanos;
frameGateEndNanos = endNanos;
}
public long lastFrameGateNanos() { return frameGateNanos; }
public long lastFrameGateEndNanos() { return frameGateEndNanos; }
public void onFrameBegin() {
if (GLStateManager.takeStateSeedPending()) {
@@ -1,54 +1,11 @@
package com.gtnewhorizons.angelica.glsm.backend;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public enum VSyncMode {
AUTO,
OFF,
ON,
MAILBOX,
OFF;
private static final List<VSyncMode> OFF_ORDER = List.of(OFF, MAILBOX, ON);
private static final List<VSyncMode> MAILBOX_ORDER = List.of(MAILBOX, ON);
private static final List<VSyncMode> ON_ORDER = List.of(ON);
private static final List<VSyncMode> DISPLAY_ORDER = List.of(OFF, ON, MAILBOX);
public boolean blocksOnVBlank() {
return this == ON;
}
public boolean usesVSyncSwapInterval() {
return this == ON || this == MAILBOX;
}
public VSyncMode swapIntervalEquivalent() {
return this == MAILBOX ? ON : this;
}
public VSyncMode resolve(boolean vsyncEnabled) {
return this != AUTO ? this : (vsyncEnabled ? ON : OFF);
}
public List<VSyncMode> fallbackOrder() {
return switch (this) {
case OFF -> OFF_ORDER;
case MAILBOX -> MAILBOX_ORDER;
default -> ON_ORDER;
};
}
MAILBOX;
public boolean tearFree() {
return this != OFF;
}
public static List<VSyncMode> selectable(Predicate<VSyncMode> supported) {
final List<VSyncMode> modes = new ArrayList<>(DISPLAY_ORDER.size());
for (VSyncMode mode : DISPLAY_ORDER) {
if (supported.test(mode)) modes.add(mode);
}
return modes;
}
}
@@ -0,0 +1,83 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.LightState;
import com.gtnewhorizons.angelica.glsm.states.MaterialState;
import org.joml.Matrix3f;
import org.joml.Vector3f;
import org.joml.Vector4f;
public final class FFPVertexLighting {
private static final Vector3f scratchNormal = new Vector3f();
private static final Vector3f scratchLightVec = new Vector3f();
private static final Vector4f scratchEyePos = new Vector4f();
private static final Matrix3f scratchNormalMat = new Matrix3f();
private static final Vector3f scratchVec = new Vector3f();
private FFPVertexLighting() {}
public static boolean modulatesVertexColor(Vector3f destFactor) {
destFactor.set(1.0f);
if (!GLStateManager.getLightingState().isEnabled()) return false;
if (!GLStateManager.getColorMaterial().isEnabled()) return false;
if (VertexKey.encodeColorMaterialMode(GLStateManager.getColorMaterialParameter().getValue()) != VertexKey.CM_AMBIENT_AND_DIFFUSE) return false;
final MaterialState material = GLStateManager.getFrontMaterial();
if (material.emission.x != 0.0f || material.emission.y != 0.0f || material.emission.z != 0.0f)
return false;
final boolean materialHasSpecular = material.shininess > 0.0f && (material.specular.x != 0.0f || material.specular.y != 0.0f || material.specular.z != 0.0f);
final Vector4f lightModelAmbient = GLStateManager.getLightModel().ambient;
float r = lightModelAmbient.x;
float g = lightModelAmbient.y;
float b = lightModelAmbient.z;
final var lightEnables = GLStateManager.getLightStates();
final var lightData = GLStateManager.getLightDataStates();
boolean normalReady = false;
for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) {
if (!lightEnables[i].isEnabled()) continue;
final LightState light = lightData[i];
if (materialHasSpecular && (light.specular.x != 0.0f || light.specular.y != 0.0f || light.specular.z != 0.0f))
return false;
if (!normalReady) {
transformCurrentNormal();
normalReady = true;
}
final float nDotVP = Math.max(scratchNormal.dot(lightDirection(light)), 0.0f);
r += light.ambient.x + nDotVP * light.diffuse.x;
g += light.ambient.y + nDotVP * light.diffuse.y;
b += light.ambient.z + nDotVP * light.diffuse.z;
}
if (r == 1.0f && g == 1.0f && b == 1.0f) return false;
if (!Float.isFinite(r + g + b)) return false;
destFactor.set(r, g, b);
return true;
}
private static void transformCurrentNormal() {
GLStateManager.getModelViewMatrix().normal(scratchNormalMat);
scratchNormal.set(ShaderManager.getCurrentNormal());
scratchNormalMat.transform(scratchNormal);
if (GLStateManager.getNormalizeState().isEnabled()) {
scratchNormal.normalize();
} else if (GLStateManager.getRescaleNormalState().isEnabled()) {
scratchNormal.mul(Uniforms.rescaleFactor(scratchNormalMat, scratchVec));
}
}
private static Vector3f lightDirection(LightState light) {
if (light.position.w == 0.0f) {
scratchLightVec.set(light.position.x, light.position.y, light.position.z);
} else {
scratchEyePos.set(0.0f, 0.0f, 0.0f, 1.0f).mul(GLStateManager.getModelViewMatrix());
scratchLightVec.set(light.position.x - scratchEyePos.x, light.position.y - scratchEyePos.y, light.position.z - scratchEyePos.z);
}
return scratchLightVec.normalize();
}
}
@@ -232,8 +232,12 @@ public class Uniforms {
private void stageNormalMatrix() {
GLStateManager.getModelViewMatrix().normal(normalMatrix);
putMat3(FFPUniformBlock.NORMAL_MATRIX, normalMatrix);
final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length();
putFloat(FFPUniformBlock.NORMAL_SCALE, scale);
putFloat(FFPUniformBlock.NORMAL_SCALE, rescaleFactor(normalMatrix, tempVec3));
}
static float rescaleFactor(Matrix3f normalMatrix, Vector3f scratch) {
final float f = normalMatrix.getColumn(2, scratch).lengthSquared();
return f > 1.0e-12f ? 1.0f / (float) Math.sqrt(f) : 1.0f;
}
private void stageTextureMatrices() {
@@ -20,38 +20,36 @@ public final class VertexKey {
public static final int MAX_UNITS = 4;
public static final int FFP_LIGHT_COUNT = 2;
private final long packed;
private static final int BIT_LIGHTING = 0;
private static final int BIT_LIGHT0 = 1;
private static final int BIT_LIGHT1 = 2;
private static final int BIT_LIGHT0_DIR = 3;
private static final int BIT_LIGHT1_DIR = 4;
private static final int BIT_COLOR_MATERIAL = 5;
private static final int BIT_SEPARATE_SPECULAR = 6;
private static final int BIT_FOG = 7;
private static final int BIT_FOG_DIST_MODE = 8; // 2 bits: 8-9
private static final int BIT_NORMALIZE = 10;
private static final int BIT_RESCALE_NORMAL = 11;
// Per-unit texcoord enable: bits 12-15 (unit 0..3). Unit 1 doubles as the lightmap flag.
private static final int BIT_UNIT_TEX_BASE = 12;
private static final int BIT_HAS_VERTEX_COLOR = 16;
private static final int BIT_HAS_VERTEX_NORMAL = 17;
private static final int BIT_HAS_VERTEX_TEX = 18;
private static final int BIT_HAS_VERTEX_LIGHTMAP = 19;
private static final int BIT_COLOR_MAT_MODE = 20; // 3 bits: 20-22
// TexGen modes (unit 0 only, for now): 3 bits each (0=NONE, 1=OBJ_LINEAR, 2=EYE_LINEAR).
private static final int BIT_TEXGEN_S = 23; // 3 bits: 23-25
private static final int BIT_TEXGEN_T = 26; // 3 bits: 26-28
private static final int BIT_TEXGEN_R = 29; // 3 bits: 29-31
private static final int BIT_TEXGEN_Q = 32; // 3 bits: 32-34
private static final int BIT_CLIP_PLANES = 35;
private static final int BIT_WIDE_LINE = 36;
// Per-unit texmat enable: bits 37-40 (unit 0..3). Unit 1 is the lightmap matrix.
private static final int BIT_UNIT_TEXMAT_BASE = 37;
private static final int BIT_UNIT23_UV_FROM_UNIT0 = 41;
private static final int BIT_LINE_STIPPLE = 42;
private static final int BIT_INSTANCED = 44;
private static final int BIT_LIGHT_BASE = BIT_LIGHTING + 1;
private static final int BIT_LIGHT_DIR_BASE = BIT_LIGHT_BASE + FFP_LIGHT_COUNT;
private static final int BIT_COLOR_MATERIAL = BIT_LIGHT_DIR_BASE + FFP_LIGHT_COUNT;
private static final int BIT_SEPARATE_SPECULAR = BIT_COLOR_MATERIAL + 1;
private static final int BIT_FOG = BIT_SEPARATE_SPECULAR + 1;
private static final int BIT_FOG_DIST_MODE = BIT_FOG + 1;
private static final int BIT_NORMALIZE = BIT_FOG_DIST_MODE + 2;
private static final int BIT_RESCALE_NORMAL = BIT_NORMALIZE + 1;
private static final int BIT_UNIT_TEX_BASE = BIT_RESCALE_NORMAL + 1;
private static final int BIT_HAS_VERTEX_COLOR = BIT_UNIT_TEX_BASE + MAX_UNITS;
private static final int BIT_HAS_VERTEX_NORMAL = BIT_HAS_VERTEX_COLOR + 1;
private static final int BIT_HAS_VERTEX_TEX = BIT_HAS_VERTEX_NORMAL + 1;
private static final int BIT_HAS_VERTEX_LIGHTMAP = BIT_HAS_VERTEX_TEX + 1;
private static final int BIT_COLOR_MAT_MODE = BIT_HAS_VERTEX_LIGHTMAP + 1;
// TexGen modes are unit 0 only, for now.
private static final int BIT_TEXGEN_S = BIT_COLOR_MAT_MODE + 3;
private static final int BIT_TEXGEN_T = BIT_TEXGEN_S + 3;
private static final int BIT_TEXGEN_R = BIT_TEXGEN_T + 3;
private static final int BIT_TEXGEN_Q = BIT_TEXGEN_R + 3;
private static final int BIT_CLIP_PLANES = BIT_TEXGEN_Q + 3;
private static final int BIT_WIDE_LINE = BIT_CLIP_PLANES + 1;
private static final int BIT_UNIT_TEXMAT_BASE = BIT_WIDE_LINE + 1;
private static final int BIT_UNIT23_UV_FROM_UNIT0 = BIT_UNIT_TEXMAT_BASE + MAX_UNITS;
private static final int BIT_LINE_STIPPLE = BIT_UNIT23_UV_FROM_UNIT0 + 1;
private static final int BIT_INSTANCED = BIT_LINE_STIPPLE + 1;
public static final int TG_NONE = 0;
public static final int TG_OBJ_LINEAR = 1;
@@ -70,10 +68,8 @@ public final class VertexKey {
public long pack() { return packed; }
public boolean lightingEnabled() { return bit(BIT_LIGHTING); }
public boolean light0Enabled() { return bit(BIT_LIGHT0); }
public boolean light1Enabled() { return bit(BIT_LIGHT1); }
public boolean light0Directional() { return bit(BIT_LIGHT0_DIR); }
public boolean light1Directional() { return bit(BIT_LIGHT1_DIR); }
public boolean lightEnabled(int light) { return bit(BIT_LIGHT_BASE + light); }
public boolean lightDirectional(int light) { return bit(BIT_LIGHT_DIR_BASE + light); }
public boolean colorMaterialEnabled() { return bit(BIT_COLOR_MATERIAL); }
public boolean separateSpecular() { return bit(BIT_SEPARATE_SPECULAR); }
public boolean fogEnabled() { return bit(BIT_FOG); }
@@ -136,17 +132,12 @@ public final class VertexKey {
if (lighting) {
bits |= (1L << BIT_LIGHTING);
if (GLStateManager.getLightStates()[0].isEnabled()) {
bits |= (1L << BIT_LIGHT0);
for (int i = 0; i < FFP_LIGHT_COUNT; i++) {
if (!GLStateManager.getLightStates()[i].isEnabled()) continue;
bits |= (1L << (BIT_LIGHT_BASE + i));
// position.w == 0 means directional
if (GLStateManager.getLightDataStates()[0].position.w == 0.0f) {
bits |= (1L << BIT_LIGHT0_DIR);
}
}
if (GLStateManager.getLightStates()[1].isEnabled()) {
bits |= (1L << BIT_LIGHT1);
if (GLStateManager.getLightDataStates()[1].position.w == 0.0f) {
bits |= (1L << BIT_LIGHT1_DIR);
if (GLStateManager.getLightDataStates()[i].position.w == 0.0f) {
bits |= (1L << (BIT_LIGHT_DIR_BASE + i));
}
}
@@ -265,7 +256,7 @@ public final class VertexKey {
@Override
public String toString() {
return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%b]",
packed, lightingEnabled(), light0Enabled(), light1Enabled(),
packed, lightingEnabled(), lightEnabled(0), lightEnabled(1),
colorMaterialEnabled(), fogEnabled(),
unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0,
unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0,
@@ -182,11 +182,10 @@ public final class VertexShaderGenerator {
}
// Per-light accumulation
if (key.light0Enabled()) {
emitLightContribution(sb, key, 0);
}
if (key.light1Enabled()) {
emitLightContribution(sb, key, 1);
for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) {
if (key.lightEnabled(i)) {
emitLightContribution(sb, key, i);
}
}
sb.append(" v_Color = vec4(clamp(color0, 0.0, 1.0), outAlpha);\n");
@@ -198,7 +197,7 @@ public final class VertexShaderGenerator {
private static void emitLightContribution(StringBuilder sb, VertexKey key, int lightIndex) {
final String li = String.valueOf(lightIndex);
final boolean directional = (lightIndex == 0) ? key.light0Directional() : key.light1Directional();
final boolean directional = key.lightDirectional(lightIndex);
final String posUniform = "u_Light" + li + "Position";
sb.append(" { // Light ").append(li).append('\n');
@@ -1,8 +1,13 @@
package com.gtnewhorizons.angelica.glsm.hooks;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import org.taumc.glsl.grammar.GLSLParser;
@FunctionalInterface
public interface ShaderTransformPostProcessor {
void onTransformed(String transformedSource, ShaderType shaderType);
default void onTransformed(String transformedSource, GLSLParser.Translation_unitContext bodyTree, int headerLen, ShaderType shaderType) {
onTransformed(transformedSource, shaderType);
}
}
@@ -0,0 +1,92 @@
package com.gtnewhorizons.angelica.glsm.profiling;
import java.util.ArrayList;
import java.util.List;
public final class SectionRegistry {
public interface Emitter {
long enter(int category, String text);
void leave(long nativeId);
void setup(int category, String name);
boolean isConnected();
}
private static final class Category {
final int id;
final String name;
Category(int id, String name) {
this.id = id;
this.name = name;
}
}
private static final class Section {
final long token;
final int category;
final String text;
long nativeId;
Section(long token, int category, String text, long nativeId) {
this.token = token;
this.category = category;
this.text = text;
this.nativeId = nativeId;
}
}
private final Emitter emitter;
private final List<Category> categories = new ArrayList<>();
private final List<Section> open = new ArrayList<>();
private long nextToken;
private boolean connected;
public SectionRegistry(Emitter emitter) {
this.emitter = emitter;
}
public synchronized void registerCategory(int category, String name) {
categories.add(new Category(category, name));
}
public synchronized long enter(int category, String text) {
syncConnection();
final long token = ++nextToken;
open.add(new Section(token, category, text, emitter.enter(category, text)));
return token;
}
public synchronized void leave(long token) {
for (int i = 0; i < open.size(); i++) {
final Section section = open.get(i);
if (section.token == token) {
open.remove(i);
if (section.nativeId != 0L) emitter.leave(section.nativeId);
return;
}
}
}
public synchronized void poll() {
syncConnection();
}
private void syncConnection() {
final boolean now = emitter.isConnected();
if (now == connected) return;
connected = now;
if (now) replay();
}
private void replay() {
for (int i = 0; i < categories.size(); i++) {
final Category category = categories.get(i);
emitter.setup(category.id, category.name);
}
for (int i = 0; i < open.size(); i++) {
final Section section = open.get(i);
section.nativeId = emitter.enter(section.category, section.text);
}
}
}
@@ -44,6 +44,18 @@ public final class Tracy {
public static final int COLOR_IRIS = 0x9E862E; // gold
public static final int COLOR_FFP = 0x7A4E9E; // purple
public static final int SECTION_WORLD = 1;
public static final int SECTION_SHADERS = 2;
public static final int SECTION_BENCHMARK = 3;
public static final int SECTION_UI = 4;
private static final SectionRegistry SECTIONS = new SectionRegistry(new SectionRegistry.Emitter() {
@Override public long enter(int category, String text) { return BACKEND.sectionEnter(category, text); }
@Override public void leave(long nativeId) { BACKEND.sectionLeave(nativeId); }
@Override public void setup(int category, String name) { BACKEND.sectionSetup(category, name); }
@Override public boolean isConnected() { return BACKEND.isConnected(); }
});
private static final ThreadLocal<ZoneStack> STACK = new ThreadLocal<>() {
@Override
protected ZoneStack initialValue() {
@@ -62,6 +74,10 @@ public final class Tracy {
FINE_ZONES = ENABLED && SystemProperties.TRACY_FINE_ZONES;
if (ENABLED) {
Runtime.getRuntime().addShutdownHook(new Thread(Tracy::shutdown, "Tracy-Shutdown"));
SECTIONS.registerCategory(SECTION_WORLD, "World");
SECTIONS.registerCategory(SECTION_SHADERS, "Shaders");
SECTIONS.registerCategory(SECTION_BENCHMARK, "Benchmark");
SECTIONS.registerCategory(SECTION_UI, "UI");
LOGGER.info("Tracy profiling enabled");
}
}
@@ -95,6 +111,7 @@ public final class Tracy {
LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but no TracyBackend service present");
return null;
}
if (!implementsCurrentAbi(found)) return null;
final TracyBackend backend = found;
final CountDownLatch done = new CountDownLatch(1);
final AtomicReference<Boolean> result = new AtomicReference<>();
@@ -120,10 +137,28 @@ public final class Tracy {
return backend;
}
private static final String ABI_SENTINEL = "sectionEnter";
private static boolean implementsCurrentAbi(TracyBackend backend) {
try {
backend.getClass().getMethod(ABI_SENTINEL, int.class, String.class);
return true;
} catch (NoSuchMethodException e) {
LOGGER.warn("Tracy backend {} was built against an older TracyBackend interface; profiling disabled", backend.getClass().getName());
return false;
}
}
private record InitRunner(TracyBackend backend, CountDownLatch done, AtomicReference<Boolean> result) implements Runnable {
@Override
public void run() {
final boolean ok = backend.init();
boolean ok;
try {
ok = backend.init();
} catch (LinkageError e) {
LOGGER.warn("Tracy backend {} failed to link; profiling disabled: {}", backend.getClass().getName(), e);
ok = false;
}
if (!result.compareAndSet(null, ok) && ok) {
backend.shutdown();
}
@@ -168,7 +203,7 @@ public final class Tracy {
final String name = stack.poppedName();
if (name != null && WARNED_LEAKS.add(name)) {
LOGGER.warn("Tracy: unbalanced profiler section '{}' left open (leaked by its caller); closed at next root", name);
BACKEND.message("unbalanced profiler section '" + name + "' closed at root");
BACKEND.message("unbalanced profiler section '" + name + "' closed at root", TracyBackend.SEVERITY_WARNING);
}
}
}
@@ -274,6 +309,7 @@ public final class Tracy {
threadNameRefreshed = true;
BACKEND.setCurrentThreadName(Thread.currentThread().getName());
}
SECTIONS.poll();
BACKEND.frameMark();
}
@@ -330,8 +366,22 @@ public final class Tracy {
}
public static void message(String text) {
message(text, TracyBackend.SEVERITY_INFO);
}
public static void message(String text, int severity) {
if (!ENABLED || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return;
BACKEND.message(text);
BACKEND.message(text, severity);
}
public static long sectionEnter(int category, String text) {
if (!ENABLED || SHUTTING_DOWN) return 0L;
return SECTIONS.enter(category, text);
}
public static void sectionLeave(long token) {
if (token == 0L || !ENABLED || SHUTTING_DOWN) return;
SECTIONS.leave(token);
}
public static boolean isConnected() {
@@ -5,6 +5,13 @@ public interface TracyBackend {
int PLOT_FORMAT_MEMORY = 1;
int PLOT_FORMAT_PERCENTAGE = 2;
int SEVERITY_TRACE = 0;
int SEVERITY_DEBUG = 1;
int SEVERITY_INFO = 2;
int SEVERITY_WARNING = 3;
int SEVERITY_ERROR = 4;
int SEVERITY_FATAL = 5;
boolean init();
long internSrcLoc(String name, int color);
@@ -24,7 +31,14 @@ public interface TracyBackend {
void plotInt(long namePtr, long value);
void plot(long namePtr, double value);
void message(String text);
void message(String text, int severity);
default void message(String text) { message(text, SEVERITY_INFO); }
long sectionEnter(int category, String text);
void sectionLeave(long id);
void sectionSetup(int category, String name);
void setCurrentThreadName(String name);
boolean isConnected();
void shutdown();
@@ -2,7 +2,7 @@ package com.gtnewhorizons.angelica.glsm.profiling;
public final class ZoneStack {
public static final long EMPTY = -1L;
static final int MAX_DEPTH = 512;
public static final int MAX_DEPTH = 512;
private long[] stack = new long[64];
private boolean[] gpu = new boolean[64];
@@ -162,6 +162,7 @@ public class GLSMRedirector {
private static final String EXTGpuShader4 = "org/lwjgl/opengl/EXTGpuShader4";
private static final String EXTGPUShader4 = "org/lwjgl/opengl/EXTGPUShader4";
private static final String ARBTimerQuery = "org/lwjgl/opengl/ARBTimerQuery";
private static final String EXTTimerQuery = "org/lwjgl/opengl/EXTTimerQuery";
// Redirect VAO related calls from NHLib
private static final String UniversalVAO = "com/gtnewhorizon/gtnhlib/client/opengl/UniversalVAO";
@@ -632,6 +633,10 @@ public class GLSMRedirector {
.add("glQueryCounter")
.add("glGetQueryObjectui64")
);
methodRedirects.put(EXTTimerQuery, RedirectMap.newMap()
.add("glGetQueryObjectuEXT", "glGetQueryObjectui64")
.add("glGetQueryObjectui64EXT", "glGetQueryObjectui64")
);
glDescRedirects.put("org/lwjgl/opengl/GL32C glFenceSync(II)J", "glFenceSync");
glDescRedirects.put("org/lwjgl/opengl/GL32C glClientWaitSync(JIJ)I", "glClientWaitSync");
@@ -100,7 +100,7 @@ public final class GlslVulkanPreprocess {
return out;
}
public record Metadata(Set<String> boolUniforms, Set<String> explicitVsInputs) {}
public record Metadata(Set<String> boolUniforms, Set<String> explicitVsInputs, boolean needsSamplerless) {}
public static Metadata collectEdits(String source, GLSLParser.Translation_unitContext root, int glShaderType, String debugName, boolean separateReadOnlyImages, List<Edit> edits) {
final boolean isVertex = glShaderType == GL20.GL_VERTEX_SHADER;
@@ -216,7 +216,7 @@ public final class GlslVulkanPreprocess {
}
}, root);
if (needsSamplerless[0]) {
if (needsSamplerless[0] && source != null) {
final int at = versionDirectiveEnd(source);
if (at >= 0) edits.add(new Edit(at, at - 1, "\n" + SAMPLERLESS_EXTENSION));
}
@@ -234,7 +234,7 @@ public final class GlslVulkanPreprocess {
}
}
return new Metadata(bools, explicitInputs);
return new Metadata(bools, explicitInputs, needsSamplerless[0]);
}
public static void clearCache() {
@@ -0,0 +1,67 @@
package com.gtnewhorizons.angelica.glsm;
import org.junit.jupiter.api.Test;
import org.taumc.glsl.grammar.GLSLParser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ReservedWordRestoreTest {
private static void assertTreeRestoreMatchesStringRestore(String label, String renamedSource) {
final GLSLParser.Translation_unitContext treeA = GlslTransformUtils.parseFullQuiet(renamedSource);
final String legacy = GlslTransformUtils.restoreReservedWords(GlslTransformUtils.getFormattedShader(treeA, ""));
final GLSLParser.Translation_unitContext treeB = GlslTransformUtils.parseFullQuiet(renamedSource);
GlslTransformUtils.restoreReservedWordsInTree(treeB);
final String inTree = GlslTransformUtils.getFormattedShader(treeB, "");
assertEquals(legacy, inTree, "in-tree restore diverged from string restore for " + label);
}
@Test
void allThreeRenamesRestoreIdentically() {
final String src = "float angelica_renamed_sample = 1.0;\n"
+ "uniform sampler2D angelica_renamed_sampler;\n"
+ "vec4 angelica_renamed_texture = vec4(0.0);\n"
+ "void main() {\n"
+ " vec4 c = angelica_renamed_texture + vec4(angelica_renamed_sample);\n"
+ "}\n";
assertTreeRestoreMatchesStringRestore("all-three", src);
}
@Test
void renamedNewStaysRenamed() {
final String src = "float angelica_renamed_new = 2.0;\n"
+ "void main() { float x = angelica_renamed_new; }\n";
assertTreeRestoreMatchesStringRestore("new-identifier", src);
final GLSLParser.Translation_unitContext tree = GlslTransformUtils.parseFullQuiet(src);
GlslTransformUtils.restoreReservedWordsInTree(tree);
final String out = GlslTransformUtils.getFormattedShader(tree, "");
assertTrue(out.contains("angelica_renamed_new"), "new is reserved in every GLSL version and must stay renamed");
}
@Test
void renamedTextureFunctionCallRestores() {
final String src = "uniform sampler2D tex;\n"
+ "void main() {\n"
+ " vec4 c = angelica_renamed_texture2D(tex, vec2(0.5));\n"
+ "}\n";
assertTreeRestoreMatchesStringRestore("texture2D-call", src);
final GLSLParser.Translation_unitContext tree = GlslTransformUtils.parseFullQuiet(src);
GlslTransformUtils.restoreReservedWordsInTree(tree);
final String out = GlslTransformUtils.getFormattedShader(tree, "");
assertTrue(out.contains("texture2D"), "suffixed rename must strip only the prefix");
assertFalse(out.contains("angelica_renamed_"), "no renamed remnants expected");
}
@Test
void untouchedSourcePrintsIdentically() {
final String src = "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(1.0); }\n";
assertTreeRestoreMatchesStringRestore("no-renames", src);
}
}
@@ -2,7 +2,7 @@ package com.gtnewhorizons.angelica.glsm.backend;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Predicate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -11,63 +11,36 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class BackendPolicyTest {
@Test
void autoFollowsTheVsyncToggle() {
assertEquals(VSyncMode.ON, VSyncMode.AUTO.resolve(true));
assertEquals(VSyncMode.OFF, VSyncMode.AUTO.resolve(false));
}
@Test
void anExplicitModeIgnoresTheVsyncToggle() {
for (VSyncMode mode : new VSyncMode[]{ VSyncMode.ON, VSyncMode.MAILBOX, VSyncMode.OFF }) {
assertEquals(mode, mode.resolve(true));
assertEquals(mode, mode.resolve(false));
}
}
@Test
void onlyOnBlocks() {
assertTrue(VSyncMode.ON.blocksOnVBlank());
assertFalse(VSyncMode.MAILBOX.blocksOnVBlank());
assertFalse(VSyncMode.OFF.blocksOnVBlank());
}
@Test
void mailboxRidesOnSwapIntervalOne() {
assertTrue(VSyncMode.ON.usesVSyncSwapInterval());
assertTrue(VSyncMode.MAILBOX.usesVSyncSwapInterval());
assertFalse(VSyncMode.OFF.usesVSyncSwapInterval());
}
@Test
void swapIntervalBackendsReportWhatTheyActuallyGet() {
assertEquals(VSyncMode.ON, VSyncMode.MAILBOX.swapIntervalEquivalent());
assertEquals(VSyncMode.ON, VSyncMode.ON.swapIntervalEquivalent());
assertEquals(VSyncMode.OFF, VSyncMode.OFF.swapIntervalEquivalent());
}
@Test
void fallbackNeverWidensTearing() {
assertEquals(List.of(VSyncMode.ON), VSyncMode.ON.fallbackOrder());
assertEquals(List.of(VSyncMode.MAILBOX, VSyncMode.ON), VSyncMode.MAILBOX.fallbackOrder());
assertEquals(List.of(VSyncMode.OFF, VSyncMode.MAILBOX, VSyncMode.ON), VSyncMode.OFF.fallbackOrder());
}
@Test
void onlyOffCanTear() {
void onlyImmediateCanTear() {
assertTrue(VSyncMode.ON.tearFree());
assertTrue(VSyncMode.MAILBOX.tearFree());
assertFalse(VSyncMode.OFF.tearFree());
}
private static final Predicate<VSyncMode> NO_MAILBOX = mode -> mode != VSyncMode.MAILBOX;
private static final Predicate<VSyncMode> EVERYTHING = mode -> true;
@Test
void onlyBackendSupportedModesAreSelectable() {
assertEquals(List.of(VSyncMode.OFF, VSyncMode.ON), VSyncMode.selectable(m -> m != VSyncMode.MAILBOX));
assertEquals(List.of(VSyncMode.OFF, VSyncMode.ON, VSyncMode.MAILBOX), VSyncMode.selectable(m -> true));
void mailboxIsTakenWhenTheBackendOffersIt() {
assertEquals(VSyncMode.MAILBOX, RenderBackend.resolveTearFreeMode(null, EVERYTHING));
}
@Test
void autoIsNeverSelectable() {
assertFalse(VSyncMode.selectable(m -> true).contains(VSyncMode.AUTO));
void vsyncIsTheFallbackWhenMailboxIsUnsupported() {
assertEquals(VSyncMode.ON, RenderBackend.resolveTearFreeMode(null, NO_MAILBOX));
assertEquals(VSyncMode.ON, RenderBackend.resolveTearFreeMode(VSyncMode.MAILBOX, NO_MAILBOX));
}
@Test
void anExplicitSupportedPreferenceWins() {
assertEquals(VSyncMode.ON, RenderBackend.resolveTearFreeMode(VSyncMode.ON, EVERYTHING));
assertEquals(VSyncMode.MAILBOX, RenderBackend.resolveTearFreeMode(VSyncMode.MAILBOX, EVERYTHING));
}
@Test
void offIsNeverATearFreePreference() {
assertEquals(VSyncMode.MAILBOX, RenderBackend.resolveTearFreeMode(VSyncMode.OFF, EVERYTHING));
assertEquals(VSyncMode.ON, RenderBackend.resolveTearFreeMode(VSyncMode.OFF, NO_MAILBOX));
}
@Test
@@ -89,32 +62,4 @@ class BackendPolicyTest {
assertEquals(0, RenderBackend.refreshHzFrom(-1, -1, -1.0f));
assertEquals(0, RenderBackend.refreshHzFrom(144, 0, 0.0f));
}
@Test
void glRenderAheadKeepsZeroAsOff() {
assertEquals(0, RenderBackend.clampRenderAhead(0, 0, 9));
assertEquals(0, RenderBackend.clampRenderAhead(-1, 0, 9));
}
@Test
void glRenderAheadClampsToItsRange() {
assertEquals(1, RenderBackend.clampRenderAhead(1, 0, 9));
assertEquals(3, RenderBackend.clampRenderAhead(3, 0, 9));
assertEquals(9, RenderBackend.clampRenderAhead(9, 0, 9));
assertEquals(9, RenderBackend.clampRenderAhead(20, 0, 9));
}
@Test
void sdlRenderAheadHasNoOffSwitch() {
assertEquals(3, RenderBackend.clampRenderAhead(0, 1, 3));
assertEquals(3, RenderBackend.clampRenderAhead(-1, 1, 3));
}
@Test
void sdlRenderAheadClampsToItsRange() {
assertEquals(1, RenderBackend.clampRenderAhead(1, 1, 3));
assertEquals(2, RenderBackend.clampRenderAhead(2, 1, 3));
assertEquals(3, RenderBackend.clampRenderAhead(3, 1, 3));
assertEquals(3, RenderBackend.clampRenderAhead(6, 1, 3));
}
}
@@ -0,0 +1,241 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Vector3f;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.COLOR_BIT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@GLCoreTest
class FFPVertexLightingGLTest {
private static final int POSITION_LOC = VertexFormatElement.Usage.POSITION.getAttributeLocation();
private static final int COLOR_LOC = VertexFormatElement.Usage.COLOR.getAttributeLocation();
private static final int STRIDE = 16;
private static final int VERTEX_COLOR = 0xFF808080;
private static final float VERTEX_CHANNEL = 0x80 / 255.0f;
private static final Vector3f IDENTITY_FACTOR = new Vector3f(1.0f, 1.0f, 1.0f);
private final Vector3f factor = new Vector3f();
private int vao;
private int vbo;
@BeforeEach
void setUpState() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glViewport(0, 0, 800, 600);
GLStateManager.disableDepthTest();
GLStateManager.disableCull();
GLStateManager.disableBlend();
GLStateManager.disableTexture();
GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f);
standardItemLighting();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 0.0f);
}
@AfterEach
void cleanup() {
GLStateManager.glDisable(GL11.GL_NORMALIZE);
GLStateManager.glDisable(GL12.GL_RESCALE_NORMAL);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glDisable(GL11.GL_LIGHTING);
GLStateManager.glDisable(GL11.GL_LIGHT0);
GLStateManager.glDisable(GL11.GL_LIGHT1);
GLStateManager.glDisable(GL11.GL_LIGHT2);
GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL);
final ShaderManager sm = ShaderManager.getInstance();
if (sm.isActive()) sm.deactivate();
sm.disable();
GLStateManager.glBindVertexArray(0);
if (vbo != 0) {
GLStateManager.glDeleteBuffers(vbo);
vbo = 0;
}
if (vao != 0) {
GLStateManager.glDeleteVertexArrays(vao);
vao = 0;
}
}
private static void standardItemLighting() {
GLStateManager.glEnable(GL11.GL_LIGHTING);
GLStateManager.glEnable(GL11.GL_LIGHT0);
GLStateManager.glEnable(GL11.GL_LIGHT1);
GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL);
GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, floats(0.4f, 0.4f, 0.4f, 1.0f));
light(GL11.GL_LIGHT0, 0.2f, 1.0f, -0.7f);
light(GL11.GL_LIGHT1, -0.2f, 1.0f, 0.7f);
}
private static void light(int light, float x, float y, float z) {
GLStateManager.glLight(light, GL11.GL_POSITION, floats(x, y, z, 0.0f));
GLStateManager.glLight(light, GL11.GL_DIFFUSE, floats(0.6f, 0.6f, 0.6f, 1.0f));
GLStateManager.glLight(light, GL11.GL_AMBIENT, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glLight(light, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f));
}
private static String gateState() {
final var material = GLStateManager.getFrontMaterial();
return "lighting=" + GLStateManager.getLightingState().isEnabled()
+ " colorMaterial=" + GLStateManager.getColorMaterial().isEnabled()
+ " cmParam=0x" + Integer.toHexString(GLStateManager.getColorMaterialParameter().getValue())
+ " emission=" + material.emission
+ " specular=" + material.specular
+ " shininess=" + material.shininess
+ " lmAmbient=" + GLStateManager.getLightModel().ambient
+ " light0=" + GLStateManager.getLightStates()[0].isEnabled()
+ " light1=" + GLStateManager.getLightStates()[1].isEnabled();
}
private static FloatBuffer floats(float... values) {
final FloatBuffer buf = BufferUtils.createFloatBuffer(values.length);
buf.put(values).flip();
return buf;
}
private void buildTriangle() {
vao = GLStateManager.glGenVertexArrays();
GLStateManager.glBindVertexArray(vao);
final ByteBuffer data = BufferUtils.createByteBuffer(3 * STRIDE);
putVertex(data, -0.9f, -0.9f);
putVertex(data, 0.9f, -0.9f);
putVertex(data, 0.0f, 0.9f);
data.flip();
vbo = GLStateManager.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW);
GLStateManager.glEnableVertexAttribArray(POSITION_LOC);
GLStateManager.glVertexAttribPointer(POSITION_LOC, 3, GL11.GL_FLOAT, false, STRIDE, 0L);
GLStateManager.glEnableVertexAttribArray(COLOR_LOC);
GLStateManager.glVertexAttribPointer(COLOR_LOC, 4, GL11.GL_UNSIGNED_BYTE, true, STRIDE, 12L);
VAOManager.setCurrentVertexFlags(COLOR_BIT);
}
private static void putVertex(ByteBuffer buf, float x, float y) {
final int base = buf.position();
buf.putFloat(base, x).putFloat(base + 4, y).putFloat(base + 8, 0.0f);
buf.putInt(base + 12, VERTEX_COLOR);
buf.position(base + STRIDE);
}
private float[] drawAndReadCenter() {
buildTriangle();
final ShaderManager sm = ShaderManager.getInstance();
sm.enable();
sm.activate();
GLStateManager.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT);
GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "FFP draw must not raise a GL error");
final ByteBuffer pixel = BufferUtils.createByteBuffer(4);
GL11.glReadPixels(400, 200, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel);
return new float[] { (pixel.get(0) & 0xFF) / 255.0f, (pixel.get(1) & 0xFF) / 255.0f, (pixel.get(2) & 0xFF) / 255.0f };
}
private void assertSolverMatchesShader(String context) {
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), context + ": expected a representable factor");
final float[] actual = drawAndReadCenter();
final float[] expected = { Math.min(1.0f, VERTEX_CHANNEL * factor.x), Math.min(1.0f, VERTEX_CHANNEL * factor.y), Math.min(1.0f, VERTEX_CHANNEL * factor.z) };
for (int c = 0; c < 3; c++) {
assertEquals(expected[c], actual[c], 2.0f / 255.0f, context + ": channel " + c + " solver=" + expected[c] + " shader=" + actual[c] + " factor=" + factor);
}
}
@Test
void faceOnNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f);
assertSolverMatchesShader("face-on normal");
}
@Test
void signNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.0f, 0.0f, -0.010416667f);
assertSolverMatchesShader("sign normal");
assertTrue(factor.x < 0.45f, "a 0.0104-long normal must stay at the 0.4 light model ambient floor rather than pick up 0.6 per light, got " + factor.x);
}
@Test
void tiltedNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.3f, 0.8f, 0.5f);
assertSolverMatchesShader("tilted normal");
}
@Test
void rescaleNormalMatchesGeneratedShader() {
GLStateManager.glEnable(GL12.GL_RESCALE_NORMAL);
GLStateManager.glScalef(1.0f, 2.0f, 1.0f);
GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f);
assertSolverMatchesShader("rescale normal");
}
@Test
void normalizeMatchesGeneratedShader() {
GLStateManager.glEnable(GL11.GL_NORMALIZE);
GLStateManager.glScalef(1.0f, 2.0f, 1.0f);
GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f);
assertSolverMatchesShader("normalize");
assertTrue(factor.x > 1.2f, "normalize restores the unit normal, which must pick up more diffuse than rescale's 0.5-long one, got " + factor.x);
}
@Test
void materialEmissionIsNotRepresentable() {
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.1f, 0.1f, 0.1f, 1.0f));
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "emission is additive, so the lit colour is not vertexColor * factor");
assertEquals(IDENTITY_FACTOR, factor, "a rejected solve must leave an identity factor");
}
@Test
void specularContributionIsNotRepresentable() {
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f));
GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 16.0f);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f));
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "specular is additive, so the lit colour is not vertexColor * factor");
}
@Test
void nonAmbientAndDiffuseColorMaterialIsNotRepresentable() {
GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION);
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "only AMBIENT_AND_DIFFUSE makes the lit colour scale with the vertex colour");
}
@Test
void lightsBeyondTheFfpCountAreIgnored() {
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState);
final Vector3f twoLights = new Vector3f(factor);
light(GL11.GL_LIGHT2, 0.0f, 0.0f, 1.0f);
GLStateManager.glEnable(GL11.GL_LIGHT2);
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState);
assertEquals(twoLights, factor, "VertexShaderGenerator emits only GL_LIGHT0/GL_LIGHT1, so text must not see GL_LIGHT2 either");
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class UniformsRescaleTest {
private static float rescaleFactorFor(float sx, float sy, float sz) {
final Matrix3f normalMatrix = new Matrix3f();
new Matrix4f().rotateY(0.7f).scale(sx, sy, sz).normal(normalMatrix);
return Uniforms.rescaleFactor(normalMatrix, new Vector3f());
}
@Test
void rescaleFactorUsesTheInverseModelviewBottomRow() {
assertEquals(8.0f, rescaleFactorFor(4.0f, 2.0f, 8.0f), 1.0e-5f, "wrong normal matrix column");
}
@Test
void uniformScaleIsRowIndependent() {
assertEquals(2.0f, rescaleFactorFor(2.0f, 2.0f, 2.0f), 1.0e-5f);
}
@Test
void singularMatrixFallsBackToUnitScale() {
assertEquals(1.0f, rescaleFactorFor(1.0f, 1.0f, 0.0f), 1.0e-5f, "a degenerate normal matrix must not divide by zero");
}
}
@@ -0,0 +1,113 @@
package com.gtnewhorizons.angelica.glsm.profiling;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SectionRegistryTest {
private static final class RecordingEmitter implements SectionRegistry.Emitter {
final List<String> setups = new ArrayList<>();
final List<String> enters = new ArrayList<>();
final List<Long> leaves = new ArrayList<>();
long nextId;
boolean connected;
@Override
public long enter(int category, String text) {
enters.add(category + ":" + text);
return connected ? ++nextId : 0L;
}
@Override
public void leave(long nativeId) {
leaves.add(nativeId);
}
@Override
public void setup(int category, String name) {
setups.add(category + ":" + name);
}
@Override
public boolean isConnected() {
return connected;
}
}
private final RecordingEmitter emitter = new RecordingEmitter();
private final SectionRegistry registry = new SectionRegistry(emitter);
private void reconnect() {
emitter.connected = false;
registry.poll();
emitter.connected = true;
registry.poll();
}
@Test
void tokensOutliveEveryReplayAndLeaveUsesTheNewestId() {
final long openedWhileDisconnected = registry.enter(1, "world");
assertNotEquals(0L, openedWhileDisconnected, "token must be valid while disconnected");
assertEquals(0L, emitter.nextId, "no native id while disconnected");
emitter.connected = true;
registry.poll();
final long openedWhileConnected = registry.enter(2, "shaders");
assertNotEquals(openedWhileDisconnected, openedWhileConnected);
reconnect();
emitter.leaves.clear();
registry.leave(openedWhileDisconnected);
registry.leave(openedWhileConnected);
assertEquals(List.of(3L, 4L), emitter.leaves, "leave must use the post-reconnect ids");
}
@Test
void aSectionEnteredOnTheConnectingFrameIsNotEnteredTwice() {
emitter.connected = true;
registry.enter(2, "shaders pack / Overworld");
registry.poll();
assertEquals(List.of("2:shaders pack / Overworld"), emitter.enters, "must not re-enter a section already live on this connection");
}
@Test
void reconnectReplaysEveryCategoryAndEveryOpenSection() {
registry.registerCategory(1, "World");
registry.registerCategory(4, "UI");
emitter.connected = true;
registry.poll();
registry.enter(1, "world");
registry.enter(4, "pause");
emitter.setups.clear();
emitter.enters.clear();
reconnect();
assertEquals(List.of("1:World", "4:UI"), emitter.setups, "all categories re-registered");
assertEquals(List.of("1:world", "4:pause"), emitter.enters, "all open sections re-entered");
}
@Test
void leftSectionsAreNotResurrectedByAReconnect() {
emitter.connected = true;
registry.poll();
final long token = registry.enter(1, "transient");
registry.leave(token);
emitter.enters.clear();
emitter.leaves.clear();
reconnect();
registry.leave(token);
assertTrue(emitter.enters.isEmpty(), "closed sections must not be re-entered");
assertTrue(emitter.leaves.isEmpty(), "closed tokens must not be left twice");
}
}
@@ -331,6 +331,9 @@ class GLSMRedirectorTest {
void phase2NameKeyedGapsRedirect() {
assertRedirected("org/lwjgl/opengl/GL33C", "glQueryCounter", "(II)V", "glQueryCounter");
assertRedirected("org/lwjgl/opengl/GL33C", "glGetQueryObjectui64", "(II)J", "glGetQueryObjectui64");
assertRedirected("org/lwjgl/opengl/ARBTimerQuery", "glGetQueryObjectui64", "(II)J", "glGetQueryObjectui64");
assertRedirected("org/lwjgl/opengl/EXTTimerQuery", "glGetQueryObjectuEXT", "(II)J", "glGetQueryObjectui64");
assertRedirected("org/lwjgl/opengl/EXTTimerQuery", "glGetQueryObjectui64EXT", "(II)J", "glGetQueryObjectui64");
assertRedirected("org/lwjgl/opengl/GL30C", "glBindFragDataLocation", "(IILjava/lang/CharSequence;)V", "glBindFragDataLocation");
assertRedirected("org/lwjgl/opengl/GL11C", "glGetIntegerv", "(I[I)V", "glGetInteger");
assertRedirected("org/lwjgl/opengl/GL20C", "glUniform4fv", "(I[F)V", "glUniform4");
+2 -2
View File
@@ -9,13 +9,13 @@ asmCompile = "5.0.3"
lwjgl3 = "3.4.2-20260602.093430-9"
lwjgl3ify = "3.0.31"
celeritas = "2.5.9-GTNH"
celeritas = "2.5.10-GTNH"
gtnhlib = "0.11.36"
eventbus = "7.0-beta.15"
glslTransformLib = "0.2.0-33.g3ec381e"
antlr4Runtime = "4.13.2"
jcpp = "1.4.14"
tracy = "0.13.1"
tracy = "0.14.0"
retroFuturaBootstrap = "1.1.0"
lombok = "1.18.46"
@@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.glsm.GLESCaps;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.DebugMessageHandler;
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import me.eigenraven.lwjgl3ify.api.Lwjgl3Aware;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -171,10 +172,14 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend {
public int getMinGLSLVersion() {return 330;}
@Override
protected void setSwapInterval(boolean vsync) {SDLVideo.SDL_GL_SetSwapInterval(vsync ? 1 : 0);}
protected VSyncMode applyVSyncMode(VSyncMode preferred) {
final boolean enabled = preferred.tearFree();
SDLVideo.SDL_GL_SetSwapInterval(enabled ? 1 : 0);
return enabled ? VSyncMode.ON : VSyncMode.OFF;
}
@Override
public int getDisplayRefreshRateHz() {
protected int queryDisplayRefreshRateHz() {
final long window = Display.getWindow();
final int displayId = window == 0 ? SDLVideo.SDL_GetPrimaryDisplay() : SDLVideo.SDL_GetDisplayForWindow(window);
if (displayId == 0) return 0;
+2
View File
@@ -59,6 +59,7 @@ dependencies {
api(project(":glsm"))
compileOnly(libs.lwjgl3ify) { artifact { classifier = "dev" }; isTransitive = false }
compileOnly(libs.retrofuturabootstrap) { isTransitive = false }
compileOnly(libs.celeritas.common) { isTransitive = false }
// GL enum constants (compileOnly -- no runtime GL dependency)
@@ -76,6 +77,7 @@ dependencies {
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(testFixtures(project(":glsm")))
testImplementation(libs.celeritas.common) { isTransitive = false }
testImplementation(libs.lwjgl3.opengl)
// GL.<clinit> loads liblwjgl_opengl.so. Test scope only: a root-level runtimeOnly collides with lwjgl3Bindings.
testRuntimeOnly(libs.lwjgl3.opengl) { artifact { classifier = lwjglNatives } }
@@ -10,6 +10,7 @@ import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.sdl.SDLLog;
import org.taumc.glsl.grammar.GLSLParser;
import org.lwjgl.sdl.SDLProperties;
import org.lwjgl.system.Platform;
import org.lwjglx.Sys;
@@ -100,6 +101,11 @@ public final class SDLGPUGate {
ShaderManager.prewarmSpirv(transformedSource, glShaderType);
}
public static void prewarmSpirv(String transformedSource, GLSLParser.Translation_unitContext bodyTree, int headerLen, int glShaderType) {
if (!isActive()) return;
ShaderManager.prewarmSpirv(transformedSource, bodyTree, headerLen, glShaderType);
}
public static void clearShaderPrewarmCache() {
if (!isActive()) return;
ShaderManager.clearPrewarmCache();
@@ -152,6 +158,9 @@ public final class SDLGPUGate {
}
public static void fallBackToGL() {
if (SDLGPULWJGLService.isOfferedAsAvailable()) {
throw new IllegalStateException("Celeritas already selected the SDL GPU LWJGL service; falling back to OpenGL would leave it bound to a dead backend");
}
disarmed = true;
engaged = false;
deviceReady = false;
@@ -19,11 +19,17 @@ import java.util.Arrays;
/** SDL GPU implementation of {@link LWJGLService} for Celeritas */
public final class SDLGPULWJGLService extends LWJGLService {
private static volatile boolean offeredAsAvailable;
public static boolean isOfferedAsAvailable() { return offeredAsAvailable; }
@Override public int getPriority() {
if (SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable() && SDLGPUGate.isEngaged()) {
return 200;
if (!SystemProperties.USE_SDL_GPU || !SDLGPUGate.isSDLGPUAvailable() || !SDLGPUGate.isEngaged()) {
return PRIORITY_UNAVAILABLE;
}
return Integer.MIN_VALUE;
offeredAsAvailable = true;
return 200;
}
@Override public boolean isOpenGLVersionSupported(int major, int minor) {
@@ -148,22 +154,30 @@ public final class SDLGPULWJGLService extends LWJGLService {
}
@Override public void glDeleteSync(long sync) { BackendManager.RENDER_BACKEND.deleteSync(sync); }
private long[] queryTimestamps = new long[64];
private long[] queryElapsed = new long[64];
private int activeQueryId = -1;
private long activeQueryStart;
private void ensureQueryCapacity(int id) {
if (id >= queryTimestamps.length) {
queryTimestamps = Arrays.copyOf(queryTimestamps, Math.max(id + 1, queryTimestamps.length * 2));
if (id >= queryElapsed.length) {
queryElapsed = Arrays.copyOf(queryElapsed, Math.max(id + 1, queryElapsed.length * 2));
}
}
@Override public int glGenQueries() { return BackendManager.RENDER_BACKEND.genQueries(); }
@Override public void glDeleteQueries(int query) { }
@Override public void glQueryCounter(int id, int target) {
@Override public void glBeginQuery(int target, int id) {
ensureQueryCapacity(id);
queryTimestamps[id] = System.nanoTime();
activeQueryId = id;
activeQueryStart = System.nanoTime();
}
@Override public void glEndQuery(int target) {
if (activeQueryId < 0) return;
queryElapsed[activeQueryId] = System.nanoTime() - activeQueryStart;
activeQueryId = -1;
}
@Override public long glGetQueryObjectui64(int id, int pname) {
if (id >= 0 && id < queryTimestamps.length) return queryTimestamps[id];
if (id >= 0 && id < queryElapsed.length) return queryElapsed[id];
return 0;
}
@@ -18,6 +18,8 @@ import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.frame.FenceTracker;
import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager;
import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager.FrameState;
import com.gtnewhorizons.angelica.sdlgpu.frame.Presenter;
import com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.DrawDispatch;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineApplier;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache;
@@ -41,9 +43,10 @@ import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageBufferBinder;
import com.gtnewhorizons.angelica.sdlgpu.sampler.StorageTextureBinder;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import com.gtnewhorizons.angelica.sdlgpu.splash.SplashDispatcher;
import com.gtnewhorizons.angelica.sdlgpu.splash.SplashOffscreenTarget;
import com.gtnewhorizons.angelica.sdlgpu.frame.OffscreenTarget;
import com.gtnewhorizons.angelica.sdlgpu.util.DebugLabels;
import com.gtnewhorizons.angelica.sdlgpu.util.DebugMessageRelay;
import com.gtnewhorizons.angelica.sdlgpu.util.ThreadRegistry;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
@@ -80,12 +83,11 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.lwjgl.sdl.SDLGPU;
import org.lwjgl.sdl.SDLSurface;
import org.lwjgl.sdl.SDL_GPUBlitInfo;
import org.lwjgl.sdl.SDL_GPUBufferLocation;
import org.lwjgl.sdl.SDL_GPUTextureLocation;
@@ -108,6 +110,7 @@ public class SDLGPURenderBackend extends RenderBackend {
private final Device device = SDLGPUGate.device();
private final FrameManager frameManager = new FrameManager(device);
private volatile Presenter presenter;
private final ResourceManager resourceManager = new ResourceManager(device, frameManager);
private final Image3DClear image3DClear = new Image3DClear();
private final ShaderManager shaderManager = new ShaderManager(device);
@@ -151,33 +154,31 @@ public class SDLGPURenderBackend extends RenderBackend {
private volatile boolean shutdown;
private SplashOffscreenTarget splashTarget;
private volatile OffscreenTarget splashTarget;
private volatile boolean splashTeardownPending;
private static final CopyOnWriteArrayList<ContextState> registeredStates = new CopyOnWriteArrayList<>();
private static final ThreadLocal<ContextState> tlState = ThreadLocal.withInitial(() -> {
private static final ThreadRegistry<ContextState> registeredStates = new ThreadRegistry<>(new ContextState[0]);
private static final ThreadLocal<ContextState> tlState = new ThreadLocal<>();
private static ContextState s() {
final ContextState sole = registeredStates.sole();
if (sole != null && sole.owner == Thread.currentThread()) return sole;
final ContextState st = tlState.get();
return st != null ? st : registerState();
}
private static ContextState registerState() {
final ContextState st = new ContextState();
for (int i = 0; i < ContextState.MAX_VERTEX_ATTRIBS; i++) st.attribDefaults[i * 4 + 3] = 1.0f;
st.attribDefaults[4] = 1.0f; st.attribDefaults[5] = 1.0f;
st.attribDefaults[6] = 1.0f;
tlState.set(st);
registeredStates.add(st);
refreshSoleState();
return st;
});
private static volatile ContextState soleState;
private static void refreshSoleState() {
soleState = registeredStates.size() == 1 ? registeredStates.get(0) : null;
}
private static ContextState s() {
final ContextState st = soleState;
if (st != null && st.owner == Thread.currentThread()) return st;
return tlState.get();
}
private void markAllPipelineInputDirty() {
for (ContextState st : registeredStates) st.pipeline.markInputDirty();
for (ContextState st : registeredStates.snapshot()) st.pipeline.markInputDirty();
}
public static final int CTR_SLOT_WRITES = 0;
@@ -189,7 +190,7 @@ public class SDLGPURenderBackend extends RenderBackend {
public static void takeContextCounters(int[] out) {
Arrays.fill(out, 0);
for (ContextState st : registeredStates) {
for (ContextState st : registeredStates.snapshot()) {
out[CTR_SLOT_WRITES] += st.slotWrites;
out[CTR_SLOT_WRITES_ELIDED] += st.slotWritesElided;
out[CTR_SSBO_BINDS] += st.ssboBinds;
@@ -204,7 +205,7 @@ public class SDLGPURenderBackend extends RenderBackend {
}
private void releaseUniformStagingAllThreads(ShaderManager.ProgramObject prog) {
for (ContextState st : registeredStates) st.releaseUniformStaging(prog);
for (ContextState st : registeredStates.snapshot()) st.releaseUniformStaging(prog);
}
@@ -240,16 +241,12 @@ public class SDLGPURenderBackend extends RenderBackend {
});
GLSMHooks.LOADING_CHECKPOINT
.addListener(event -> {
if (Thread.currentThread() == GLStateManager.getMainThread()) {
if (!GLStateManager.isSplashComplete()) {
SplashDispatcher.tryDispatch(this, splashTarget);
} else if (splashTarget != null) {
SplashDispatcher.signalFrameReady();
SplashDispatcher.tryDispatch(this, splashTarget);
splashTarget.destroy(resourceManager);
splashTarget = null;
SplashDispatcher.reset();
if (!GLStateManager.isSplashComplete()) {
if (Thread.currentThread() == GLStateManager.getMainThread()) {
SplashDispatcher.tryDispatch(this, splashTarget, false);
}
} else if (splashTarget != null) {
splashTeardownPending = true;
}
if (event.requiresSync) {
frameManager.requestSyncFlushOnAllRegisteredFrames();
@@ -290,13 +287,19 @@ public class SDLGPURenderBackend extends RenderBackend {
resourceManager.setBufferLivenessListener(this::markAllPipelineInputDirty);
shaderManager.setUniformReleaseListener(this::releaseUniformStagingAllThreads);
fenceTracker.setUnresolvedFenceFlush(this::midFrameFenceFlush);
frameManager.setMainThread(GLStateManager.getMainThread());
if (!SystemProperties.DISABLE_SDL_PRESENTER_THREAD) {
presenter = new Presenter(frameManager, MainStartOnFirstThread.instance());
frameManager.setPresenter(presenter);
LOG.info("SDL presenter thread enabled: presents run on '{}'", device.getWindowThread() != null ? device.getWindowThread().getName() : "window thread");
}
final int splashW = Math.max(1, Display.getWidth());
final int splashH = Math.max(1, Display.getHeight());
final int[] maxDesktop = device.getMaxDesktopSizePixels();
final int splashTexW = Math.max(splashW, maxDesktop[0]);
final int splashTexH = Math.max(splashH, maxDesktop[1]);
splashTarget = new SplashOffscreenTarget();
splashTarget = new OffscreenTarget();
splashTarget.create(device, resourceManager, splashTexW, splashTexH, device.getSwapchainTextureFormat());
SplashDispatcher.seedDrawnSize(splashW, splashH);
LOG.info("Splash offscreen target {}x{} (window {}x{}, max desktop {}x{})", splashTexW, splashTexH, splashW, splashH, maxDesktop[0], maxDesktop[1]);
@@ -376,31 +379,50 @@ public class SDLGPURenderBackend extends RenderBackend {
LOG.info("Populated GL capabilities for SDL GPU backend");
}
@Override protected void setSwapInterval(boolean vsync) {
device.setVSyncMode(VSyncMode.AUTO, vsync);
}
private final AtomicReference<VSyncMode> pendingVSync = new AtomicReference<>();
@Override protected VSyncMode applyVSyncMode(VSyncMode preferred, boolean vsyncEnabled) {
return device.setVSyncMode(preferred, vsyncEnabled);
@Override protected VSyncMode applyVSyncMode(VSyncMode preferred) {
pendingVSync.set(preferred);
return device.chooseVSyncMode(preferred);
}
@Override public boolean supportsVSyncMode(VSyncMode mode) {
return mode == VSyncMode.AUTO || device.supportsVSyncMode(mode);
return device.supportsVSyncMode(mode);
}
@Override public int getMinRenderAhead() { return Device.MIN_FRAMES_IN_FLIGHT; }
private void applyPendingVSync() {
final VSyncMode preferred = pendingVSync.getAndSet(null);
if (preferred != null) {
if (presenter != null) presenter.drain();
publishVSyncMode(device.applyVSync(preferred));
}
}
@Override public int getMaxRenderAhead() { return Device.MAX_FRAMES_IN_FLIGHT; }
@Override public void setRenderAheadLimit(int frames) { device.setFramesInFlight(frames); }
@Override public int getDisplayRefreshRateHz() {
@Override protected int queryDisplayRefreshRateHz() {
return device.getDisplayRefreshRateHz();
}
@Override public boolean gateAnchorsNextFrameStart() { return true; }
@Override public boolean wantsDisplayUpdateGateTiming() { return false; }
@Override public long lastFrameGateNanos() {
if (presenter != null) return frameManager.windowFrame().lastFrameGateNanos;
return frameManager.lastFrameGateNanos();
}
@Override public long lastFrameGateEndNanos() {
if (presenter != null) return frameManager.windowFrame().lastFrameGateEndNanos;
return frameManager.lastFrameGateEndNanos();
}
@Override public boolean hasSwapchainBackpressure() { return true; }
@Override public void shutdown() {
if (shutdown) return;
shutdown = true;
if (presenter != null) presenter.drain();
frameManager.destroyFinalTarget();
if (splashTarget != null) {
splashTarget.destroy(resourceManager);
splashTarget = null;
@@ -423,7 +445,7 @@ public class SDLGPURenderBackend extends RenderBackend {
fenceTracker.dispose();
frameManager.releaseAllRegisteredFrames();
resourceManager.shutdownTexSamplerStates();
for (ContextState st : registeredStates) {
for (ContextState st : registeredStates.snapshot()) {
if (st.fanIndexBuffer != 0) {
resourceManager.releaseBufferHandle(st.fanIndexBuffer);
st.fanIndexBuffer = 0;
@@ -441,7 +463,6 @@ public class SDLGPURenderBackend extends RenderBackend {
clearMappedState(st);
}
registeredStates.clear();
soleState = null;
drawDispatch.clearWarnedState();
pipelineStore.shutdown();
@@ -480,32 +501,35 @@ public class SDLGPURenderBackend extends RenderBackend {
}
@Override public void onRenderThreadReleased(Thread t) {
if (shutdown || t == GLStateManager.getMainThread()) return;
if (frameManager.isFrameActive()) {
frameManager.endFrame();
}
frameManager.releaseThreadState();
registeredStates.remove(tlState.get());
tlState.remove();
refreshSoleState();
final ContextState st = tlState.get();
if (st != null) {
tlState.remove();
registeredStates.remove(st);
}
}
@Override public boolean handleMakeCurrent(Object drawable) {
if (!isSDLManagedDrawable(drawable)) return false;
Lwjgl3GLCapabilitiesShim.installOnCurrentThread(advertisedCapabilities());
if (splashTarget != null && Thread.currentThread() != GLStateManager.getMainThread()) {
s().boundFboId = splashTarget.fboId();
final OffscreenTarget splash = splashTarget;
if (splash != null && Thread.currentThread() != GLStateManager.getMainThread()) {
s().boundFboId = splash.fboId();
frameManager.frame().swapchainUnavailable = true;
}
return true;
}
@Override public boolean handleReleaseContext(Object drawable) {
if (isSDLManagedDrawable(drawable)) {
Lwjgl3GLCapabilitiesShim.clearOnCurrentThread();
onRenderThreadReleased(Thread.currentThread());
return true;
}
return false;
if (!isSDLManagedDrawable(drawable)) return false;
if (Thread.currentThread() == GLStateManager.getMainThread()) return true;
Lwjgl3GLCapabilitiesShim.clearOnCurrentThread();
onRenderThreadReleased(Thread.currentThread());
return true;
}
private static boolean isSDLManagedDrawable(Object drawable) {
@@ -515,7 +539,8 @@ public class SDLGPURenderBackend extends RenderBackend {
}
@Override public boolean handleSwapBuffers() {
if (splashTarget != null && splashTarget.isFor(s()) && Thread.currentThread() != GLStateManager.getMainThread()) {
final OffscreenTarget splash = splashTarget;
if (splash != null && splash.isFor(s()) && Thread.currentThread() != GLStateManager.getMainThread()) {
endFrameUploadFlush();
frameManager.endFrame();
SplashDispatcher.signalFrameReady((int) s().viewportW, (int) s().viewportH);
@@ -528,33 +553,30 @@ public class SDLGPURenderBackend extends RenderBackend {
return true;
}
public void dispatchSplashBlit(SplashOffscreenTarget target) {
public void dispatchSplashBlit(OffscreenTarget target) {
if (shutdown || target == null) return;
onFrameBegin();
final FrameManager.FrameState f = frameManager.frame();
if (!frameManager.ensureSwapchainAcquired(f)) {
onFrameEnd();
return;
}
frameManager.endCopyPassIfActive();
frameManager.endRenderPassIfActive();
final long drawnSize = SplashDispatcher.getDrawnSize();
final int srcW = Math.max(1, Math.min((int) (drawnSize >> 32), target.width()));
final int srcH = Math.max(1, Math.min((int) drawnSize, target.height()));
try (var stack = MemoryStack.stackPush()) {
final var info = SDL_GPUBlitInfo.calloc(stack);
info.source(s -> s.texture(target.colorTexture()).x(0).y(0).w(srcW).h(srcH));
info.destination(d -> d.texture(f.swapchainTexture).x(0).y(0).w(f.swapchainWidth).h(f.swapchainHeight));
info.filter(SDL_GPU_FILTER_LINEAR);
info.flip_mode(SDLSurface.SDL_FLIP_VERTICAL);
SDL_BlitGPUTexture(f.commandBuffer, info);
}
f.swapchainUsedThisFrame = true;
onFrameEnd();
frameManager.presentSplash(target.colorTexture(), srcW, srcH);
}
private void finishSplash() {
splashTeardownPending = false;
final OffscreenTarget target = splashTarget;
if (target == null) return;
SplashDispatcher.signalFrameReady();
SplashDispatcher.tryDispatch(this, target, true);
if (presenter != null) presenter.drain();
splashTarget = null;
target.destroy(resourceManager);
SplashDispatcher.reset();
}
@Override public void onFrameBegin() {
if (shutdown) return;
if (splashTeardownPending) finishSplash();
if (GLStateManager.isSplashComplete()) applyPendingVSync();
frameManager.beginFrame();
beginFrameInit();
}
@@ -636,22 +658,24 @@ public class SDLGPURenderBackend extends RenderBackend {
endFrameUploadFlushNoWait();
final FrameState f = frameManager.frame();
if (f.frameActive && !f.swapchainUsedThisFrame) {
if (f.frameActive && !f.fbo0UsedThisFrame) {
if (!emptyFrameWarned) {
emptyFrameWarned = true;
LOG.info("Frame {} ended without drawing to the swapchain; skipping present (further occurrences counted in sdl.emptyFrames)", f.frameNumber);
LOG.info("Frame {} ended without drawing to FBO 0; presenting the previous contents (further occurrences counted in sdl.emptyFrames)", f.frameNumber);
}
frameManager.markFrameEmpty(f);
}
awaitUploadFlush();
frameManager.endFrame();
frameManager.presentFinalTarget();
fenceTracker.resolvePendingFences();
resourceManager.flushDeferredReleases();
resourceManager.recycleGpuBufferPool(frameManager.getFrameNumber());
}
@Override public void onPreSwapchainInvalidatingChange(Object change) {
if (presenter != null) presenter.drain();
endFrameUploadFlush();
if (frameManager.isFrameActive()) {
frameManager.endFrame();
@@ -700,54 +724,6 @@ public class SDLGPURenderBackend extends RenderBackend {
return transferThread != null ? transferThread.getDebugInfo() : null;
}
private static final long PRESENT_STATS_WINDOW_NANOS = 1_000_000_000L;
private static final long PRESENT_STATS_STALE_NANOS = 2_000_000_000L;
private long presentStatsNanos;
private long presentStatsLoopFrames;
private long presentStatsPresentedFrames;
private long presentStatsSkips;
private long presentStatsEmpty;
private long presentStatsAcquireNanos;
private String presentDebugLine;
@Override public String getPresentDebugInfo() {
if (shutdown) return null;
final long now = System.nanoTime();
final long elapsed = now - presentStatsNanos;
if (presentStatsNanos == 0L || elapsed > PRESENT_STATS_STALE_NANOS) {
snapshotPresentStats(now);
presentDebugLine = null;
return null;
}
if (elapsed < PRESENT_STATS_WINDOW_NANOS) return presentDebugLine;
final long loopDelta = frameManager.statLoopFrames() - presentStatsLoopFrames;
final long presentedDelta = frameManager.statPresentedFrames() - presentStatsPresentedFrames;
final long skipDelta = frameManager.statPresentSkips() - presentStatsSkips;
final long emptyDelta = frameManager.statEmptyFrames() - presentStatsEmpty;
final long acquireDelta = frameManager.statAcquireWaitNanos() - presentStatsAcquireNanos;
final double seconds = elapsed / 1.0e9;
presentDebugLine = String.format("Present: %s %dHz | loop %.0f/s shown %.0f/s | skip %.0f/s empty %.0f/s | acq %.2fms | fif %d",
getEffectiveVSyncMode(), device.getDisplayRefreshRateHz(),
loopDelta / seconds, presentedDelta / seconds,
skipDelta / seconds, emptyDelta / seconds,
loopDelta == 0 ? 0.0 : acquireDelta / (double) loopDelta / 1.0e6,
Device.framesInFlight());
snapshotPresentStats(now);
return presentDebugLine;
}
private void snapshotPresentStats(long now) {
presentStatsNanos = now;
presentStatsLoopFrames = frameManager.statLoopFrames();
presentStatsPresentedFrames = frameManager.statPresentedFrames();
presentStatsSkips = frameManager.statPresentSkips();
presentStatsEmpty = frameManager.statEmptyFrames();
presentStatsAcquireNanos = frameManager.statAcquireWaitNanos();
}
@Override public void enable(int cap) { setBoolCap(cap, true); }
@Override public void enablei(int cap, int index) { setBoolCapIndexed(cap, index, true); }
@Override public void disable(int cap) { setBoolCap(cap, false); }
@@ -952,7 +928,7 @@ public class SDLGPURenderBackend extends RenderBackend {
final ContextState st = cs;
// Swapchain path: just record pending state; ensureSwapchainRenderPass consumes it lazily.
// FBO0 path: just record pending state; ensureFbo0RenderPass consumes it lazily.
if (st.boundFboId == 0) {
if (wantColor) {
st.pendingSwapchainClear = true;
@@ -1710,7 +1686,7 @@ public class SDLGPURenderBackend extends RenderBackend {
final long texHandle;
final int srcSdlFormat;
if (cs.boundReadFboId == 0) {
texHandle = frameManager.getSwapchainTexture();
texHandle = frameManager.getFbo0Texture();
srcSdlFormat = frameManager.getSwapchainFormat();
} else {
final FboState fbo = resourceManager.getFbo(cs.boundReadFboId);
@@ -20,6 +20,7 @@ import org.lwjgl.system.Platform;
import org.lwjglx.opengl.Display;
import java.nio.IntBuffer;
import java.util.List;
import java.util.function.Supplier;
import static org.lwjgl.sdl.SDLGPU.*;
@@ -31,13 +32,11 @@ import static org.lwjgl.system.MemoryUtil.memUTF8;
public final class Device {
private static final Logger LOG = LogManager.getLogger("Angelica-SDLGPU");
public static final int MIN_FRAMES_IN_FLIGHT = 1;
public static final int DEFAULT_FRAMES_IN_FLIGHT = 2;
public static final int MAX_FRAMES_IN_FLIGHT = 3;
private static volatile int framesInFlight = DEFAULT_FRAMES_IN_FLIGHT;
private static final int FRAMES_IN_FLIGHT = Math.min(Math.max(SystemProperties.SDL_FRAMES_IN_FLIGHT, 1), MAX_FRAMES_IN_FLIGHT);
public static int framesInFlight() { return framesInFlight; }
public static int framesInFlight() { return FRAMES_IN_FLIGHT; }
private static final int REQUESTED_SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL;
@@ -49,7 +48,7 @@ public final class Device {
private String driverVersion;
private String driverInfo;
private VSyncMode vsyncMode = VSyncMode.ON;
private volatile String windowThreadName;
private volatile Thread windowThread;
private SDL_LogOutputFunction logCallback; // prevent GC
private volatile boolean lost;
@@ -155,7 +154,13 @@ public final class Device {
throw new RuntimeException("Failed to claim window for SDL GPU device: " + SDLError.SDL_GetError());
}
claimed = true;
windowThreadName = Thread.currentThread().getName();
windowThread = Thread.currentThread();
if (!SDL_SetGPUAllowedFramesInFlight(device, FRAMES_IN_FLIGHT)) {
LOG.warn("SDL_SetGPUAllowedFramesInFlight({}) failed: {}", FRAMES_IN_FLIGHT, SDLError.SDL_GetError());
} else {
LOG.info("SDL frames-in-flight set to {}", FRAMES_IN_FLIGHT);
}
logWindowDiagnostics(window);
LOG.info("SDL GPU device claimed window successfully");
@@ -263,8 +268,8 @@ public final class Device {
return driverName;
}
public String getWindowThreadName() {
return windowThreadName;
public Thread getWindowThread() {
return windowThread;
}
public String getDeviceName() {
@@ -295,34 +300,48 @@ public final class Device {
return (supportedShaderFormats & SDL_GPU_SHADERFORMAT_DXBC) != 0;
}
public void setFramesInFlight(int frames) {
final int n = Math.min(Math.max(frames, MIN_FRAMES_IN_FLIGHT), MAX_FRAMES_IN_FLIGHT);
if (n == framesInFlight || device == 0 || !claimed) return;
if (!SDL_SetGPUAllowedFramesInFlight(device, n)) {
LOG.warn("SDL_SetGPUAllowedFramesInFlight({}) failed: {}; keeping {}", n, SDLError.SDL_GetError(), framesInFlight);
return;
}
framesInFlight = n;
LOG.info("SDL frames-in-flight set to {}", n);
private static final List<VSyncMode> ON_ORDER = List.of(VSyncMode.ON);
private static final List<VSyncMode> OFF_ORDER = List.of(VSyncMode.OFF, VSyncMode.ON);
private static final List<VSyncMode> MAILBOX_ORDER = List.of(VSyncMode.MAILBOX, VSyncMode.ON);
private static List<VSyncMode> presentModeOrder(VSyncMode preferred) {
return switch (preferred) {
case MAILBOX -> MAILBOX_ORDER;
case OFF -> OFF_ORDER;
default -> ON_ORDER;
};
}
public VSyncMode setVSyncMode(VSyncMode preferred, boolean vsyncEnabled) {
public VSyncMode chooseVSyncMode(VSyncMode preferred) {
for (VSyncMode candidate : presentModeOrder(preferred)) {
if (supportsVSyncMode(candidate)) return candidate;
}
return vsyncMode;
}
public VSyncMode applyVSync(VSyncMode preferred) {
if (device == 0 || !claimed) return vsyncMode;
final long window = Display.getWindow();
final VSyncMode requested = preferred.resolve(vsyncEnabled);
for (VSyncMode candidate : requested.fallbackOrder()) {
final List<VSyncMode> order = presentModeOrder(preferred);
for (VSyncMode candidate : order) {
final int sdlMode = toSdl(candidate);
if (!SDL_WindowSupportsGPUPresentMode(device, window, sdlMode)) continue;
if (!SDL_SetGPUSwapchainParameters(device, window, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, sdlMode)) {
LOG.warn("Failed to set present mode {}: {}", candidate, SDLError.SDL_GetError());
continue;
}
if (candidate != order.get(0)) {
LOG.warn("Present mode {} is not supported by this window; using {} instead", order.get(0), candidate);
}
vsyncMode = candidate;
LOG.info("SDL present mode {} (requested {}, preference {}, vsync={}), refresh {}Hz, supported: vsync={} mailbox={} immediate={}",
candidate, requested, preferred, vsyncEnabled, getDisplayRefreshRateHz(),
supportsVSyncMode(VSyncMode.ON), supportsVSyncMode(VSyncMode.MAILBOX), supportsVSyncMode(VSyncMode.OFF));
LOG.info("SDL present mode {} (preferred={}), refresh {}Hz, {}, video={}, framesInFlight={}, supported: vsync={} immediate={} mailbox={}",
candidate, preferred, getDisplayRefreshRateHz(),
(SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) != 0 ? "fullscreen" : "windowed",
SDL_GetCurrentVideoDriver(), FRAMES_IN_FLIGHT,
supportsVSyncMode(VSyncMode.ON), supportsVSyncMode(VSyncMode.OFF), supportsVSyncMode(VSyncMode.MAILBOX));
return candidate;
}
LOG.warn("No usable present mode for request {}; keeping {}", requested, vsyncMode);
LOG.warn("No usable present mode for preference {}; keeping {}", preferred, vsyncMode);
return vsyncMode;
}
@@ -330,6 +349,25 @@ public final class Device {
return device != 0 && claimed && SDL_WindowSupportsGPUPresentMode(device, Display.getWindow(), toSdl(mode));
}
public long getClaimedWindow() {
return device != 0 && claimed ? Display.getWindow() : 0L;
}
public boolean wasWindowResized() {
return getClaimedWindow() != 0L && Display.wasResized();
}
public long getWindowSizeInPixels() {
final long window = getClaimedWindow();
if (window == 0) return 0L;
try (MemoryStack stack = MemoryStack.stackPush()) {
final IntBuffer w = stack.mallocInt(1);
final IntBuffer h = stack.mallocInt(1);
SDL_GetWindowSizeInPixels(window, w, h);
return ((long) w.get(0) << 32) | (h.get(0) & 0xFFFFFFFFL);
}
}
private static int toSdl(VSyncMode mode) {
return switch (mode) {
case OFF -> SDL_GPU_PRESENTMODE_IMMEDIATE;
@@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager;
import com.gtnewhorizons.angelica.sdlgpu.util.MemoryAccess;
import com.gtnewhorizons.angelica.sdlgpu.util.ThreadRegistry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.sdlgpu.resource.UploadArena;
@@ -16,16 +17,20 @@ import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.sdl.SDLError;
import org.lwjgl.sdl.SDL_FColor;
import org.lwjgl.sdl.SDL_GPUBlitInfo;
import org.lwjgl.sdl.SDL_GPUBlitRegion;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo;
import org.lwjglx.opengl.Display;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.lwjgl.sdl.SDLGPU.*;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_NONE;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_VERTICAL;
import static org.lwjgl.system.MemoryStack.*;
/**
@@ -47,9 +52,6 @@ public final class FrameManager {
public long renderPass;
public long copyPass;
public boolean computePassOpen;
public long swapchainTexture;
public int swapchainWidth;
public int swapchainHeight;
public boolean frameActive;
public long currentColorTarget;
public long currentDepthTarget;
@@ -57,10 +59,9 @@ public final class FrameManager {
public long frameNumber;
public boolean clearedThisFrame;
public boolean depthClearedThisFrame;
public boolean swapchainUsedThisFrame;
public boolean swapchainAcquiredThisFrame;
public boolean fbo0UsedThisFrame;
public boolean presentedThisFrame;
public boolean swapchainUnavailable;
public boolean skipPresent;
public long renderPassGeneration;
public boolean wantFenceOnNextSubmit;
@@ -82,7 +83,12 @@ public final class FrameManager {
public int batchBreakSamplerThisFrame;
public int stateAppliesThisFrame;
public long acquireWaitNanosThisFrame;
public volatile long lastFrameGateNanos;
public volatile long lastFrameGateEndNanos;
public int midFrameSubmitsThisFrame;
public int mipGensThisFrame;
public int mipGenSubmitsThisFrame;
public int uploadFlushSubmitsThisFrame;
public int blitsThisFrame;
public int presentSkipsThisFrame;
public int emptyFramesThisFrame;
@@ -143,53 +149,52 @@ public final class FrameManager {
private volatile boolean globalSyncAtNextBeginFrame;
private final CopyOnWriteArrayList<FrameState> registeredFrames = new CopyOnWriteArrayList<>();
private final ThreadRegistry<FrameState> registeredFrames = new ThreadRegistry<>(new FrameState[0]);
private volatile FrameState soleFrame;
private final ThreadLocal<FrameState> tlFrame = ThreadLocal.withInitial(() -> {
final FrameState f = new FrameState();
registeredFrames.add(f);
refreshSoleFrame();
return f;
});
private void refreshSoleFrame() {
soleFrame = registeredFrames.size() == 1 ? registeredFrames.get(0) : null;
}
private final ThreadLocal<FrameState> tlFrame = new ThreadLocal<>();
public FrameState frame() {
final FrameState f = soleFrame;
if (f != null && f.owner == Thread.currentThread()) return f;
return tlFrame.get();
final FrameState sole = registeredFrames.sole();
if (sole != null && sole.owner == Thread.currentThread()) return sole;
final FrameState f = tlFrame.get();
return f != null ? f : registerFrame();
}
private FrameState registerFrame() {
final FrameState f = new FrameState();
tlFrame.set(f);
registeredFrames.add(f);
return f;
}
public int registeredFrameCount() {
return registeredFrames.size();
}
public FrameState busiestFrame() {
final FrameState[] frames = registeredFrames.snapshot();
FrameState best = null;
for (final FrameState f : registeredFrames) {
for (final FrameState f : frames) {
if (best == null || f.frameNumber > best.frameNumber) best = f;
}
return best != null ? best : frame();
}
public static final long SWAPCHAIN_LAYOUT_HASH = 0x5CA1AB1E5CA1AB1EL;
public static final long FBO0_LAYOUT_HASH = 0x5CA1AB1E5CA1AB1EL;
private final OffscreenTarget finalTarget = new OffscreenTarget();
public OffscreenTarget finalTarget() { return finalTarget; }
public void destroyFinalTarget() {
if (resourceManager != null) finalTarget.destroy(resourceManager);
}
public static final long MAX_PENDING_UPLOAD_BYTES = 16L * 1024L * 1024L;
public static final int MAX_PENDING_UPLOAD_COMMANDS = 256;
private Runnable beforeEndCopyPass;
private long statLoopFrames;
private long statPresentedFrames;
private long statPresentSkips;
private long statEmptyFrames;
private long statAcquireWaitNanos;
public long statLoopFrames() { return statLoopFrames; }
public long statPresentedFrames() { return statPresentedFrames; }
public long statPresentSkips() { return statPresentSkips; }
public long statEmptyFrames() { return statEmptyFrames; }
public long statAcquireWaitNanos() { return statAcquireWaitNanos; }
public FrameManager(Device device) {
this.device = device;
@@ -199,24 +204,12 @@ public final class FrameManager {
this.resourceManager = resourceManager;
}
private static volatile boolean threadLogged;
public void beginFrame() {
final FrameState f = frame();
if (f.frameActive) {
LOG.warn("beginFrame() called while frame already active on thread {}", Thread.currentThread().getName());
return;
}
if (!threadLogged) {
threadLogged = true;
final String renderThread = Thread.currentThread().getName();
final String windowThread = device.getWindowThreadName();
if (windowThread != null && !windowThread.equals(renderThread)) {
LOG.warn("Frames are recorded on '{}' but the SDL window was created on '{}'; SDL requires swapchain acquire/wait on the window-creating thread", renderThread, windowThread);
} else {
LOG.info("First beginFrame() on thread={}", renderThread);
}
}
flushPendingUploadCommandBuffer(f);
if (globalSyncAtNextBeginFrame) {
@@ -231,11 +224,10 @@ public final class FrameManager {
throw new RuntimeException("Failed to acquire GPU command buffer: " + SDLError.SDL_GetError());
}
f.swapchainTexture = 0;
f.swapchainWidth = 0;
f.swapchainHeight = 0;
f.swapchainAcquiredThisFrame = false;
f.swapchainUnavailable = false;
f.presentedThisFrame = false;
maintainFinalTarget();
f.frameActive = true;
f.renderPass = 0;
@@ -244,25 +236,53 @@ public final class FrameManager {
f.frameNumber++;
f.clearedThisFrame = false;
f.depthClearedThisFrame = false;
f.swapchainUsedThisFrame = false;
f.skipPresent = false;
f.fbo0UsedThisFrame = false;
}
private static final long FINAL_TARGET_SIZE_POLL_NANOS = 1_000_000_000L;
private long finalTargetPollNanos;
private volatile Thread mainThread;
public void setMainThread(Thread thread) {
this.mainThread = thread;
}
// Resizing releases a texture an in-flight present may still reference, so drain before ensureSize.
private void maintainFinalTarget() {
if (resourceManager == null) return;
final Thread owner = mainThread;
if (owner != null && Thread.currentThread() != owner) return;
final long now = System.nanoTime();
final boolean poll = finalTargetPollNanos == 0L || now - finalTargetPollNanos >= FINAL_TARGET_SIZE_POLL_NANOS;
if (!poll && !device.wasWindowResized() && finalTarget.isReady()) return;
if (poll) finalTargetPollNanos = now;
final long size = device.getWindowSizeInPixels();
if (size == 0L) return;
final int width = (int) (size >> 32);
final int height = (int) size;
if (finalTarget.isReady() && width == finalTarget.width() && height == finalTarget.height()) return;
if (presenter != null) presenter.drain();
finalTarget.ensureSize(device, resourceManager, width, height);
}
public void markFrameEmpty(FrameState f) {
f.skipPresent = true;
f.emptyFramesThisFrame++;
}
static boolean swapchainClearNeedsPassBreak(ContextState st, FrameState f) {
return (st.pendingSwapchainClear || st.pendingSwapchainDepthClear || st.pendingSwapchainStencilClear) && f.renderPass != 0 && f.currentColorTarget == f.swapchainTexture;
return (st.pendingSwapchainClear || st.pendingSwapchainDepthClear || st.pendingSwapchainStencilClear) && f.renderPass != 0 && f.activeLayoutHash == FBO0_LAYOUT_HASH;
}
public boolean ensureSwapchainRenderPass(FrameState f, ContextState st) {
public boolean ensureFbo0RenderPass(FrameState f, ContextState st) {
final boolean clearColor = st.pendingSwapchainClear;
if (swapchainClearNeedsPassBreak(st, f)) {
endRenderPassIfActive(f);
}
final boolean applied = ensureSwapchainRenderPass(f,
final boolean applied = ensureFbo0RenderPass(f,
clearColor ? st.pendingSwapchainR : st.clearR,
clearColor ? st.pendingSwapchainG : st.clearG,
clearColor ? st.pendingSwapchainB : st.clearB,
@@ -277,9 +297,9 @@ public final class FrameManager {
return true;
}
private boolean ensureSwapchainRenderPass(FrameState f, float clearR, float clearG, float clearB, float clearA, boolean clear, boolean clearDepth, float depthValue, boolean clearStencil, int stencilValue) {
if (!ensureSwapchainAcquired(f)) return false; // present-skip; don't bind tex=0
if (f.renderPass != 0 && f.currentColorTarget == f.swapchainTexture) {
private boolean ensureFbo0RenderPass(FrameState f, float clearR, float clearG, float clearB, float clearA, boolean clear, boolean clearDepth, float depthValue, boolean clearStencil, int stencilValue) {
if (!finalTarget.isReady() || f.commandBuffer == 0) return false;
if (f.renderPass != 0 && f.activeLayoutHash == FBO0_LAYOUT_HASH) {
return false;
}
@@ -289,7 +309,7 @@ public final class FrameManager {
clear = true;
}
final long depthTexture = resourceManager != null ? resourceManager.getOrCreateSwapchainDepthStencil(f.swapchainWidth, f.swapchainHeight) : 0L;
final long depthTexture = resourceManager != null ? resourceManager.getOrCreateSwapchainDepthStencil(finalTarget.width(), finalTarget.height()) : 0L;
if (depthTexture != 0 && !f.depthClearedThisFrame) {
clearDepth = true;
clearStencil = true;
@@ -298,7 +318,7 @@ public final class FrameManager {
try (var stack = stackPush()) {
final SDL_GPUColorTargetInfo.Buffer colorTargets = SDL_GPUColorTargetInfo.calloc(1, stack);
final long ctAddr = colorTargets.get(0).address();
MemoryAccess.putAddress(ctAddr + SDL_GPUColorTargetInfo.TEXTURE, f.swapchainTexture);
MemoryAccess.putAddress(ctAddr + SDL_GPUColorTargetInfo.TEXTURE, finalTarget.colorTexture());
MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.LOAD_OP, clear ? SDL_GPU_LOADOP_CLEAR : SDL_GPU_LOADOP_LOAD);
MemoryAccess.putInt(ctAddr + SDL_GPUColorTargetInfo.STORE_OP, SDL_GPU_STOREOP_STORE);
@@ -333,10 +353,11 @@ public final class FrameManager {
}
f.renderPassGeneration++;
f.swapchainPassesThisFrame++;
f.currentColorTarget = f.swapchainTexture;
f.currentColorTarget = finalTarget.colorTexture();
f.currentDepthTarget = depthTexture;
f.activeLayoutHash = SWAPCHAIN_LAYOUT_HASH;
f.swapchainUsedThisFrame = true;
f.activeLayoutHash = FBO0_LAYOUT_HASH;
f.fbo0UsedThisFrame = true;
finalTarget.markContent();
}
return true;
}
@@ -388,6 +409,8 @@ public final class FrameManager {
public void noteMipGen() { frame().mipGensThisFrame++; }
public void noteMipGenSubmit() { frame().mipGenSubmitsThisFrame++; }
public void noteBlit() { frame().blitsThisFrame++; }
public void noteClearPass() { frame().clearPassesThisFrame++; }
@@ -441,6 +464,20 @@ public final class FrameManager {
}
}
private volatile boolean acquireThreadReported;
private void checkAcquireOnWindowThread() {
if (acquireThreadReported) return;
final Thread self = Thread.currentThread();
final Thread window = device.getWindowThread();
if (window == null || window == self) return;
acquireThreadReported = true;
final String message = "Swapchain acquired on '" + self.getName() + "', window created on '" + window.getName() + "'";
if (SystemProperties.isDeobf() && !SystemProperties.DISABLE_SDL_PRESENTER_THREAD) throw new IllegalStateException(message);
LOG.warn(message);
}
public long ensureCopyPass() {
final FrameState f = frame();
if (f.copyPass != 0) {
@@ -477,17 +514,14 @@ public final class FrameManager {
}
public void requestFlushOnAllRegisteredFrames() {
final int n = registeredFrames.size();
for (int i = 0; i < n; i++) {
registeredFrames.get(i).flushRequested = true;
for (final FrameState f : registeredFrames.snapshot()) {
f.flushRequested = true;
}
}
public void requestSyncFlushOnAllRegisteredFrames() {
globalSyncAtNextBeginFrame = true;
final int n = registeredFrames.size();
for (int i = 0; i < n; i++) {
final FrameState f = registeredFrames.get(i);
for (final FrameState f : registeredFrames.snapshot()) {
f.flushRequested = true;
f.syncOnNextFlush = true;
}
@@ -514,10 +548,6 @@ public final class FrameManager {
endCopyPassIfActive(f);
endRenderPassIfActive(f);
if (!f.swapchainAcquiredThisFrame && !f.swapchainUnavailable && !f.skipPresent && f.commandBuffer != 0) {
ensureSwapchainAcquired(f);
}
if (f.commandBuffer != 0) {
Tracy.beginZone(Z_SDL_SUBMIT);
try {
@@ -538,13 +568,13 @@ public final class FrameManager {
f.commandBuffer = 0;
}
if (Tracy.ENABLED && resourceManager != null) SdlFramePlots.emit(f, resourceManager);
drainWindowPresentCounters(f);
statLoopFrames++;
if (f.swapchainAcquiredThisFrame) statPresentedFrames++;
statPresentSkips += f.presentSkipsThisFrame;
statEmptyFrames += f.emptyFramesThisFrame;
statAcquireWaitNanos += f.acquireWaitNanosThisFrame;
if (Tracy.ENABLED && resourceManager != null) {
SdlFramePlots.emit(f, resourceManager);
}
f.midFrameSubmitsThisFrame = 0;
f.lastPlottedRenderPassGen = f.renderPassGeneration;
f.computePassesThisFrame = 0;
@@ -563,6 +593,8 @@ public final class FrameManager {
f.stateAppliesThisFrame = 0;
f.acquireWaitNanosThisFrame = 0;
f.mipGensThisFrame = 0;
f.mipGenSubmitsThisFrame = 0;
f.uploadFlushSubmitsThisFrame = 0;
f.blitsThisFrame = 0;
f.clearPassesThisFrame = 0;
f.swapchainPassesThisFrame = 0;
@@ -577,9 +609,6 @@ public final class FrameManager {
f.computeBatchJoinsThisFrame = 0;
f.frameActive = false;
f.swapchainTexture = 0;
if (afterPresent != null) afterPresent.run();
}
public void submitMidFrame() {
@@ -603,6 +632,7 @@ public final class FrameManager {
Tracy.endZone();
}
f.submitsThisFrame++;
f.midFrameSubmitsThisFrame++;
f.commandBuffer = 0;
if (f.frameActive) {
reacquireCommandBuffer();
@@ -614,6 +644,7 @@ public final class FrameManager {
if (f.frameActive) {
endFrame();
}
presentFinalTarget();
beginFrame();
}
@@ -690,6 +721,7 @@ public final class FrameManager {
device.reportGpuFailure("submit pending upload command buffer");
}
f.submitsThisFrame++;
f.uploadFlushSubmitsThisFrame++;
f.pendingUploadCommandBuffer = 0;
f.pendingUploadBytes = 0;
f.pendingUploadCommands = 0;
@@ -724,22 +756,16 @@ public final class FrameManager {
public long getActiveLayoutHash(FrameState f) { return f.activeLayoutHash; }
public long getSwapchainTexture() {
final FrameState f = frame();
ensureSwapchainAcquired(f);
return f.swapchainTexture;
public long getFbo0Texture() {
return finalTarget.colorTexture();
}
public int getSwapchainWidth() {
final FrameState f = frame();
ensureSwapchainAcquired(f);
return f.swapchainWidth;
public int getFbo0Width() {
return finalTarget.width();
}
public int getSwapchainHeight() {
final FrameState f = frame();
ensureSwapchainAcquired(f);
return f.swapchainHeight;
public int getFbo0Height() {
return finalTarget.height();
}
public int getSwapchainFormat() {
@@ -774,8 +800,8 @@ public final class FrameManager {
return frame().frameNumber;
}
public boolean isSwapchainUsedThisFrame() {
return frame().swapchainUsedThisFrame;
public boolean isFbo0UsedThisFrame() {
return frame().fbo0UsedThisFrame;
}
public void reacquireCommandBuffer() {
@@ -788,24 +814,18 @@ public final class FrameManager {
f.currentDepthTarget = 0;
if (f.frameActive) {
final boolean wasAcquired = f.swapchainAcquiredThisFrame;
f.swapchainAcquiredThisFrame = false;
f.swapchainTexture = 0;
if (wasAcquired && !ensureSwapchainAcquired(f)) {
LOG.warn("Failed to re-acquire swapchain after readback: {}", SDLError.SDL_GetError());
}
f.clearedThisFrame = false;
}
}
public void releaseThreadState() {
final FrameState f = frame();
final FrameState f = tlFrame.get();
if (f == null) return;
if (resourceManager != null) resourceManager.flushUploadArena(f);
flushPendingUploadCommandBuffer(f);
releaseFrameStateResources(f);
registeredFrames.remove(f);
tlFrame.remove();
refreshSoleFrame();
registeredFrames.remove(f);
}
private void releaseFrameStateResources(FrameState f) {
@@ -843,23 +863,95 @@ public final class FrameManager {
}
public void releaseAllRegisteredFrames() {
for (FrameState f : registeredFrames) {
for (final FrameState f : registeredFrames.snapshot()) {
releaseFrameStateResources(f);
}
registeredFrames.clear();
soleFrame = null;
}
public boolean ensureSwapchainAcquired() {
return ensureSwapchainAcquired(frame());
public long lastFrameGateNanos() {
return frame().lastFrameGateNanos;
}
public boolean ensureSwapchainAcquired(FrameState f) {
if (f.swapchainAcquiredThisFrame) return true;
if (f.swapchainUnavailable) return false;
if (!f.frameActive || f.commandBuffer == 0) return false;
public long lastFrameGateEndNanos() {
return frame().lastFrameGateEndNanos;
}
endActiveEncoders(f);
private volatile Presenter presenter;
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
private final FrameState windowFrame = new FrameState();
public FrameState windowFrame() {
return windowFrame;
}
public void presentFinalTarget() {
if (!finalTarget.hasContent()) return;
present(finalTarget.colorTexture(), finalTarget.width(), finalTarget.height(), SDL_FLIP_NONE, false);
}
public void presentSplash(long srcTexture, int srcW, int srcH) {
present(srcTexture, srcW, srcH, SDL_FLIP_VERTICAL, true);
}
private void present(long srcTexture, int srcW, int srcH, int flipMode, boolean splash) {
final FrameState f = frame();
if (f.presentedThisFrame) return;
final Presenter p = presenter;
if (p != null) {
f.presentedThisFrame = true;
p.requestPresent(srcTexture, srcW, srcH, flipMode);
} else {
presentBlit(f, srcTexture, srcW, srcH, flipMode);
}
if (splash) f.presentedThisFrame = false;
}
private final AtomicLong windowAcquireWaitNanos = new AtomicLong();
private final AtomicInteger windowPresentSkips = new AtomicInteger();
private void drainWindowPresentCounters(FrameState f) {
if (f == windowFrame) return;
final long acquire = windowAcquireWaitNanos.getAndSet(0L);
if (acquire != 0L) {
f.acquireWaitNanosThisFrame += acquire;
f.lastFrameGateNanos = windowFrame.lastFrameGateNanos;
f.lastFrameGateEndNanos = windowFrame.lastFrameGateEndNanos;
}
f.presentSkipsThisFrame += windowPresentSkips.getAndSet(0);
}
private void noteAcquireWait(FrameState f, long waitNanos) {
if (f == windowFrame) windowAcquireWaitNanos.addAndGet(waitNanos);
else f.acquireWaitNanosThisFrame += waitNanos;
}
private void notePresentSkip(FrameState f) {
if (f == windowFrame) windowPresentSkips.incrementAndGet();
else f.presentSkipsThisFrame++;
}
public void presentOnWindowThread(long srcTexture, int srcW, int srcH, int flipMode) {
presentBlit(windowFrame, srcTexture, srcW, srcH, flipMode);
windowFrame.presentedThisFrame = false;
windowFrame.swapchainUnavailable = false;
}
public boolean presentBlit(FrameState f, long srcTexture, int srcW, int srcH, int flipMode) {
if (srcTexture == 0 || srcW <= 0 || srcH <= 0) return false;
if (f.presentedThisFrame || f.swapchainUnavailable) return false;
checkAcquireOnWindowThread();
final long window = device.getClaimedWindow();
if (window == 0) return false;
final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice());
if (cb == 0) return false;
final long t0 = System.nanoTime();
final long tex;
@@ -872,7 +964,7 @@ public final class FrameManager {
final IntBuffer pHeight = stack.ints(0);
Tracy.beginZone(Z_SDL_ACQUIRE_WAIT);
try {
callOk = SDL_WaitAndAcquireGPUSwapchainTexture(f.commandBuffer, Display.getWindow(), pTexture, pWidth, pHeight);
callOk = SDL_WaitAndAcquireGPUSwapchainTexture(cb, window, pTexture, pWidth, pHeight);
} finally {
Tracy.endZone();
}
@@ -880,25 +972,43 @@ public final class FrameManager {
w = pWidth.get(0);
h = pHeight.get(0);
} catch (RuntimeException re) {
f.acquireWaitNanosThisFrame += System.nanoTime() - t0;
SDL_CancelGPUCommandBuffer(cb);
f.swapchainUnavailable = true;
throw re;
}
f.acquireWaitNanosThisFrame += System.nanoTime() - t0;
final long tEnd = System.nanoTime();
f.lastFrameGateNanos = tEnd - t0;
f.lastFrameGateEndNanos = tEnd;
noteAcquireWait(f, tEnd - t0);
if (!callOk) {
if (!callOk || tex == 0) {
SDL_CancelGPUCommandBuffer(cb);
f.swapchainUnavailable = true;
notePresentSkip(f);
return false;
}
if (tex == 0) {
f.swapchainUnavailable = true;
f.presentSkipsThisFrame++;
try (MemoryStack stack = stackPush()) {
final long info = stack.ncalloc(SDL_GPUBlitInfo.ALIGNOF, 1, SDL_GPUBlitInfo.SIZEOF);
writeBlitRegion(info + SDL_GPUBlitInfo.SOURCE, srcTexture, srcW, srcH);
writeBlitRegion(info + SDL_GPUBlitInfo.DESTINATION, tex, w, h);
MemoryAccess.putInt(info + SDL_GPUBlitInfo.FILTER, SDL_GPU_FILTER_LINEAR);
MemoryAccess.putInt(info + SDL_GPUBlitInfo.FLIP_MODE, flipMode);
nSDL_BlitGPUTexture(cb, info);
}
if (!SDL_SubmitGPUCommandBuffer(cb)) {
device.reportGpuFailure("submit present blit");
return false;
}
f.swapchainTexture = tex;
f.swapchainWidth = w;
f.swapchainHeight = h;
f.swapchainAcquiredThisFrame = true;
f.presentedThisFrame = true;
if (afterPresent != null) afterPresent.run();
return true;
}
private static void writeBlitRegion(long region, long texture, int w, int h) {
MemoryAccess.putAddress(region + SDL_GPUBlitRegion.TEXTURE, texture);
MemoryAccess.putInt(region + SDL_GPUBlitRegion.W, w);
MemoryAccess.putInt(region + SDL_GPUBlitRegion.H, h);
}
}
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.sdlgpu.splash;
package com.gtnewhorizons.angelica.sdlgpu.frame;
import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.resource.FboState;
import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager;
import org.lwjgl.opengl.GL11;
@@ -9,13 +8,14 @@ import org.lwjgl.opengl.GL11;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_SAMPLER;
public final class SplashOffscreenTarget {
public final class OffscreenTarget {
private int fboGlId;
private int colorTexGlId;
private long colorTexHandle;
private int width;
private int height;
private boolean hasContent;
public void create(Device device, ResourceManager rm, int width, int height, int swapchainSdlFormat) {
this.width = width;
@@ -37,10 +37,20 @@ public final class SplashOffscreenTarget {
fbo.cachedFormatsDirty = true;
}
public void ensureSize(Device device, ResourceManager rm, int width, int height) {
if (width <= 0 || height <= 0) return;
if (colorTexHandle != 0 && width == this.width && height == this.height) return;
destroy(rm);
create(device, rm, width, height, device.getSwapchainTextureFormat());
}
public int fboId() { return fboGlId; }
public long colorTexture() { return colorTexHandle; }
public int width() { return width; }
public int height() { return height; }
public boolean isReady() { return colorTexHandle != 0; }
public boolean hasContent() { return hasContent; }
public void markContent() { hasContent = true; }
public boolean isFor(ContextState st) {
return fboGlId != 0 && st.boundFboId == fboGlId;
@@ -56,5 +66,6 @@ public final class SplashOffscreenTarget {
colorTexGlId = 0;
colorTexHandle = 0;
}
hasContent = false;
}
}
@@ -0,0 +1,38 @@
package com.gtnewhorizons.angelica.sdlgpu.frame;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;
public final class Presenter {
private final FrameManager frameManager;
private final Executor windowThreadExecutor;
private final Semaphore pending = new Semaphore(1);
public Presenter(FrameManager frameManager, Executor windowThreadExecutor) {
this.frameManager = frameManager;
this.windowThreadExecutor = windowThreadExecutor;
}
public void requestPresent(long srcTexture, int srcW, int srcH, int flipMode) {
pending.acquireUninterruptibly();
boolean submitted = false;
try {
windowThreadExecutor.execute(() -> {
try {
frameManager.presentOnWindowThread(srcTexture, srcW, srcH, flipMode);
} finally {
pending.release();
}
});
submitted = true;
} finally {
if (!submitted) pending.release();
}
}
public void drain() {
pending.acquireUninterruptibly();
pending.release();
}
}
@@ -40,6 +40,8 @@ final class SdlFramePlots {
private static final long PLOT_PRESENT_TO_PRESENT_US = Tracy.plotHandle("sdl.presentToPresentUs");
private static final long PLOT_FRAMES_IN_FLIGHT = Tracy.plotHandle("sdl.framesInFlight");
private static final long PLOT_MIP_GENS = Tracy.plotHandle("sdl.mipGens");
private static final long PLOT_MIP_GEN_SUBMITS = Tracy.plotHandle("sdl.mipGenSubmits");
private static final long PLOT_UPLOAD_FLUSH_SUBMITS = Tracy.plotHandle("sdl.uploadFlushSubmits");
private static final long PLOT_BLIT_FALLBACKS = Tracy.plotHandle("sdl.blitFallbacks");
private static final long PLOT_PRESENT_SKIPS = Tracy.plotHandle("sdl.presentSkips");
private static final long PLOT_EMPTY_FRAMES = Tracy.plotHandle("sdl.emptyFrames");
@@ -54,6 +56,7 @@ final class SdlFramePlots {
private static final long PLOT_BUFFER_POOL_HITS = Tracy.plotHandle("sdl.bufferPoolHits");
private static final long PLOT_PIPELINE_KEY_RECOMPUTES = Tracy.plotHandle("sdl.pipelineKeyRecomputes");
private static final long PLOT_PIPELINE_FAST_PATH_HITS = Tracy.plotHandle("sdl.pipelineFastPathHits");
private static final long PLOT_MID_FRAME_SUBMITS = Tracy.plotHandle("sdl.midFrameSubmits");
private static final int[] contextCounters = new int[SDLGPURenderBackend.CTR_COUNT];
@@ -99,9 +102,12 @@ final class SdlFramePlots {
f.lastEndFrameNanos = nowNanos;
Tracy.plotInt(PLOT_FRAMES_IN_FLIGHT, Device.framesInFlight());
Tracy.plotInt(PLOT_MIP_GENS, f.mipGensThisFrame);
Tracy.plotInt(PLOT_MIP_GEN_SUBMITS, f.mipGenSubmitsThisFrame);
Tracy.plotInt(PLOT_UPLOAD_FLUSH_SUBMITS, f.uploadFlushSubmitsThisFrame);
Tracy.plotInt(PLOT_BLIT_FALLBACKS, f.blitsThisFrame);
Tracy.plotInt(PLOT_PRESENT_SKIPS, f.presentSkipsThisFrame);
Tracy.plotInt(PLOT_EMPTY_FRAMES, f.emptyFramesThisFrame);
Tracy.plotInt(PLOT_DROPPED_DRAWS, f.droppedDrawsThisFrame);
Tracy.plotInt(PLOT_MID_FRAME_SUBMITS, f.midFrameSubmitsThisFrame);
}
}
@@ -109,7 +109,7 @@ public final class PipelineApplier {
}
if (st.boundFboId == 0) {
if (frameManager.ensureSwapchainRenderPass(f, st)) {
if (frameManager.ensureFbo0RenderPass(f, st)) {
st.pipeline.setDepthTargetFormat(resourceManager.getSwapchainDepthStencilFormat());
}
return;
@@ -64,7 +64,7 @@ public final class FboState {
h = Hashing.fmix64(h, db);
}
h = Hashing.fmix64(h, depthTexture);
if (h == 0L || h == FrameManager.SWAPCHAIN_LAYOUT_HASH) h = 0xD1CE5EEDL;
if (h == 0L || h == FrameManager.FBO0_LAYOUT_HASH) h = 0xD1CE5EEDL;
structuralLayoutHash = h;
}
@@ -587,7 +587,7 @@ public final class ResourceManager {
final GpuBucket b = gpuBufferPool.get(Hashing.packHiLo(usage, bucket));
if (b == null || b.handles.isEmpty()) return 0;
for (int i = 0, n = b.handles.size(); i < n; i++) {
if (gpuPoolCurrentFrame - b.frames.getLong(i) >= Device.framesInFlight()) {
if (gpuPoolCurrentFrame - b.frames.getLong(i) >= Device.MAX_FRAMES_IN_FLIGHT) {
final long handle = b.handles.getLong(i);
final int last = n - 1;
if (i != last) {
@@ -1376,7 +1376,7 @@ public final class ResourceManager {
for (int i = 0; i < n; i += 2) {
final long handle = batchSegmentPending.getLong(i);
final long stamp = batchSegmentPending.getLong(i + 1);
if (currentFrame - stamp >= Device.framesInFlight()) {
if (currentFrame - stamp >= Device.MAX_FRAMES_IN_FLIGHT) {
batchSegmentFree.enqueue(handle);
} else {
batchSegmentPending.set(w, handle);
@@ -101,19 +101,11 @@ public final class TextureOps {
public void readbackTexture(long texHandle, int x, int y, int w, int h, int level, ByteBuffer output) {
if (texHandle == 0 || output == null) return;
frameManager.endCopyPassIfActive();
frameManager.endRenderPassIfActive();
frameManager.submitMidFrame();
if (texHandle == frameManager.getSwapchainTexture()) {
final long cb = frameManager.getCommandBuffer();
if (cb == 0) return;
resourceManager.downloadFromTexture(cb, texHandle, x, y, w, h, level, output);
frameManager.reacquireCommandBuffer();
} else {
final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice());
if (cb == 0) return;
resourceManager.downloadFromTexture(cb, texHandle, x, y, w, h, level, output);
}
final long cb = SDL_AcquireGPUCommandBuffer(device.getDevice());
if (cb == 0) return;
resourceManager.downloadFromTexture(cb, texHandle, x, y, w, h, level, output);
}
public void copyTexSubImageImpl(ContextState st, int destGlId, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
@@ -210,6 +202,7 @@ public final class TextureOps {
if (!SDL_SubmitGPUCommandBuffer(uploadCb)) {
device.reportGpuFailure("submit mipmap generation CB");
}
frameManager.noteMipGenSubmit();
if (f.commandBuffer == uploadCb) {
f.commandBuffer = 0;
@@ -31,11 +31,6 @@ public final class PerFrameBlockInjector {
private PerFrameBlockInjector() {}
public static String inject(String source, PerFrameUniformBlock perFrame, PerFrameUniformBlock perPass) {
final PerFrameUniformBlock[] blocks = new PerFrameUniformBlock[ShaderManager.BLOCK_COUNT];
blocks[ShaderManager.BLOCK_PER_FRAME] = normalize(perFrame);
blocks[ShaderManager.BLOCK_PER_PASS] = normalize(perPass);
if (blocks[0] == null && blocks[1] == null) return source;
final GLSLParser.Translation_unitContext root;
try {
root = GlslTransformUtils.parseFullQuiet(source);
@@ -43,8 +38,19 @@ public final class PerFrameBlockInjector {
return source;
}
final List<Edit> edits = new ArrayList<>();
collectEdits(root, perFrame, perPass, edits);
return edits.isEmpty() ? source : applyEdits(source, edits);
}
public static void collectEdits(GLSLParser.Translation_unitContext root, PerFrameUniformBlock perFrame, PerFrameUniformBlock perPass, List<Edit> out) {
final PerFrameUniformBlock[] blocks = new PerFrameUniformBlock[ShaderManager.BLOCK_COUNT];
blocks[ShaderManager.BLOCK_PER_FRAME] = normalize(perFrame);
blocks[ShaderManager.BLOCK_PER_PASS] = normalize(perPass);
if (blocks[0] == null && blocks[1] == null) return;
final int insertAt = firstDeclarationStart(root);
if (insertAt < 0) return source;
if (insertAt < 0) return;
final Map<String, String> memberTypes = new LinkedHashMap<>();
final Object2IntOpenHashMap<String> memberBlock = new Object2IntOpenHashMap<>();
@@ -71,18 +77,16 @@ public final class PerFrameBlockInjector {
if (referenced.contains(m.name())) { injected[b] = true; anyInjected = true; break; }
}
}
if (!anyInjected) return source;
if (!anyInjected) return;
final List<Edit> edits = new ArrayList<>(stripEdits.size() + 2);
final StringBuilder blockDecls = new StringBuilder(128);
for (int b = 0; b < blocks.length; b++) {
if (injected[b]) appendBlockText(blockDecls, b, blocks[b].members(), shadowed);
}
edits.add(new Edit(insertAt, insertAt - 1, blockDecls.toString()));
out.add(new Edit(insertAt, insertAt - 1, blockDecls.toString()));
for (int i = 0; i < stripEdits.size(); i++) {
if (injected[stripBlocks.getInt(i)]) edits.add(stripEdits.get(i));
if (injected[stripBlocks.getInt(i)]) out.add(stripEdits.get(i));
}
return applyEdits(source, edits);
}
private static PerFrameUniformBlock normalize(PerFrameUniformBlock block) {
@@ -188,19 +188,46 @@ public final class ShaderManager {
return new PrewarmTransformResult(transformedSource, Set.of());
}
final List<Edit> edits = new ArrayList<>();
if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) {
PerFrameBlockInjector.collectEdits(root, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock, edits);
}
final GlslVulkanPreprocess.Metadata meta = GlslVulkanPreprocess.collectEdits(transformedSource, root, glShaderType, "prewarm", true, edits);
if (glShaderType == GL20.GL_VERTEX_SHADER) {
ClipZRemap.collectEdits(root, edits);
}
SamplerStripper.collectEdits(root, transformedSource, edits);
String s = edits.isEmpty() ? transformedSource : GlslVulkanPreprocess.applyEdits(transformedSource, edits);
if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) {
s = PerFrameBlockInjector.inject(s, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock);
}
final String s = edits.isEmpty() ? transformedSource : GlslVulkanPreprocess.applyEdits(transformedSource, edits);
return new PrewarmTransformResult(s, meta.boolUniforms());
}
public static PrewarmTransformResult applyPrewarmTransformsFull(String finalSource, GLSLParser.Translation_unitContext bodyTree, int headerLen, int glShaderType) {
final String header = finalSource.substring(0, headerLen);
final String body = finalSource.substring(headerLen);
final List<Edit> edits = new ArrayList<>();
if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) {
PerFrameBlockInjector.collectEdits(bodyTree, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock, edits);
}
final GlslVulkanPreprocess.Metadata meta = GlslVulkanPreprocess.collectEdits(null, bodyTree, glShaderType, "prewarm", true, edits);
if (glShaderType == GL20.GL_VERTEX_SHADER) {
ClipZRemap.collectEdits(bodyTree, edits);
}
SamplerStripper.collectEdits(bodyTree, body, edits);
String outHeader = header;
if (meta.needsSamplerless()) {
final int nl = header.indexOf('\n');
outHeader = header.substring(0, nl) + "\n" + GlslVulkanPreprocess.SAMPLERLESS_EXTENSION + header.substring(nl);
}
if (edits.isEmpty() && outHeader == header) {
return new PrewarmTransformResult(finalSource, meta.boolUniforms());
}
return new PrewarmTransformResult(outHeader + GlslVulkanPreprocess.applyEdits(body, edits), meta.boolUniforms());
}
public static void prewarmSpirv(String transformedSource, int glShaderType) {
prewarmSpirv(transformedSource, null, 0, glShaderType);
}
public static void prewarmSpirv(String transformedSource, GLSLParser.Translation_unitContext bodyTree, int headerLen, int glShaderType) {
if (glShaderType != GL20.GL_VERTEX_SHADER && glShaderType != GL20.GL_FRAGMENT_SHADER
&& glShaderType != GL43.GL_COMPUTE_SHADER && glShaderType != GL32.GL_GEOMETRY_SHADER) {
return;
@@ -211,7 +238,9 @@ public final class ShaderManager {
if (PREWARM_CACHE.containsKey(key)) return;
}
final PrewarmTransformResult pre = applyPrewarmTransformsFull(transformedSource, glShaderType);
final PrewarmTransformResult pre = bodyTree != null
? applyPrewarmTransformsFull(transformedSource, bodyTree, headerLen, glShaderType)
: applyPrewarmTransformsFull(transformedSource, glShaderType);
final SpirvCompiler.Result r = SpirvCompiler.compile(pre.source(), shaderKindFor(glShaderType), "prewarm", SpirvCompiler.Options.vulkanForced460Core());
if (r.spirv() == null) return;
@@ -652,7 +681,7 @@ public final class ShaderManager {
return null;
}
LOG.info("Vertex attribute conversion: program {} converted {}", program, attribs);
if (SystemProperties.DUMP_SHADERS) dumpVariantSource(program, src);
if (SystemProperties.dumpShaders()) dumpVariantSource(program, src);
return v;
} finally {
memFree(r.spirv());
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess.Edit;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.taumc.glsl.grammar.GLSLParser;
@@ -18,11 +19,29 @@ public final class UscaledRetype {
public record Attrib(String name, int location, int declVecSize, int boundVecSize, boolean signed) {}
private record RetypeKey(String source, List<Attrib> attribs) {}
private static final int CACHE_MAX = 64;
private static final Object2ObjectLinkedOpenHashMap<RetypeKey, String> CACHE = new Object2ObjectLinkedOpenHashMap<>();
private UscaledRetype() {}
public static String retype(String source, List<Attrib> attribs) {
if (attribs.isEmpty()) return source;
final RetypeKey key = new RetypeKey(source, List.copyOf(attribs));
synchronized (CACHE) {
if (CACHE.containsKey(key)) return CACHE.getAndMoveToFirst(key);
}
final String result = retypeUncached(source, attribs);
synchronized (CACHE) {
CACHE.putAndMoveToFirst(key, result);
while (CACHE.size() > CACHE_MAX) CACHE.removeLast();
}
return result;
}
private static String retypeUncached(String source, List<Attrib> attribs) {
final GLSLParser.Translation_unitContext root;
try {
root = GlslTransformUtils.parseFullQuiet(source);
@@ -80,7 +80,7 @@ public final class DxbcCrossCompile {
return new Output(copy, cached.entrypoint);
}
final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
final int dumpId = SystemProperties.dumpShaders() ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType);
final String hlsl = compileToHlsl(spirv, glShaderType);
@@ -87,7 +87,7 @@ public final class MslCrossCompile {
return new Output(copy, cached.entrypoint);
}
final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
final int dumpId = SystemProperties.dumpShaders() ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType);
try (MemoryStack stack = stackPush()) {
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.sdlgpu.splash;
import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend;
import com.gtnewhorizons.angelica.sdlgpu.frame.OffscreenTarget;
public final class SplashDispatcher {
@@ -32,10 +33,10 @@ public final class SplashDispatcher {
return (long) w << 32 | (h & 0xffffffffL);
}
public static void tryDispatch(SDLGPURenderBackend backend, SplashOffscreenTarget target) {
public static void tryDispatch(SDLGPURenderBackend backend, OffscreenTarget target, boolean force) {
if (!frameReady || target == null) return;
final long now = System.nanoTime();
if (now - lastBlitNanos < MIN_INTERVAL_NS) return;
if (!force && now - lastBlitNanos < MIN_INTERVAL_NS) return;
lastBlitNanos = now;
frameReady = false;
backend.dispatchSplashBlit(target);
@@ -0,0 +1,67 @@
package com.gtnewhorizons.angelica.sdlgpu.util;
import java.util.Arrays;
public final class ThreadRegistry<T> {
private final T[] empty;
private final Object lock = new Object();
private volatile T[] entries;
private volatile T sole;
public ThreadRegistry(T[] empty) {
this.empty = empty;
this.entries = empty;
}
public T sole() {
return sole;
}
public T[] snapshot() {
return entries;
}
public int size() {
return entries.length;
}
public void add(T entry) {
synchronized (lock) {
final T[] prev = entries;
final T[] next = Arrays.copyOf(prev, prev.length + 1);
next[prev.length] = entry;
publish(next);
}
}
public boolean remove(T entry) {
synchronized (lock) {
final T[] prev = entries;
int idx = -1;
for (int i = 0; i < prev.length; i++) {
if (prev[i] == entry) {
idx = i;
break;
}
}
if (idx < 0) return false;
final T[] next = Arrays.copyOf(prev, prev.length - 1);
System.arraycopy(prev, idx + 1, next, idx, prev.length - idx - 1);
publish(next);
}
return true;
}
public void clear() {
synchronized (lock) {
publish(empty);
}
}
private void publish(T[] next) {
entries = next;
sole = next.length == 1 ? next[0] : null;
}
}
@@ -7,7 +7,6 @@ import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -15,17 +14,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class ImageUnitBindingStateTest {
@SuppressWarnings("unchecked")
private static ContextState state() throws Exception {
final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState");
f.setAccessible(true);
return ((ThreadLocal<ContextState>) f.get(null)).get();
}
@Test
void bindImageTextureRecordsTheFullTuple() throws Exception {
void bindImageTextureRecordsTheFullTuple() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.bindImageTexture(2, 77, 3, true, 5, GL15.GL_READ_WRITE, GL30.GL_R32UI);
@@ -38,7 +31,7 @@ class ImageUnitBindingStateTest {
}
@Test
void getIntegerIndexedAnswersImageBindingsFromState() throws Exception {
void getIntegerIndexedAnswersImageBindingsFromState() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
backend.bindImageTexture(1, 42, 2, false, 4, GL15.GL_READ_ONLY, GL30.GL_RGBA32UI);
@@ -52,9 +45,9 @@ class ImageUnitBindingStateTest {
}
@Test
void outOfRangeUnitIsIgnored() throws Exception {
void outOfRangeUnitIsIgnored() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.bindImageTexture(0, 11, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI);
backend.bindImageTexture(ContextState.MAX_IMAGE_UNITS, 99, 0, true, 0, GL15.GL_READ_ONLY, GL30.GL_R32UI);
@@ -0,0 +1,17 @@
package com.gtnewhorizons.angelica.sdlgpu;
import com.mitchej123.lwjgl.LWJGLService;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
class SDLGPULWJGLServiceGatingTest {
@Test
void anUnengagedSdlDeclinesAndNeverArmsTheFallbackTripwire() {
assertFalse(SDLGPUGate.isEngaged(), "test JVM must not have an engaged SDL GPU device");
assertEquals(LWJGLService.PRIORITY_UNAVAILABLE, new SDLGPULWJGLService().getPriority());
assertFalse(SDLGPULWJGLService.isOfferedAsAvailable(), "declining must leave fallBackToGL() usable");
}
}
@@ -1,6 +1,8 @@
package com.gtnewhorizons.angelica.sdlgpu;
import com.gtnewhorizons.angelica.glsm.testutil.Reflect;
import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager;
import com.gtnewhorizons.angelica.sdlgpu.resource.ResourceManager;
import org.lwjgl.sdl.SDLError;
@@ -57,6 +59,10 @@ public final class SdlTestRig {
return create().frameManager;
}
public static ContextState contextState() {
return Reflect.invokeStatic(SDLGPURenderBackend.class, "s", new Class<?>[0]);
}
private static long realSdlDevice;
private static final int SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL;
@@ -48,13 +48,6 @@ class UniformNegativeLocationTest {
st.releaseUniformStaging(prog);
}
@SuppressWarnings("unchecked")
private static ContextState threadState() throws Exception {
final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState");
f.setAccessible(true);
return ((ThreadLocal<ContextState>) f.get(null)).get();
}
private static void clearApplier(SDLGPURenderBackend backend) throws Exception {
final Field f = SDLGPURenderBackend.class.getDeclaredField("pipelineApplier");
f.setAccessible(true);
@@ -66,7 +59,7 @@ class UniformNegativeLocationTest {
void scalarAndVectorEntryPointsNeverReachTheApplier() throws Exception {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
clearApplier(backend);
threadState().boundProgramObj = null;
SdlTestRig.contextState().boundProgramObj = null;
final IntBuffer iv = MemoryUtil.memAllocInt(4);
try {
@@ -6,13 +6,13 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import com.gtnewhorizons.angelica.sdlgpu.util.ThreadRegistry;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ContextCounterAggregationTest {
private List<ContextState> registered;
private ThreadRegistry<ContextState> registered;
private ContextState a;
private ContextState b;
@@ -0,0 +1,113 @@
package com.gtnewhorizons.angelica.sdlgpu.frame;
import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_NONE;
@Timeout(10)
class PresenterTest {
private static final class DeferredExecutor implements Executor {
final Deque<Runnable> tasks = new ArrayDeque<>();
@Override
public void execute(Runnable command) {
tasks.add(command);
}
void runNext() {
tasks.removeFirst().run();
}
}
private static Presenter presenter(DeferredExecutor executor) {
return new Presenter(new FrameManager(new Device()), executor);
}
private static void awaitWaiting(Thread t) throws InterruptedException {
while (t.getState() != Thread.State.WAITING && t.getState() != Thread.State.TIMED_WAITING) {
assertTrue(t.isAlive(), "thread died instead of blocking");
Thread.onSpinWait();
}
}
@Test
void aSecondRequestBlocksUntilTheFirstPresentRuns() throws Exception {
final DeferredExecutor executor = new DeferredExecutor();
final Presenter p = presenter(executor);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
assertEquals(1, executor.tasks.size());
final Thread second = new Thread(() -> p.requestPresent(2L, 10, 10, SDL_FLIP_NONE));
second.start();
awaitWaiting(second);
assertEquals(1, executor.tasks.size(), "second present must not enqueue while the first is in flight");
executor.runNext();
second.join();
assertEquals(1, executor.tasks.size(), "second present enqueues only after the first released the slot");
}
@Test
void drainBlocksUntilThePendingPresentCompletes() throws Exception {
final DeferredExecutor executor = new DeferredExecutor();
final Presenter p = presenter(executor);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
final Thread drainer = new Thread(p::drain);
drainer.start();
awaitWaiting(drainer);
executor.runNext();
drainer.join();
}
@Test
void anInlineExecutorReleasesTheSlotImmediately() {
final Presenter p = new Presenter(new FrameManager(new Device()), Runnable::run);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(2L, 10, 10, SDL_FLIP_NONE);
p.drain();
}
@Test
void presentingDoesNotEnterTheFrameRegistry() throws Exception {
final DeferredExecutor executor = new DeferredExecutor();
final FrameManager fm = new FrameManager(new Device());
final Presenter p = new Presenter(fm, executor);
fm.frame();
final int before = fm.registeredFrameCount();
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
final Thread windowThread = new Thread(executor::runNext, "window-thread");
windowThread.start();
windowThread.join();
assertEquals(before, fm.registeredFrameCount(), "the window thread must stay out of the frame registry");
}
@Test
void theSplashPresentGoesThroughTheWindowThreadToo() {
final DeferredExecutor executor = new DeferredExecutor();
final FrameManager fm = new FrameManager(new Device());
fm.setPresenter(new Presenter(fm, executor));
fm.frame();
final int before = fm.registeredFrameCount();
fm.presentSplash(1L, 10, 10);
assertEquals(1, executor.tasks.size(), "the splash blit must be enqueued on the window thread");
assertEquals(before, fm.registeredFrameCount(), "the splash present must not touch the calling thread's frame");
}
}
@@ -8,13 +8,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class SwapchainClearPassBreakTest {
private static final long SWAPCHAIN = 0x5A1CL;
private static FrameManager.FrameState activeSwapchainPass() {
private static FrameManager.FrameState activeFbo0Pass() {
final FrameManager.FrameState f = new FrameManager.FrameState();
f.swapchainTexture = SWAPCHAIN;
f.renderPass = 0xBEEFL;
f.currentColorTarget = SWAPCHAIN;
f.activeLayoutHash = FrameManager.FBO0_LAYOUT_HASH;
return f;
}
@@ -22,23 +19,23 @@ class SwapchainClearPassBreakTest {
void aPendingColorClearBreaksTheActivePass() {
final ContextState st = new ContextState();
st.pendingSwapchainClear = true;
assertTrue(swapchainClearNeedsPassBreak(st, activeSwapchainPass()), "otherwise the clear is deferred to the next pass and wipes what this one drew");
assertTrue(swapchainClearNeedsPassBreak(st, activeFbo0Pass()), "otherwise the clear is deferred to the next pass and wipes what this one drew");
}
@Test
void aPendingDepthOrStencilClearBreaksTheActivePass() {
final ContextState depth = new ContextState();
depth.pendingSwapchainDepthClear = true;
assertTrue(swapchainClearNeedsPassBreak(depth, activeSwapchainPass()));
assertTrue(swapchainClearNeedsPassBreak(depth, activeFbo0Pass()));
final ContextState stencil = new ContextState();
stencil.pendingSwapchainStencilClear = true;
assertTrue(swapchainClearNeedsPassBreak(stencil, activeSwapchainPass()));
assertTrue(swapchainClearNeedsPassBreak(stencil, activeFbo0Pass()));
}
@Test
void nothingPendingLeavesThePassAlone() {
assertFalse(swapchainClearNeedsPassBreak(new ContextState(), activeSwapchainPass()));
assertFalse(swapchainClearNeedsPassBreak(new ContextState(), activeFbo0Pass()));
}
@Test
@@ -46,18 +43,18 @@ class SwapchainClearPassBreakTest {
final ContextState st = new ContextState();
st.pendingSwapchainClear = true;
final FrameManager.FrameState f = activeSwapchainPass();
final FrameManager.FrameState f = activeFbo0Pass();
f.renderPass = 0;
assertFalse(swapchainClearNeedsPassBreak(st, f));
}
@Test
void aPassBoundToAnFboIsNotTheSwapchainPass() {
void aPassBoundToAnFboIsNotTheFbo0Pass() {
final ContextState st = new ContextState();
st.pendingSwapchainClear = true;
final FrameManager.FrameState f = activeSwapchainPass();
f.currentColorTarget = 0xF80L;
final FrameManager.FrameState f = activeFbo0Pass();
f.activeLayoutHash = 0xF80L;
assertFalse(swapchainClearNeedsPassBreak(st, f));
}
}
@@ -0,0 +1,58 @@
package com.gtnewhorizons.angelica.sdlgpu.resource;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.frame.FrameManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.lwjgl.opengl.GL11;
import java.nio.ByteBuffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_TEXTUREUSAGE_SAMPLER;
import static org.lwjgl.system.MemoryUtil.memAlloc;
import static org.lwjgl.system.MemoryUtil.memFree;
@Timeout(60)
class ReadbackSubmitOrderGpuTest {
private static final int SIZE = 4;
@AfterAll
static void releaseDevice() {
SdlTestRig.releaseRealDevice();
}
@Test
void aReadbackSubmitsTheFramesWritesFirst() throws Exception {
final SdlTestRig rig = SdlTestRig.acquireRealDevice();
final ResourceManager rm = rig.resourceManager;
final FrameManager fm = rig.frameManager;
final TextureOps textureOps = new TextureOps(rig.device, fm, rm, null);
final int glId = rm.genTexture();
final long texture = rm.createTexture(glId, GL11.GL_TEXTURE_2D, GL11.GL_RGBA8, SIZE, SIZE, 1, 1, SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET);
assertNotEquals(0L, texture, "texture creation failed");
fm.beginFrame();
final FrameManager.FrameState f = fm.frame();
final long frameCb = f.commandBuffer;
assertNotEquals(0L, frameCb, "no frame command buffer to order against");
assertEquals(0, f.midFrameSubmitsThisFrame);
final ByteBuffer out = memAlloc(SIZE * SIZE * 4);
try {
textureOps.readbackTexture(texture, 0, 0, SIZE, SIZE, 0, out);
} finally {
memFree(out);
}
assertEquals(1, f.midFrameSubmitsThisFrame, "the frame command buffer must be submitted before the download buffer, or the readback sees stale contents");
assertNotEquals(frameCb, f.commandBuffer, "the frame must continue on a freshly acquired command buffer");
fm.endFrame();
}
}
@@ -1,29 +1,23 @@
package com.gtnewhorizons.angelica.sdlgpu.sampler;
import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class SamplerBindGenerationTest {
@SuppressWarnings("unchecked")
private static ContextState state() throws Exception {
final Field f = SDLGPURenderBackend.class.getDeclaredField("tlState");
f.setAccessible(true);
return ((ThreadLocal<ContextState>) f.get(null)).get();
}
@Test
void switchingActiveUnitDoesNotBumpTheGeneration() throws Exception {
void switchingActiveUnitDoesNotBumpTheGeneration() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.activeTexture(GL13.GL_TEXTURE0);
final int before = st.samplerBindGen;
@@ -37,9 +31,9 @@ class SamplerBindGenerationTest {
}
@Test
void aRealBindChangeBumpsTheGeneration() throws Exception {
void aRealBindChangeBumpsTheGeneration() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.activeTexture(GL13.GL_TEXTURE0);
backend.bindTexture(GL11.GL_TEXTURE_2D, 0);
@@ -50,9 +44,9 @@ class SamplerBindGenerationTest {
}
@Test
void rebindingTheSameTextureDoesNotBumpTheGeneration() throws Exception {
void rebindingTheSameTextureDoesNotBumpTheGeneration() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.activeTexture(GL13.GL_TEXTURE0);
backend.bindTexture(GL11.GL_TEXTURE_2D, 99);
@@ -63,9 +57,9 @@ class SamplerBindGenerationTest {
}
@Test
void bindingsAreHeldPerUnitSoTheActiveUnitIsNotSamplerState() throws Exception {
void bindingsAreHeldPerUnitSoTheActiveUnitIsNotSamplerState() {
final SDLGPURenderBackend backend = new SDLGPURenderBackend();
final ContextState st = state();
final ContextState st = SdlTestRig.contextState();
backend.activeTexture(GL13.GL_TEXTURE2);
backend.bindTexture(GL11.GL_TEXTURE_2D, 55);
@@ -0,0 +1,76 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler;
import com.gtnewhorizons.angelica.glsm.testutil.TestPaths;
import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerLookup;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL20;
import org.lwjgl.util.shaderc.Shaderc;
import java.nio.ByteBuffer;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.system.MemoryUtil.memFree;
class FontFilterVertexSamplerTest {
private static final String FONT_FILTER_VSH = TestPaths.readString("src/main/resources/assets/angelica/shaders/fontFilter.vsh");
private static String runSdlPipeline(String raw) {
final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, GL20.GL_VERTEX_SHADER, "fontFilter.vsh", true);
String src = pre != null ? pre.rewrittenSource() : raw;
src = ClipZRemap.injectGLToVulkanClipZ(src);
src = SamplerStripper.stripUnused(src);
return src;
}
private static ShaderManager.StageReflection reflect(String source) {
final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_vertex_shader,
"fontFilter.vsh", SpirvCompiler.Options.vulkanForced460Core());
assertNotNull(r.spirv(), () -> "fontFilter.vsh failed to compile for Vulkan: " + r.error());
final ByteBuffer spirv = r.spirv();
try {
return ShaderManager.reflectStage(spirv, true);
} finally {
memFree(spirv);
}
}
@Test
void samplerSurvivesStrippingAndReflectsOnTheVertexStage() {
final String transformed = runSdlPipeline(FONT_FILTER_VSH);
assertTrue(transformed.contains("uniform sampler2D lightmap"), "a reference inside a runtime if must keep the declaration; only preprocessor #if hides it");
final List<String> samplers = reflect(transformed).samplerNames();
assertEquals(List.of("lightmap"), samplers, "the vertex stage must expose exactly the lightmap sampler");
}
@Test
void looseVec3UniformReflectsWithAStd140Offset() {
final List<ShaderManager.UboMember> members = reflect(runSdlPipeline(FONT_FILTER_VSH)).uboMembers();
final ShaderManager.UboMember lightmap = members.stream()
.filter(m -> m.name().endsWith("u_Lightmap"))
.findFirst()
.orElseThrow(() -> new AssertionError("u_Lightmap missing from the default uniform block: " + members));
assertEquals(3, lightmap.vectorSize(), "u_Lightmap must reflect as a 3-wide vector");
assertEquals(1, lightmap.columns(), "u_Lightmap is a vector, not a matrix");
assertEquals(0, lightmap.arrayStride(), "a scalar member takes Std140Writer's contiguous path");
assertEquals(0, lightmap.offset() % 16, "std140 aligns a vec3 to 16 bytes");
}
@Test
void samplerNamedLightmapResolvesToTextureUnitOne() {
final List<String> samplers = reflect(runSdlPipeline(FONT_FILTER_VSH)).samplerNames();
final Object2IntOpenHashMap<String> noExplicitUnits = new Object2IntOpenHashMap<>();
noExplicitUnits.defaultReturnValue(-1);
assertEquals(1, SamplerLookup.getSamplerTextureUnit(samplers, noExplicitUnits, 0), "even without a glUniform1i the SDL fallback must put a sampler named 'lightmap' on unit 1");
}
}
@@ -1,15 +1,28 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock;
import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.lwjgl.opengl.GL43;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PrewarmSingleParseEquivalenceTest {
@AfterEach
void clearBlocks() {
GLSMHooks.perFrameUniformBlock = null;
GLSMHooks.perPassUniformBlock = null;
}
private static String legacy(String source, int glShaderType) {
final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(source, glShaderType, "test", true);
String src = pre != null ? pre.rewrittenSource() : source;
@@ -17,6 +30,9 @@ class PrewarmSingleParseEquivalenceTest {
src = ClipZRemap.injectGLToVulkanClipZ(src);
}
src = SamplerStripper.stripUnused(src);
if (glShaderType == GL20.GL_VERTEX_SHADER || glShaderType == GL20.GL_FRAGMENT_SHADER) {
src = PerFrameBlockInjector.inject(src, GLSMHooks.perFrameUniformBlock, GLSMHooks.perPassUniformBlock);
}
return src;
}
@@ -28,6 +44,14 @@ class PrewarmSingleParseEquivalenceTest {
assertEquals(legacyOut, parseOnceOut, "single-parse vs chained pipeline diverged for " + label);
}
private static void assertEquivalentIgnoringWhitespace(String label, String source, int glShaderType) {
GlslVulkanPreprocess.clearCache();
final String legacyOut = legacy(source, glShaderType);
GlslVulkanPreprocess.clearCache();
final String parseOnceOut = ShaderManager.applyPrewarmTransforms(source, glShaderType);
assertEquals(legacyOut.replaceAll("\\s+", " "), parseOnceOut.replaceAll("\\s+", " "), "single-parse vs chained pipeline diverged beyond whitespace for " + label);
}
@Test
void minimalFragment_noTransformsNeeded() {
final String src = "#version 460 core\n"
@@ -135,4 +159,87 @@ class PrewarmSingleParseEquivalenceTest {
final String src = "this is not valid GLSL @@@@\n";
assertEquivalent("unparseable", src, GL20.GL_FRAGMENT_SHADER);
}
private static final PerFrameUniformBlock PER_FRAME = new PerFrameUniformBlock(List.of(
new Member("cameraPosition", UniformType.VEC3),
new Member("frameTimeCounter", UniformType.FLOAT)));
private static final PerFrameUniformBlock PER_PASS = new PerFrameUniformBlock(List.of(
new Member("alphaTestRef", UniformType.FLOAT)));
@Test
void perFrameBlock_replaceableUniformStrippedAndInjected() {
GLSMHooks.perFrameUniformBlock = PER_FRAME;
GLSMHooks.perPassUniformBlock = PER_PASS;
final String src = "#version 460 core\n"
+ "uniform float frameTimeCounter;\n"
+ "uniform float alphaTestRef;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() {\n"
+ " if (fragColor.a < alphaTestRef) discard;\n"
+ " fragColor = vec4(frameTimeCounter);\n"
+ "}\n";
assertEquivalent("pfb-replaceable", src, GL20.GL_FRAGMENT_SHADER);
}
@Test
void perFrameBlock_firstDeclIsUnlocatedVsInput() {
GLSMHooks.perFrameUniformBlock = PER_FRAME;
final String src = "#version 460 core\n"
+ "in vec3 a_Position;\n"
+ "layout(location = 5) in vec2 a_TexCoord;\n"
+ "uniform vec3 cameraPosition;\n"
+ "void main() {\n"
+ " gl_Position = vec4(a_Position - cameraPosition, 1.0);\n"
+ "}\n";
assertEquivalent("pfb-unlocated-first-in", src, GL20.GL_VERTEX_SHADER);
}
@Test
void perFrameBlock_memberUniformWithInitializer() {
GLSMHooks.perPassUniformBlock = PER_PASS;
final String src = "#version 460 core\n"
+ "uniform float alphaTestRef = 0.1;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() {\n"
+ " if (fragColor.a < alphaTestRef) discard;\n"
+ "}\n";
assertEquivalent("pfb-initializer", src, GL20.GL_FRAGMENT_SHADER);
}
@Test
void perFrameBlock_firstDeclIsStrippedSampler() {
GLSMHooks.perFrameUniformBlock = PER_FRAME;
final String src = "#version 460 core\n"
+ "uniform sampler2D u_Unused;\n"
+ "uniform float frameTimeCounter;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() {\n"
+ " fragColor = vec4(frameTimeCounter);\n"
+ "}\n";
assertEquivalentIgnoringWhitespace("pfb-stripped-first-sampler", src, GL20.GL_FRAGMENT_SHADER);
}
@Test
void perFrameBlock_shadowedMemberKeepsLocalDeclaration() {
GLSMHooks.perFrameUniformBlock = PER_FRAME;
final String src = "#version 460 core\n"
+ "uniform vec4 frameTimeCounter;\n"
+ "uniform vec3 cameraPosition;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() {\n"
+ " fragColor = frameTimeCounter + vec4(cameraPosition, 0.0);\n"
+ "}\n";
assertEquivalent("pfb-shadowed", src, GL20.GL_FRAGMENT_SHADER);
}
@Test
void perFrameBlock_noReferencesLeavesSourceUntouched() {
GLSMHooks.perFrameUniformBlock = PER_FRAME;
GLSMHooks.perPassUniformBlock = PER_PASS;
final String src = "#version 460 core\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(1.0); }\n";
assertEquivalent("pfb-unreferenced", src, GL20.GL_FRAGMENT_SHADER);
}
}
@@ -0,0 +1,123 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock;
import com.gtnewhorizons.angelica.glsm.hooks.PerFrameUniformBlock.Member;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PrewarmTreeHandoffEquivalenceTest {
private static final String HEADER = "#version 460 core\n";
@AfterEach
void clearBlocks() {
GLSMHooks.perFrameUniformBlock = null;
GLSMHooks.perPassUniformBlock = null;
}
private static void assertHandoffEquivalent(String label, String body, int glShaderType) {
final GLSLParser.Translation_unitContext tree = ShaderParser.parseShader(body).full();
GlslTransformUtils.restoreReservedWordsInTree(tree);
final String printedBody = GlslTransformUtils.getFormattedShaderRebased(tree, "");
final String finalSource = HEADER + printedBody;
GlslVulkanPreprocess.clearCache();
final ShaderManager.PrewarmTransformResult reparse = ShaderManager.applyPrewarmTransformsFull(finalSource, glShaderType);
GlslVulkanPreprocess.clearCache();
final ShaderManager.PrewarmTransformResult treeFed = ShaderManager.applyPrewarmTransformsFull(finalSource, tree, HEADER.length(), glShaderType);
assertEquals(reparse.source(), treeFed.source(), "tree handoff diverged from re-parse for " + label);
assertEquals(reparse.boolUniforms(), treeFed.boolUniforms(), "bool uniforms diverged for " + label);
}
@Test
void minimalFragment() {
assertHandoffEquivalent("minimal-fragment",
"layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(1.0); }\n",
GL20.GL_FRAGMENT_SHADER);
}
@Test
void unusedSamplerStripped() {
assertHandoffEquivalent("unused-sampler",
"uniform sampler2D u_Unused;\n"
+ "uniform sampler2D u_Used;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = texture(u_Used, vec2(0.5)); }\n",
GL20.GL_FRAGMENT_SHADER);
}
@Test
void perFrameBlockInjection() {
GLSMHooks.perFrameUniformBlock = new PerFrameUniformBlock(List.of(
new Member("cameraPosition", UniformType.VEC3),
new Member("frameTimeCounter", UniformType.FLOAT)));
assertHandoffEquivalent("per-frame-block",
"uniform float frameTimeCounter;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(frameTimeCounter); }\n",
GL20.GL_FRAGMENT_SHADER);
}
@Test
void vertexClipZAndUnlocatedInputs() {
GLSMHooks.perFrameUniformBlock = new PerFrameUniformBlock(List.of(
new Member("cameraPosition", UniformType.VEC3)));
assertHandoffEquivalent("vertex-clipz-unlocated",
"layout(location = 0) in vec3 a_Position;\n"
+ "in vec2 a_TexCoord;\n"
+ "uniform vec3 cameraPosition;\n"
+ "out vec2 v_TexCoord;\n"
+ "void main() {\n"
+ " v_TexCoord = a_TexCoord;\n"
+ " gl_Position = vec4(a_Position - cameraPosition, 1.0);\n"
+ "}\n",
GL20.GL_VERTEX_SHADER);
}
@Test
void boolUniformMetadata() {
assertHandoffEquivalent("bool-uniform",
"uniform bool u_Enabled;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(u_Enabled ? 1.0 : 0.0); }\n",
GL20.GL_FRAGMENT_SHADER);
}
@Test
void texelFetchPath() {
assertHandoffEquivalent("texelfetch",
"uniform sampler2D u_Data;\n"
+ "layout(location = 0) out vec4 fragColor;\n"
+ "void main() { fragColor = texelFetch(u_Data, ivec2(0), 0); }\n",
GL20.GL_FRAGMENT_SHADER);
}
@Test
void geometryStage() {
assertHandoffEquivalent("geometry",
"layout(triangles) in;\n"
+ "layout(triangle_strip, max_vertices = 3) out;\n"
+ "void main() {\n"
+ " for (int i = 0; i < 3; i++) {\n"
+ " gl_Position = gl_in[i].gl_Position;\n"
+ " EmitVertex();\n"
+ " }\n"
+ " EndPrimitive();\n"
+ "}\n",
GL32.GL_GEOMETRY_SHADER);
}
}
@@ -0,0 +1,46 @@
package com.gtnewhorizons.angelica.sdlgpu.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertFalse;
class ThreadRegistryTest {
private static ThreadRegistry<Object> registry() {
return new ThreadRegistry<>(new Object[0]);
}
@Test
void soleTracksTheSingleEntry() {
final ThreadRegistry<Object> r = registry();
final Object a = new Object();
final Object b = new Object();
assertNull(r.sole(), "empty registry has no sole entry");
r.add(a);
assertSame(a, r.sole());
r.add(b);
assertNull(r.sole(), "two entries means no sole entry");
r.remove(b);
assertSame(a, r.sole());
r.remove(a);
assertNull(r.sole());
assertEquals(0, r.size());
}
@Test
void removeOfAnAbsentEntryLeavesTheRegistryAlone() {
final ThreadRegistry<Object> r = registry();
final Object a = new Object();
r.add(a);
final Object[] before = r.snapshot();
assertFalse(r.remove(new Object()));
assertSame(before, r.snapshot(), "a no-op remove must not republish");
assertSame(a, r.sole());
}
}
@@ -4,19 +4,14 @@ import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.ffp.FFPVertexLighting;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
@@ -29,20 +24,31 @@ import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutByte;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutShort;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memRealloc;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD;
/**
* A batching replacement for {@code FontRenderer}
@@ -67,6 +73,8 @@ public class BatchingFontRenderer {
private final int AAStrength;
private final int alphaTestRefLocation;
private final int mvpMatrixLocation;
private final int lightmapLocation;
private final int lightmapSamplerLocation;
private final int fontShaderId;
final boolean isSGA;
@@ -111,6 +119,8 @@ public class BatchingFontRenderer {
AAStrength = GLStateManager.glGetUniformLocation(fontShaderId, "strength");
alphaTestRefLocation = GLStateManager.glGetUniformLocation(fontShaderId, "alphaTestRef");
mvpMatrixLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_MVPMatrix");
lightmapLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_Lightmap");
lightmapSamplerLocation = GLStateManager.glGetUniformLocation(fontShaderId, "lightmap");
if (ebo == null) {
ebo = new IndexBuffer();
vbo = GLStateManager.glGenBuffers();
@@ -128,6 +138,9 @@ public class BatchingFontRenderer {
// [v, v, t, t, c, c, c, c, tb, tb, tb, tb]
// v, t and tb are floats, c is bytes; 36 bytes total
private static final int VERTEX_SIZE = 36;
/** {@code OpenGlHelper.lightmapTexUnit} */
private static final int LIGHTMAP_TEX_UNIT = 1;
private static int rawCapacity = INITIAL_BATCH_SIZE * VERTEX_SIZE;
private static ByteBuffer vertexData = memAlloc(rawCapacity);
private static long vertexDataAddress = memAddress0(vertexData);
@@ -138,6 +151,7 @@ public class BatchingFontRenderer {
private static int fontVAO = 0;
private static int vbo;
private static IndexBuffer ebo;
private static int lightmapSamplerProgram;
private static final int RING_CAPACITY = 2 * 1024 * 1024;
private static PersistentStreamingBuffer streamRing;
@@ -158,11 +172,58 @@ public class BatchingFontRenderer {
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
private float lightmapU = 0.0f;
private float lightmapV = 0.0f;
private boolean lightmapActive = false;
private int lightmapTextureId = 0;
private final Vector3f lightingFactor = new Vector3f(1.0f, 1.0f, 1.0f);
private boolean lightingFactorActive = false;
private static final Vector4f scratchLightmapUv = new Vector4f();
private int applyLighting(int argb) {
if (!lightingFactorActive) return argb;
final int red = Math.max(0, Math.min(255, (int) (((argb >> 16) & 0xFF) * lightingFactor.x + 0.5f)));
final int green = Math.max(0, Math.min(255, (int) (((argb >> 8) & 0xFF) * lightingFactor.y + 0.5f)));
final int blue = Math.max(0, Math.min(255, (int) ((argb & 0xFF) * lightingFactor.z + 0.5f)));
return (argb & 0xFF000000) | (red << 16) | (green << 8) | blue;
}
private void captureLightmapState() {
final int unitBinding = GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding();
final boolean active = GLStateManager.getProjectionMatrix().m33() == 0.0f && unitBinding != 0;
float u = 0.0f;
float v = 0.0f;
int texture = 0;
if (active) {
scratchLightmapUv.set(GLSMConfig.lastBrightnessX, GLSMConfig.lastBrightnessY, 0.0f, 1.0f).mul(GLStateManager.getTextures().getTextureUnitMatrix(LIGHTMAP_TEX_UNIT));
u = scratchLightmapUv.x;
v = scratchLightmapUv.y;
texture = unitBinding;
}
if (active == lightmapActive && u == lightmapU && v == lightmapV && texture == lightmapTextureId) {
return;
}
sealBatchSegment();
lightmapActive = active;
lightmapU = u;
lightmapV = v;
lightmapTextureId = texture;
}
private static final class TextSegment {
final Matrix4f mvp = new Matrix4f();
BatchingFontRenderer owner;
int cmdStart;
int cmdEnd;
float lightmapU;
float lightmapV;
boolean lightmapActive;
int lightmapTexture;
}
// 16-bit EBO index range
@@ -183,7 +244,6 @@ public class BatchingFontRenderer {
private int batchSealedEnd;
private static BatchingFontRenderer arenaOwner;
private void allocateBuffers() {
populateEBO(rawCapacity / VERTEX_SIZE);
}
@@ -255,6 +315,7 @@ public class BatchingFontRenderer {
private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) {
final long ptr = vertexDataAddress + vertexDataPos;
rgba = applyLighting(rgba);
// v, v
memPutFloat(ptr, x);
@@ -414,6 +475,10 @@ public class BatchingFontRenderer {
segment.cmdStart = batchSealedEnd;
segment.cmdEnd = end;
resolveMvp(segment.mvp);
segment.lightmapActive = lightmapActive;
segment.lightmapU = lightmapU;
segment.lightmapV = lightmapV;
segment.lightmapTexture = lightmapTextureId;
batchSegments.add(segment);
batchSealedEnd = end;
}
@@ -485,6 +550,7 @@ public class BatchingFontRenderer {
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
@@ -493,6 +559,7 @@ public class BatchingFontRenderer {
GLStateManager.glDepthMask(false);
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0, n = deferredSegments.size(); i < n; i++) {
@@ -500,10 +567,12 @@ public class BatchingFontRenderer {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf);
uploadLightmap(segment.owner.lightmapLocation, segment.lightmapActive, segment.lightmapU,
segment.lightmapV, segment.lightmapTexture);
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
}
}
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore, lightmapBindingBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
discardDeferredText();
@@ -517,6 +586,7 @@ public class BatchingFontRenderer {
segment.owner.recycleBatchSegments();
segment.owner.batchSealedEnd = 0;
segment.owner.batchMatrixValid = false;
segment.owner.resetLightmapState();
segment.owner = null;
}
deferredSegmentPool.addAll(deferredSegments);
@@ -578,12 +648,14 @@ public class BatchingFontRenderer {
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
setupFontDrawState();
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0; i < segmentCount; i++) {
@@ -591,6 +663,7 @@ public class BatchingFontRenderer {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture);
drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this);
}
if (batchSealedEnd < cmdCount) {
@@ -598,10 +671,11 @@ public class BatchingFontRenderer {
resolveMvp(scratchMvp);
scratchMvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId);
drawCommands(cmds, batchSealedEnd, cmdCount, this);
}
}
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore, lightmapBindingBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
truncateBatchToWatermark();
@@ -624,6 +698,10 @@ public class BatchingFontRenderer {
GLStateManager.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f);
}
GLStateManager.glUniform1f(alphaTestRefLocation, GLStateManager.getAlphaState().getReference());
if (lightmapSamplerProgram != fontShaderId) {
GLStateManager.glUniform1i(lightmapSamplerLocation, LIGHTMAP_TEX_UNIT);
lightmapSamplerProgram = fontShaderId;
}
if (fontVAO == 0) {
fontVAO = GLStateManager.glGenVertexArrays();
@@ -654,6 +732,38 @@ public class BatchingFontRenderer {
private static ResourceLocation flushLastTexture;
private static boolean flushTextureChanged;
private static float flushLastLightmapU;
private static float flushLastLightmapV;
private static boolean flushLastLightmapActive;
private static void resetFlushLightmap() {
flushLastLightmapU = Float.NaN;
flushLastLightmapV = Float.NaN;
flushLastLightmapActive = false;
}
private static int boundLightmapTexture() {
return GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding();
}
private static void bindLightmapTexture(int texture) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private static void uploadLightmap(int uniformLocation, boolean active, float u, float v, int texture) {
if (u != flushLastLightmapU || v != flushLastLightmapV || active != flushLastLightmapActive) {
GLStateManager.glUniform3f(uniformLocation, u, v, active ? 1.0f : 0.0f);
flushLastLightmapU = u;
flushLastLightmapV = v;
flushLastLightmapActive = active;
}
if (active && texture != 0 && boundLightmapTexture() != texture) {
bindLightmapTexture(texture);
}
}
private static void drawCommands(FontDrawCmd[] cmdsData, int from, int to, BatchingFontRenderer owner) {
for (int i = from; i < to; i++) {
final FontDrawCmd cmd = cmdsData[i];
@@ -673,7 +783,7 @@ public class BatchingFontRenderer {
}
}
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore) {
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore, int lightmapBindingBefore) {
GLStateManager.glUseProgram(prevProgram);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
@@ -688,6 +798,9 @@ public class BatchingFontRenderer {
if (flushTextureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
if (boundLightmapTexture() != lightmapBindingBefore) {
bindLightmapTexture(lightmapBindingBefore);
}
}
private static void restoreDepth(boolean testBefore, boolean maskBefore) {
@@ -709,11 +822,19 @@ public class BatchingFontRenderer {
batchMatrixValid = false;
vertexDataPos = deferredVertexPos;
idxWriterIndex = deferredIdxPos;
resetLightmapState();
if (arenaOwner == this) {
arenaOwner = null;
}
}
private void resetLightmapState() {
lightmapActive = false;
lightmapU = 0.0f;
lightmapV = 0.0f;
lightmapTextureId = 0;
}
// === Actual text mesh generation
public static boolean charInRange(char what, char fromInclusive, char toInclusive) {
@@ -808,6 +929,8 @@ public class BatchingFontRenderer {
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
this.beginBatch();
this.captureLightmapState();
this.lightingFactorActive = FFPVertexLighting.modulatesVertexColor(this.lightingFactor);
float curX = anchorX;
try {
final int totalStringLength = string.length();
@@ -70,9 +70,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material) {
final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder();
if (texture != null) {
b.texture(new RenderPhase.Texture(texture, false, false));
}
b.texture(texture != null ? new RenderPhase.Texture(texture, false, false) : NO_TEXTURE);
if (material.isNoCull()) {
b.cull(DISABLE_CULLING);
}
@@ -85,18 +83,14 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
if (material.isDepthOnly()) {
b.writeMaskState(DEPTH_MASK);
}
if (material.cutoutAlpha() > 0) {
b.alpha(new RenderPhase.Alpha(material.cutoutAlpha()));
}
if (material.isDepthEqual()) {
b.depthTest(EQUAL_DEPTH_TEST);
}
b.alpha(material.cutoutAlpha() > 0 ? new RenderPhase.Alpha(material.cutoutAlpha()) : ZERO_ALPHA);
b.depthTest(material.isDepthEqual() ? EQUAL_DEPTH_TEST : LEQUAL_DEPTH_TEST);
switch (material.transparency()) {
case TRANSLUCENT -> b.transparency(TRANSLUCENT_TRANSPARENCY);
case ADDITIVE -> b.transparency(ADDITIVE_TRANSPARENCY);
case ADDITIVE_ALPHA -> b.transparency(LIGHTNING_TRANSPARENCY);
case GLINT -> b.transparency(GLINT_TRANSPARENCY);
case OPAQUE -> {}
case OPAQUE -> b.transparency(NO_TRANSPARENCY);
}
switch (material.special()) {
case GLINT -> b.shader(SPECIAL_GLINT);
@@ -119,21 +113,12 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
GbufferPrograms::teardownSpecialRenderCondition);
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) {
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material).shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP);
if (material.transparency() == TesrMaterial.Transparency.TRANSLUCENT) {
b.target(TRANSLUCENT_TARGET);
}
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material).shadeModel(SMOOTH_SHADE_MODEL);
final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE;
return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, sortsTranslucent, b.build(false));
}
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) {
return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false,
tesrMaterialPhases(texture, material).build(false));
}
public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) {
return of("outline", DefaultVertexFormat.POSITION_COLOR_TEXTURE, 7, 256, RenderLayer.MultiPhaseParameters.builder().texture(new RenderPhase.Texture(texture, false, false)).cull(cull).depthTest(ALWAYS_DEPTH_TEST).alpha(ONE_TENTH_ALPHA).fog(NO_FOG).target(OUTLINE_TARGET).build(RenderLayer.OutlineMode.IS_OUTLINE));
}
@@ -154,7 +139,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
@Override
public TransparencyType getTransparencyType() {
return phases.transparency.getTransparencyType();
return phases.transparency == null ? TransparencyType.OPAQUE : phases.transparency.getTransparencyType();
}
private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) {
@@ -170,7 +155,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
}
});
this.phases = phases;
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE ? phases.texture.getId().map((arg2) -> {
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE && phases.texture != null ? phases.texture.getId().map((arg2) -> {
return getOutline(arg2, phases.cull);
}) : Optional.empty();
this.hash = Objects.hash(new Object[]{super.hashCode(), phases});
@@ -187,7 +172,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
@Override
public ResourceLocation getTextureId() {
return phases.texture.getId().orElse(null);
return phases.texture == null ? null : phases.texture.getId().orElse(null);
}
@Override
@@ -223,7 +208,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
if (arg == arg2) {
return true;
} else {
return arg != null && arg2 != null ? Objects.equals(arg.phases, arg2.phases) : false;
return arg != null && arg2 != null && arg.name.equals(arg2.name)
&& arg.getVertexFormat() == arg2.getVertexFormat() && arg.getDrawMode() == arg2.getDrawMode()
&& Objects.equals(arg.phases, arg2.phases);
}
}
}
@@ -263,7 +250,13 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
this.writeMaskState = writeMaskState;
this.shader = shader;
this.outlineMode = outlineMode;
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader);
final ImmutableList.Builder<RenderPhase> declared = ImmutableList.builder();
for (RenderPhase phase : new RenderPhase[] { this.texture, this.transparency, this.diffuseLighting,
this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering,
this.target, this.texturing, this.writeMaskState, this.shader }) {
if (phase != null) declared.add(phase);
}
this.phases = declared.build();
}
@Override
@@ -308,22 +301,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private RenderPhase.WriteMaskState writeMaskState;
private RenderPhase.Shader shader;
private Builder() {
this.texture = RenderPhase.NO_TEXTURE ;
this.transparency = RenderPhase.NO_TRANSPARENCY;
this.diffuseLighting = RenderPhase.DISABLE_DIFFUSE_LIGHTING;
this.shadeModel = RenderPhase.SHADE_MODEL;
this.alpha = RenderPhase.ZERO_ALPHA;
this.depthTest = RenderPhase.LEQUAL_DEPTH_TEST;
this.cull = RenderPhase.ENABLE_CULLING;
this.lightmap = RenderPhase.DISABLE_LIGHTMAP;
this.fog = RenderPhase.FOG;
this.layering = RenderPhase.NO_LAYERING;
this.target = RenderPhase.MAIN_TARGET;
this.texturing = RenderPhase.DEFAULT_TEXTURING;
this.writeMaskState = RenderPhase.ALL_MASK;
this.shader = RenderPhase.NO_SHADER;
}
private Builder() {}
public Builder texture(RenderPhase.Texture texture) {
this.texture = texture;
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.debug.flyby;
import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import net.minecraft.client.Minecraft;
@@ -57,6 +58,10 @@ public final class FlybyRunner {
private long plotTurning;
private int lastPhase = -1;
private long warmupSection;
private long runSection;
private long legSection;
private long[] frameTimesNs = NO_FRAMES;
private int frameCount;
private boolean framesTruncated;
@@ -180,9 +185,13 @@ public final class FlybyRunner {
this.buildPath();
this.freezeTimeAndWeather(mc);
this.state = this.warmupTicks > 0 ? State.WARMUP : State.RUNNING;
this.tick = 0;
if (this.state == State.RUNNING) this.beginMeasuring();
if (this.warmupTicks > 0) {
this.state = State.WARMUP;
this.warmupSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, "flyby warmup");
} else {
this.beginMeasuring();
}
LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(),
this.originX, this.originY, this.originZ, this.originYaw);
@@ -252,12 +261,18 @@ public final class FlybyRunner {
final int phase = (leg << 1) | turning;
if (phase != this.lastPhase) {
this.lastPhase = phase;
Tracy.message("flyby " + (turning != 0 ? "turn" : "leg") + " " + leg);
final String label = "flyby " + (turning != 0 ? "turn" : "leg") + " " + leg;
Tracy.message(label);
Tracy.sectionLeave(this.legSection);
this.legSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, label);
}
}
private void beginMeasuring() {
this.state = State.RUNNING;
Tracy.sectionLeave(this.warmupSection);
this.warmupSection = 0L;
if (Tracy.ENABLED) this.runSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, "flyby " + this.route.id());
this.plotLeg = Tracy.plotHandle("flyby.leg");
this.plotTurning = Tracy.plotHandle("flyby.turning");
this.lastPhase = -1;
@@ -265,11 +280,10 @@ public final class FlybyRunner {
this.frameCount = 0;
this.lastFrameNs = 0L;
this.runStartNs = System.nanoTime();
Tracy.message("flyby start route=" + this.route.id()
+ " length=" + this.runLength + this.route.lengthUnit()
+ " speed=" + this.route.speedOr(this.speed) + "b/t"
+ " ticks=" + this.runTicks
+ " sdlgpu=" + SystemProperties.USE_SDL_GPU);
FramePacer.beginStats();
if (Tracy.ENABLED) {
Tracy.message("flyby start route=" + this.route.id() + " length=" + this.runLength + this.route.lengthUnit() + " speed=" + this.route.speedOr(this.speed) + "b/t ticks=" + this.runTicks + " sdlgpu=" + SystemProperties.USE_SDL_GPU);
}
}
private void holdPosition(EntityClientPlayerMP player) {
@@ -364,10 +378,15 @@ public final class FlybyRunner {
this.state = State.SETTLE;
this.tick = 0;
final long elapsedNs = System.nanoTime() - this.runStartNs;
Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount);
Tracy.sectionLeave(this.legSection);
this.legSection = 0L;
Tracy.sectionLeave(this.runSection);
this.runSection = 0L;
if (Tracy.ENABLED) Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount);
final String summary = this.summarise(elapsedNs, player);
LOGGER.info(summary);
LOGGER.info(FramePacer.endStats());
if (mc.thePlayer != null) {
mc.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + summary));
}
@@ -422,6 +441,13 @@ public final class FlybyRunner {
if (this.isActive()) {
LOGGER.info("Flyby cancelled");
this.state = State.DONE;
Tracy.sectionLeave(this.warmupSection);
this.warmupSection = 0L;
Tracy.sectionLeave(this.legSection);
this.legSection = 0L;
Tracy.sectionLeave(this.runSection);
this.runSection = 0L;
FramePacer.endStats();
}
}
@@ -0,0 +1,35 @@
package com.gtnewhorizons.angelica.helpers;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumChatFormatting;
public final class RendererLivingEntityHelper {
private RendererLivingEntityHelper() {}
public static String getUpsideDownName(EntityLivingBase entity) {
if (entity instanceof EntityLiving living) {
return living.hasCustomNameTag() ? entity.getCommandSenderName() : "";
}
if (entity instanceof EntityPlayer player) {
return player.getHideCape() ? "" : entity.getCommandSenderName();
}
return entity.getCommandSenderName();
}
public static String stripFormattingCodes(String entityName) {
if (entityName == null || entityName.isEmpty()) {
return "";
}
return entityName.indexOf(FORMATTING_CHAR) < 0
? entityName
: EnumChatFormatting.getTextWithoutFormattingCodes(entityName);
}
}
@@ -6,6 +6,9 @@ import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import org.taumc.glsl.grammar.GLSLParser;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter;
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
import net.coderbot.iris.Iris;
@@ -48,6 +51,27 @@ public class IrisGLSMBridge {
StateUpdateNotifiers.colorModulatorNotifier = listener -> colorModulatorListener = listener;
}
public static void installPostTransformHook() {
if (GLSMHooks.postTransformProcessor != null) return;
GLSMHooks.postTransformProcessor = new ShaderTransformPostProcessor() {
@Override
public void onTransformed(String src, ShaderType shaderType) {
onTransformed(src, null, 0, shaderType);
}
@Override
public void onTransformed(String src, GLSLParser.Translation_unitContext bodyTree, int headerLen, ShaderType shaderType) {
if (Iris.ShaderTransformExecutor.isOnWorker()) {
SDLGPUGate.prewarmSpirv(src, bodyTree, headerLen, shaderType.id);
} else {
Iris.ShaderTransformExecutor.submitTracked(() -> {
SDLGPUGate.prewarmSpirv(src, bodyTree, headerLen, shaderType.id);
});
}
}
};
}
public static void register() {
GLSMConfig.expandVertexFormats = Iris.enabled;
IrisSamplers.initRenderer();
@@ -57,15 +81,7 @@ public class IrisGLSMBridge {
return Iris.ShaderTransformExecutor.submitTracked(work);
}
};
GLSMHooks.postTransformProcessor = (src, shaderType) -> {
if (Iris.ShaderTransformExecutor.isOnWorker()) {
SDLGPUGate.prewarmSpirv(src, shaderType.id);
} else {
Iris.ShaderTransformExecutor.submitTracked(() -> {
SDLGPUGate.prewarmSpirv(src, shaderType.id);
});
}
};
installPostTransformHook();
GLSMHooks.blendHandler = new DeferredBlendHandler() {
@Override
public boolean isBlendLocked() {
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.TileEntityMarkerTransform;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
@@ -12,10 +13,12 @@ import org.objectweb.asm.tree.ClassNode;
public class CeleritasBlockTransformer implements IClassTransformer {
private final CeleritasBlockTransform inner;
private final TileEntityMarkerTransform tileEntities;
private final String[] exclusions;
public CeleritasBlockTransformer() {
this.inner = new CeleritasBlockTransform(AngelicaClientTweaker.isObfEnv());
this.tileEntities = new TileEntityMarkerTransform(AngelicaClientTweaker.isObfEnv());
this.exclusions = inner.getTransformerExclusions();
}
@@ -31,14 +34,19 @@ public class CeleritasBlockTransformer implements IClassTransformer {
}
final ClassReader cr = new ClassReader(basicClass);
inner.trackBlockSubclasses(cr.getClassName(), cr.getSuperName());
final String className = cr.getClassName();
inner.trackBlockSubclasses(className, cr.getSuperName());
tileEntities.track(className, cr.getSuperName());
if (!inner.shouldTransform(basicClass)) {
return basicClass;
final int markers = tileEntities.markersFor(className, basicClass);
final byte[] marked = markers == 0 ? basicClass : tileEntities.addMarkers(basicClass, markers);
if (!inner.shouldTransform(marked)) {
return marked;
}
final ClassNode cn = new ClassNode();
cr.accept(cn, 0);
(markers == 0 ? cr : new ClassReader(marked)).accept(cn, 0);
final boolean changed = inner.transformClassNode(transformedName, cn);
if (changed) {
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
@@ -47,7 +55,7 @@ public class CeleritasBlockTransformer implements IClassTransformer {
AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this);
return bytes;
}
return basicClass;
return marked;
}
}
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.TileEntityMarkerTransform;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassHeaderMetadata;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
@@ -9,15 +10,18 @@ import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
import org.intellij.lang.annotations.Pattern;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.tree.ClassNode;
import java.util.jar.Manifest;
public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
private final CeleritasBlockTransform inner;
private final TileEntityMarkerTransform tileEntities;
public RFBCeleritasBlockTransformer(boolean isObf) {
inner = new CeleritasBlockTransform(isObf);
tileEntities = new TileEntityMarkerTransform(isObf);
}
@Pattern("[a-z0-9-]+")
@@ -54,15 +58,32 @@ public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
return false;
}
inner.trackBlockSubclasses(metadata.binaryThisName(), metadata.binarySuperName());
return inner.shouldTransform(classNode.getOriginalBytes());
final String thisName = metadata.binaryThisName();
final String superName = metadata.binarySuperName();
final byte[] originalBytes = classNode.getOriginalBytes();
inner.trackBlockSubclasses(thisName, superName);
if (context == RfbClassTransformer.Context.LCL_WITH_TRANSFORMS) {
tileEntities.track(thisName, superName);
if (tileEntities.markersFor(thisName, originalBytes) != 0) return true;
}
return inner.shouldTransform(originalBytes);
}
@Override
public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader,
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest,
@NotNull String className, @NotNull ClassNodeHandle classNode) {
final boolean changed = inner.transformClassNode(className, classNode.getNode());
final ClassNode node = classNode.getNode();
boolean changed = false;
if (context == RfbClassTransformer.Context.LCL_WITH_TRANSFORMS) {
final int markers = tileEntities.markersFor(node.name, classNode.getOriginalBytes());
if (markers != 0) {
tileEntities.addMarkers(node, markers);
changed = true;
}
}
changed |= inner.transformClassNode(className, node);
if (changed) {
classNode.computeMaxs();
AngelicaClassDump.dumpRFBClass(className, classNode, this);
@@ -0,0 +1,130 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Marks TileEntity subclasses that declare getDescriptionPacket, shouldRenderInPass or getDistanceFrom with a
* corresponding interface, so runtime code can test with instanceof instead of reflection.
*/
public final class TileEntityMarkerTransform {
public static final int MARK_DESCRIPTION_PACKET = 1 << 0;
public static final int MARK_SHOULD_RENDER_IN_PASS = 1 << 1;
public static final int MARK_GET_DISTANCE_FROM = 1 << 2;
private static final String SENDS_DESCRIPTION_PACKET = "com/gtnewhorizons/angelica/mixins/interfaces/SendsDescriptionPacket";
private static final String OVERRIDES_SHOULD_RENDER_IN_PASS = "com/gtnewhorizons/angelica/mixins/interfaces/OverridesShouldRenderInPass";
private static final String OVERRIDES_GET_DISTANCE_FROM = "com/gtnewhorizons/angelica/mixins/interfaces/OverridesGetDistanceFrom";
private static final String TILE_ENTITY = "net/minecraft/tileentity/TileEntity";
private static final int SCAN_FLAGS = ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
private record Marker(int bit, String method, String desc, String iface) {}
private final Marker[] markers;
private final ClassConstantPoolParser prefilter;
private final Set<String> tileEntities = Collections.newSetFromMap(new ConcurrentHashMap<>());
public TileEntityMarkerTransform(boolean isObf) {
this.markers = new Marker[] {
new Marker(MARK_DESCRIPTION_PACKET, isObf ? "func_145844_m" : "getDescriptionPacket", "()Lnet/minecraft/network/Packet;", SENDS_DESCRIPTION_PACKET),
new Marker(MARK_SHOULD_RENDER_IN_PASS, "shouldRenderInPass", "(I)Z", OVERRIDES_SHOULD_RENDER_IN_PASS),
new Marker(MARK_GET_DISTANCE_FROM, isObf ? "func_145835_a" : "getDistanceFrom", "(DDD)D", OVERRIDES_GET_DISTANCE_FROM) };
final String[] methods = new String[markers.length];
for (int i = 0; i < markers.length; i++) methods[i] = markers[i].method();
this.prefilter = new ClassConstantPoolParser(methods);
}
private boolean isTileEntity(String className) {
return className != null && (className.startsWith(TILE_ENTITY) || tileEntities.contains(className));
}
public void track(String className, String superClassName) {
if (className != null && isTileEntity(superClassName)) tileEntities.add(className);
}
public int markersFor(String className, byte[] classBytes) {
if (TILE_ENTITY.equals(className) || !isTileEntity(className) || !prefilter.find(classBytes)) return 0;
final MarkerScanner scanner = new MarkerScanner();
new ClassReader(classBytes).accept(scanner, SCAN_FLAGS);
return scanner.declared & ~scanner.alreadyPresent;
}
public byte[] addMarkers(byte[] classBytes, int markers) {
final ClassReader cr = new ClassReader(classBytes);
final ClassWriter cw = new ClassWriter(cr, 0);
cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
@Override
public void visit(int version, int access, String name, String sig, String superName, String[] interfaces) {
final String[] added = interfacesFor(markers);
if (interfaces == null) {
super.visit(version, access, name, sig, superName, added);
return;
}
final String[] merged = Arrays.copyOf(interfaces, interfaces.length + added.length);
System.arraycopy(added, 0, merged, interfaces.length, added.length);
super.visit(version, access, name, sig, superName, merged);
}
}, 0);
return cw.toByteArray();
}
public void addMarkers(ClassNode cn, int markers) {
Collections.addAll(cn.interfaces, interfacesFor(markers));
}
private int bitOf(int access, String name, String desc) {
if ((access & Opcodes.ACC_PUBLIC) == 0 || (access & Opcodes.ACC_STATIC) != 0) return 0;
for (Marker m : markers) if (m.method().equals(name) && m.desc().equals(desc)) return m.bit();
return 0;
}
private int bitOf(String interfaceName) {
for (Marker m : markers) if (m.iface().equals(interfaceName)) return m.bit();
return 0;
}
private String[] interfacesFor(int wanted) {
final String[] names = new String[Integer.bitCount(wanted)];
int next = 0;
for (Marker m : markers) if ((wanted & m.bit()) != 0) names[next++] = m.iface();
return names;
}
private final class MarkerScanner extends ClassVisitor {
private int declared;
private int alreadyPresent;
MarkerScanner() {
super(Opcodes.ASM5);
}
@Override
public void visit(int version, int access, String name, String sig, String superName, String[] interfaces) {
if (interfaces == null) return;
for (String iface : interfaces) alreadyPresent |= bitOf(iface);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] exceptions) {
declared |= bitOf(access, name, desc);
return null;
}
}
}
@@ -70,6 +70,12 @@ public enum Mixins implements IMixins {
)
),
STARMINER_RENDERER_LIVING_ENTITY_OPTIMIZATION(new MixinBuilder()
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.STARMINER)
.addClientMixins("client.starminer.MixinTransformClientHelper")
),
ANGELICA_ENTITY_OVERLAYS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.entityOverlayFixes)
@@ -377,6 +383,11 @@ public enum Mixins implements IMixins {
, "celeritas.biome_blending.MixinBlockLiquid"
, "celeritas.threading.MixinForgeHooksClient"
, "celeritas.terrain.MixinChunk"
, "celeritas.terrain.MixinWorldClient_WorkerAccess"
, "celeritas.terrain.MixinWorld_WorkerMutationGuard"
, "celeritas.terrain.MixinTileEntity_AwaitingDescriptor"
, "celeritas.terrain.MixinNetHandlerPlayClient_DescriptorRepair"
, "celeritas.terrain.MixinWorld_AwaitingDescriptor"
, "celeritas.terrain.MixinRenderRegion"
, "celeritas.terrain.MixinSectionRenderDataStorage"
, "celeritas.terrain.MixinDefaultChunkRenderer"
@@ -24,6 +24,7 @@ public enum TargetedMod implements ITargetMod {
IC2("ic2.core.coremod.IC2core", "IC2"),
NATURA(null, "Natura"),
SECURITYCRAFT(null, "securitycraft"),
STARMINER("jp.mc.ancientred.starminer.core.SMPlugin", "modJ_StarMiner"),
SUPERNOVA("com.mitchej123.supernova.core.SupernovaCore", "supernova"),
THAUMCRAFT(null, "Thaumcraft"),
TINKERS_CONSTRUCT(null, "TConstruct"),
@@ -0,0 +1,12 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface AwaitingDescriptorTE {
boolean angelica$isAwaitingDescriptor();
void angelica$setAwaitingDescriptor(boolean awaiting);
int angelica$getDescriptorWaitTicks();
void angelica$setDescriptorWaitTicks(int ticks);
}
@@ -6,6 +6,4 @@ public interface ITileEntityBoundingBoxCache {
AxisAlignedBB angelica$getCachedRenderBoundingBox();
byte angelica$boundsClass();
byte angelica$passClass();
}
@@ -0,0 +1,3 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface OverridesGetDistanceFrom {}
@@ -0,0 +1,3 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface OverridesShouldRenderInPass {}
@@ -0,0 +1,3 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface SendsDescriptionPacket {}
@@ -0,0 +1,39 @@
package com.gtnewhorizons.angelica.profiling;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiIngameMenu;
import java.util.HashMap;
import java.util.Map;
public final class TracyUiSections {
private static final Map<Class<?>, String> LABELS = new HashMap<>();
private static Class<?> current = TracyUiSections.class;
private static long section;
private TracyUiSections() {}
public static void poll(GuiScreen screen) {
if (!Tracy.ENABLED) return;
final Class<?> screenClass = screen == null ? null : screen.getClass();
if (screenClass == current) return;
current = screenClass;
Tracy.sectionLeave(section);
section = Tracy.sectionEnter(Tracy.SECTION_UI, label(screenClass));
}
private static String label(Class<?> screenClass) {
if (screenClass == null) return "in world";
String label = LABELS.get(screenClass);
if (label == null) {
if (screenClass == GuiMainMenu.class) label = "main menu";
else if (screenClass == GuiIngameMenu.class) label = "pause";
else label = screenClass.getSimpleName();
LABELS.put(screenClass, label);
}
return label;
}
}
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.proxy;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
@@ -36,6 +37,7 @@ import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
@@ -52,6 +54,8 @@ import com.gtnewhorizons.angelica.debug.TPSGraph;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.iris.IrisGLSMBridge;
import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker;
@@ -59,8 +63,10 @@ import com.gtnewhorizons.angelica.mixins.interfaces.IGameSettingsExt;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import com.gtnewhorizons.angelica.render.EmissiveTextureAutoloader;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.DefaultChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ThreadedChunkTaskProvider;
@@ -83,6 +89,7 @@ import jss.notfine.gui.GuiCustomMenu;
import jss.notfine.gui.NotFineGameOptionPages;
import jss.notfine.gui.options.named.FOVMode;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.FrameRateOptions;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.coderbot.iris.Iris;
@@ -106,8 +113,15 @@ public final class ClientProxy extends CommonProxy {
return CONFIG;
}
public static void applyVSyncMode(boolean vsyncEnabled) {
GLStateManager.setVSyncMode(options().advanced.vsyncMode, vsyncEnabled);
public static void toggleVSync(boolean enabled) {
final SodiumGameOptions opts = options();
opts.advanced.vsyncMode = enabled ? GLStateManager.preferredTearFreeMode() : VSyncMode.OFF;
try {
opts.writeChanges();
} catch (IOException e) {
AngelicaMod.LOGGER.warn("Could not persist the vsync mode", e);
}
GLStateManager.setVSyncMode(opts.advanced.vsyncMode);
}
@Override
@@ -121,6 +135,9 @@ public final class ClientProxy extends CommonProxy {
MinecraftForge.EVENT_BUS.register(new AngelicaTesrMeshCache.ReloadListener());
ModelRegistry.registerModid(MOD_ID);
blockError = new BlockError();
if (AngelicaConfig.enableIris) {
Iris.warmupShaderTransforms();
}
}
@Override
@@ -131,6 +148,16 @@ public final class ClientProxy extends CommonProxy {
HUDCaching.init();
}
CeleritasSetup.ensureInitialized();
final SodiumGameOptions opts = options();
if (opts.advanced.vsyncMode == null) {
opts.advanced.vsyncMode = FrameRateOptions.defaultMode();
}
Minecraft.getMinecraft().gameSettings.enableVsync = opts.advanced.vsyncMode.tearFree();
GLStateManager.setVSyncPreference(opts.advanced.vsyncMode);
FramePacer.setIdleWork(deadlineNanos -> {
final CeleritasWorldRenderer renderer = CeleritasWorldRenderer.getInstanceOrNull();
if (renderer != null) renderer.runFrameIdleWork(deadlineNanos);
});
MinecraftForge.EVENT_BUS.register(CeleritasDebugScreenHandler.INSTANCE);
if (AngelicaConfig.enableIris) {
IrisGLSMBridge.register();
@@ -190,9 +217,15 @@ public final class ClientProxy extends CommonProxy {
}
}
private long worldSection;
@SubscribeEvent
public void worldLoad(WorldEvent.Load event) {
if (!event.world.isRemote) return;
if (Tracy.ENABLED) {
Tracy.sectionLeave(this.worldSection);
this.worldSection = Tracy.sectionEnter(Tracy.SECTION_WORLD, "world " + event.world.provider.getDimensionName() + " (dim " + event.world.provider.dimensionId + ")");
}
if (GLStateManager.isRunningSplash()) {
GLStateManager.setRunningSplash(false);
LOGGER.info("World loaded - Enabling GLSM Cache");
@@ -212,6 +245,8 @@ public final class ClientProxy extends CommonProxy {
@SubscribeEvent
public void onWorldUnload(WorldEvent.Unload event) {
if (!event.world.isRemote) return;
Tracy.sectionLeave(this.worldSection);
this.worldSection = 0L;
DynamicLights.get().removeAllLightSources();
GpuCulling.onWorldUnload();
}
@@ -3,114 +3,304 @@ package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend;
import java.util.concurrent.locks.LockSupport;
public final class FramePacer {
public interface IdleWork {
void run(long deadlineNanos);
}
private static final int MIN_PLAUSIBLE_REFRESH_HZ = 20;
private static final int MAX_PLAUSIBLE_REFRESH_HZ = 1000;
private static final long REFRESH_POLL_NANOS = 1_000_000_000L;
private static final long IDLE_WORK_MIN_BUDGET_NANOS = 500_000L;
private static final long GATE_BLOCK_MIN_NANOS = 100_000L;
private static final int GATE_STREAK_FRAMES = 60;
static final int GATE_SETTLE_FRAMES = 120;
static final int PACING_HEADROOM_PERCENT = 5;
private static final Tracy.ZoneId Z_PACER_WAIT = Tracy.zoneId("pacerBackpressure", Tracy.COLOR_SWAP);
private static final Tracy.ZoneId Z_PACER_IDLE = Tracy.zoneId("pacerIdleWork", Tracy.COLOR_CLIENT);
private static final Tracy.ZoneId Z_PACER_SLEEP = Tracy.zoneId("pacerSleep", Tracy.COLOR_SWAP);
private static final long P_FRAME_GATE_US = Tracy.plotHandle("frameGateUs");
private static final long P_SLACK_US = Tracy.plotHandle("pacer.slackUs");
private static final long P_SPIN_US = Tracy.plotHandle("pacer.spinUs");
private static final long P_CEILING_HZ = Tracy.plotHandle("pacer.ceilingHz");
private static final long P_GATE_ACTIVE = Tracy.plotHandle("pacer.gateActive");
private static long deadline;
private static long lastFrameTime;
private static long fpsLimitOverhead;
private static long lastRefreshPollNanos;
private static int cachedRefreshHz;
private static boolean warnedUnknownRefresh;
private static boolean warnedUncapped;
private static boolean pacedLastFrame;
private static boolean statsActive;
private static VSyncMode lastVSyncMode = VSyncMode.ON;
private static int lastCapHz;
private static int lastRefreshHz;
private static IdleWork idleWork;
private static PacerSleeper sleeper = newSleeper();
private static int gateStreak;
private static Boolean settledBlocking;
private static boolean candidateBlocking;
private static int candidateFrames;
private static Boolean loggedBlocking;
private static VSyncMode loggedMode;
private static int loggedRefreshHz;
private static int loggedCapHz;
private static long lastSeenGateEnd;
private FramePacer() {}
private static PacerSleeper newSleeper() {
return new PacerSleeper(System::nanoTime, LockSupport::parkNanos, true);
}
public static void setIdleWork(IdleWork work) {
idleWork = work;
}
public static boolean pacedLastFrame() {
return pacedLastFrame;
}
public static void beginStats() {
sleeper.resetStats();
statsActive = true;
}
public static String endStats() {
statsActive = false;
final String summary = sleeper.summary(configLine());
Tracy.message(summary);
return summary;
}
static boolean statsActive() {
return statsActive;
}
static String configLine(VSyncMode mode, int refreshHz, int capHz, int ceilingHz) {
return "cfg=[" + mode + " refresh=" + refreshHz + "Hz cap=" + capHz + " ceiling=" + ceilingHz + "Hz]";
}
private static String configLine() {
return configLine(lastVSyncMode, lastRefreshHz, lastCapHz,
pacingCeilingHz(lastVSyncMode, lastCapHz, lastRefreshHz, gateActive()));
}
public static int plausibleRefreshHz(int hz) {
return hz >= MIN_PLAUSIBLE_REFRESH_HZ && hz <= MAX_PLAUSIBLE_REFRESH_HZ ? hz : 0;
}
public static int pacingCeilingHz(VSyncMode mode, int capHz, int refreshHz) {
if (mode.blocksOnVBlank()) return 0;
public static int withHeadroom(int hz, int percent) {
if (hz <= 0) return 0;
return (int) Math.max(hz + 1L, Math.round(hz * (100 + percent) / 100.0));
}
public static int pacingCeilingHz(VSyncMode mode, int capHz, int refreshHz, boolean gateActive) {
final int cap = Math.max(capHz, 0);
if (mode != VSyncMode.MAILBOX) return cap;
final int backstop = backstopHz(mode, refreshHz, gateActive);
if (cap == 0) return backstop;
if (backstop == 0) return cap;
return Math.min(cap, backstop);
}
static int backstopHz(VSyncMode mode, int refreshHz, boolean gateActive) {
if (!mode.tearFree()) return 0;
final int refresh = plausibleRefreshHz(refreshHz);
if (cap == 0) return refresh;
return refresh == 0 ? cap : Math.min(cap, refresh);
if (mode == VSyncMode.ON && gateActive) return withHeadroom(refresh, PACING_HEADROOM_PERCENT);
return refresh;
}
public static long sleepNanosFor(long targetNanos, long lastWorkNanos, long overheadNanos) {
return targetNanos - lastWorkNanos - overheadNanos;
static boolean observeGate(long gateNanos, long thresholdNanos) {
if (gateNanos > thresholdNanos) gateStreak = GATE_STREAK_FRAMES;
else if (gateStreak > 0) gateStreak--;
return gateStreak > 0;
}
public static int updateCeiling(int capHz) {
static boolean gateActive() {
return gateStreak > 0;
}
static Boolean settleGateBlocking(boolean observed) {
if (settledBlocking != null && observed == settledBlocking) {
candidateFrames = 0;
} else if (candidateFrames == 0 || observed != candidateBlocking) {
candidateBlocking = observed;
candidateFrames = 1;
} else if (++candidateFrames >= GATE_SETTLE_FRAMES) {
settledBlocking = observed;
candidateFrames = 0;
}
return settledBlocking;
}
static boolean vsyncNotHonoured(VSyncMode mode, boolean gateBlocking) {
return mode == VSyncMode.ON && !gateBlocking;
}
static boolean pacingStatusChanged(boolean blocking, VSyncMode mode, int refreshHz, int capHz) {
final Boolean settled = settleGateBlocking(blocking);
if (settled == null) return false;
if (settled.equals(loggedBlocking) && mode == loggedMode && refreshHz == loggedRefreshHz && capHz == loggedCapHz) {
return false;
}
loggedBlocking = settled;
loggedMode = mode;
loggedRefreshHz = refreshHz;
loggedCapHz = capHz;
return true;
}
static String pacingLine(VSyncMode mode, int refreshHz, int capHz, boolean gateBlocking) {
final StringBuilder sb = new StringBuilder("Frame pacing: ");
sb.append(switch (mode) {
case OFF -> "vsync off";
case MAILBOX -> "mailbox";
case ON -> "vsync";
});
if (mode.tearFree() && refreshHz > 0) sb.append(' ').append(refreshHz).append("Hz");
if (capHz > 0) sb.append(", cap ").append(capHz);
if (vsyncNotHonoured(mode, gateBlocking)) sb.append(", driver not blocking, paced by wall clock");
else if (gateBlocking) sb.append(", hardware paced");
return sb.toString();
}
static long gateBlockThresholdNanos(long targetNanos) {
return Math.max(GATE_BLOCK_MIN_NANOS, targetNanos / 32);
}
public static long nextDeadline(long previousDeadline, long now, long targetNanos) {
if (previousDeadline == 0L || now - previousDeadline > 2 * targetNanos) return now + targetNanos;
return previousDeadline + targetNanos;
}
public static long endFrame(int capHz, Runnable renderAheadWait) {
lastVSyncMode = GLStateManager.getEffectiveVSyncMode();
lastCapHz = Math.max(capHz, 0);
lastRefreshHz = refreshHz();
return pacingCeilingHz(lastVSyncMode, lastCapHz, lastRefreshHz);
return pace(pacingCeilingHz(lastVSyncMode, lastCapHz, lastRefreshHz, gateActive()), renderAheadWait);
}
public static long pace(int ceilingHz) {
public static long pace(int ceilingHz, Runnable renderAheadWait) {
long now = System.nanoTime();
long phaseEnd;
final long targetNanos = ceilingHz > 0 ? 1_000_000_000L / ceilingHz : 0L;
final long thresholdNanos = gateBlockThresholdNanos(targetNanos);
long frameGateNanos = 0L;
pacedLastFrame = ceilingHz > 0;
Tracy.plotInt(P_CEILING_HZ, ceilingHz);
if (ceilingHz > 0) {
final long time = System.nanoTime();
final long targetNanos = 1_000_000_000L / ceilingHz;
frameGateNanos = GLStateManager.lastFrameGateNanos();
final long gateEnd = GLStateManager.lastFrameGateEndNanos();
Tracy.plotInt(P_FRAME_GATE_US, frameGateNanos / 1000);
final long sleepNanos = sleepNanosFor(targetNanos, time - lastFrameTime, fpsLimitOverhead);
if (sleepNanos > 0) {
try {
Thread.sleep(sleepNanos / 1_000_000, (int) sleepNanos % 1_000_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
if (gateEnd != lastSeenGateEnd) {
lastSeenGateEnd = gateEnd;
if (frameGateNanos > thresholdNanos && GLStateManager.gateAnchorsNextFrameStart()) {
deadline = gateEnd;
}
long overhead = System.nanoTime() - time - sleepNanos;
if (overhead < 0 || overhead > targetNanos / 2) overhead = 0;
fpsLimitOverhead = overhead;
}
deadline = nextDeadline(deadline, now, targetNanos);
final IdleWork work = idleWork;
if (work != null && deadline - now > IDLE_WORK_MIN_BUDGET_NANOS) {
Tracy.beginZone(Z_PACER_IDLE);
try {
work.run(deadline);
} finally {
Tracy.endZone();
}
phaseEnd = System.nanoTime();
now = phaseEnd;
}
final long slackNanos = deadline - now;
Tracy.plotInt(P_SLACK_US, slackNanos / 1000);
final boolean slept = now < deadline;
if (slept) {
Tracy.beginZone(Z_PACER_SLEEP);
try {
now = sleeper.sleepUntil(deadline, now);
} finally {
Tracy.endZone();
}
}
if (Tracy.ENABLED || statsActive) {
sleeper.noteFrame(slackNanos, slept ? now - deadline : 0L, slept);
Tracy.plotInt(P_SPIN_US, sleeper.lastSpinNanos / 1000);
}
} else {
deadline = 0L;
}
final long time = System.nanoTime();
final long period = time - lastFrameTime;
lastFrameTime = time;
Tracy.beginZone(Z_PACER_WAIT);
try {
if (renderAheadWait != null) renderAheadWait.run();
} finally {
Tracy.endZone();
}
phaseEnd = System.nanoTime();
final long waitNanos = phaseEnd - now;
now = phaseEnd;
if (ceilingHz > 0 && waitNanos > thresholdNanos) deadline = now;
final boolean gateBlocking = observeGate(ceilingHz > 0 ? Math.max(frameGateNanos, waitNanos) : 0L, thresholdNanos);
Tracy.plotInt(P_GATE_ACTIVE, gateBlocking ? 1 : 0);
GLStateManager.pumpDisplayMessages();
if (pacingStatusChanged(gateBlocking, lastVSyncMode, lastRefreshHz, lastCapHz)) {
final boolean blocking = settledBlocking;
final String line = pacingLine(lastVSyncMode, lastRefreshHz, lastCapHz, blocking);
final boolean notHonoured = vsyncNotHonoured(lastVSyncMode, blocking);
if (notHonoured) AngelicaMod.LOGGER.warn(line);
else AngelicaMod.LOGGER.info(line);
Tracy.message(line, notHonoured ? TracyBackend.SEVERITY_WARNING : TracyBackend.SEVERITY_INFO);
}
final long period = lastFrameTime == 0L ? 0L : now - lastFrameTime;
lastFrameTime = now;
return period;
}
private static int refreshHz() {
final long now = System.nanoTime();
if (lastRefreshPollNanos == 0L || now - lastRefreshPollNanos >= REFRESH_POLL_NANOS) {
lastRefreshPollNanos = now;
cachedRefreshHz = GLStateManager.getDisplayRefreshRateHz();
}
final int hz = plausibleRefreshHz(cachedRefreshHz);
final int reported = GLStateManager.getDisplayRefreshRateHz();
final int hz = plausibleRefreshHz(reported);
if (hz == 0 && lastVSyncMode == VSyncMode.MAILBOX && !warnedUnknownRefresh) {
warnedUnknownRefresh = true;
AngelicaMod.LOGGER.warn("Display refresh rate reported as {}Hz; Mailbox will not be paced to the refresh rate. The Max Framerate setting still applies.", cachedRefreshHz);
if (hz == 0 && lastCapHz == 0 && lastVSyncMode.tearFree() && !warnedUncapped) {
warnedUncapped = true;
AngelicaMod.LOGGER.warn("Display refresh rate reported as {}Hz, so the frame rate cannot be bounded if the driver ignores vsync. Set Max Framerate to bound it.", reported);
}
return hz;
}
public static String debugIndicator(VSyncMode mode, int refreshHz, int capHz) {
final boolean vsync = mode.blocksOnVBlank();
final boolean mailbox = mode == VSyncMode.MAILBOX;
final boolean showCap = capHz > 0 && !vsync;
if (!vsync && !mailbox && !showCap) return null;
public static String debugIndicator(VSyncMode mode, int refreshHz, int capHz, boolean gateActive) {
final int cap = Math.max(capHz, 0);
final boolean showCap = cap > 0 && cap == pacingCeilingHz(mode, cap, refreshHz, gateActive);
if (!mode.tearFree() && !showCap) return null;
final StringBuilder sb = new StringBuilder(" [");
if (vsync || mailbox) {
sb.append(vsync ? "vsync" : "mailbox");
if (refreshHz > 0) sb.append(' ').append(refreshHz);
if (mode.tearFree()) {
sb.append(mode == VSyncMode.MAILBOX ? "mailbox" : "vsync");
final int refresh = plausibleRefreshHz(refreshHz);
if (refresh > 0) sb.append(' ').append(refresh);
if (showCap) sb.append(", ");
}
if (showCap) sb.append("cap ").append(capHz);
if (showCap) sb.append("cap ").append(cap);
return sb.append(']').toString();
}
public static String debugIndicator() {
return debugIndicator(lastVSyncMode, lastRefreshHz, lastCapHz);
return debugIndicator(lastVSyncMode, lastRefreshHz, lastCapHz, gateActive());
}
public static VSyncMode lastVSyncMode() { return lastVSyncMode; }
public static int lastCapHz() { return lastCapHz; }
public static int lastRefreshHz() { return lastRefreshHz; }
}
@@ -0,0 +1,122 @@
package com.gtnewhorizons.angelica.rendering;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
final class PacerSleeper {
private static final long MIN_PARK_NANOS = 1_000_000L;
private static final long MAX_OVERSHOOT_NANOS = 4_000_000L;
static final int SLOTS = 10;
static final long MIN_SPIN_FLOOR_NANOS = 20_000L;
private static final long MAX_SPIN_FLOOR_NANOS = 500_000L;
private final LongSupplier clock;
private final LongConsumer parker;
private final boolean spinWait;
private final long[] overshoots = new long[SLOTS];
private long overshootSum;
private long spinFloorNanos = MIN_SPIN_FLOOR_NANOS;
private int offset;
long lastSpinNanos;
int lastParks;
private long frames;
private long slackSum;
private long parkTotal;
private long lateFrames;
private long lateMax;
PacerSleeper(LongSupplier clock, LongConsumer parker, boolean spinWait) {
this.clock = clock;
this.parker = parker;
this.spinWait = spinWait;
}
long spinFloorNanos() {
return spinFloorNanos;
}
long sleepUntil(long deadlineNanos, long now) {
resetLastFrame();
long spinFloor = spinFloorNanos;
while (true) {
final long remaining = deadlineNanos - now;
if (remaining <= spinFloor) break;
if (Thread.currentThread().isInterrupted()) return clock.getAsLong();
long request = remaining - avgOvershootNanos() - spinFloor;
if (request <= 0L) {
if (remaining <= MIN_PARK_NANOS) break;
request = MIN_PARK_NANOS;
}
final long before = now;
parker.accept(request);
now = clock.getAsLong();
record(Math.min(Math.max(0L, now - before - request), MAX_OVERSHOOT_NANOS));
spinFloor = spinFloorNanos;
lastParks++;
}
if (spinWait) {
final long spinStart = now;
while (now < deadlineNanos) {
if (deadlineNanos - now > spinFloor) Thread.yield();
else Thread.onSpinWait();
now = clock.getAsLong();
}
lastSpinNanos = now - spinStart;
}
return now;
}
void noteFrame(long slackNanos, long wakeLateNanos, boolean slept) {
if (!slept) resetLastFrame();
frames++;
slackSum += slackNanos;
parkTotal += lastParks;
if (slackNanos < 0L && -slackNanos > lateMax) lateMax = -slackNanos;
if (slackNanos < 0L || wakeLateNanos > 0L) lateFrames++;
}
private void resetLastFrame() {
lastSpinNanos = 0L;
lastParks = 0;
}
void resetStats() {
frames = 0L;
slackSum = 0L;
parkTotal = 0L;
lateFrames = 0L;
lateMax = 0L;
}
String summary(String config) {
if (frames == 0L) return "pacer: " + config + " no paced frames";
return "pacer: " + config + " frames=" + frames + " parks=" + parkTotal + " slackUs avg=" + slackSum / frames / 1000L + " floorUs=" + spinFloorNanos / 1000L
+ " overshootUs est=" + avgOvershootNanos() / 1000L + " lateFrames=" + lateFrames + " lateMaxUs=" + lateMax / 1000L;
}
long avgOvershootNanos() {
return overshootSum / SLOTS;
}
private void record(long nanos) {
overshootSum += nanos - overshoots[offset];
overshoots[offset] = nanos;
offset = (offset + 1) % SLOTS;
long max = 0L;
for (final long o : overshoots) {
if (o > max) max = o;
}
final long jitter = max - avgOvershootNanos();
spinFloorNanos = Math.max(MIN_SPIN_FLOOR_NANOS, Math.min(MAX_SPIN_FLOOR_NANOS, jitter));
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import net.minecraft.tileentity.TileEntity;
public class RenderThreadContext {
@@ -15,10 +15,13 @@ public class RenderThreadContext {
currentWorldSlice.remove();
}
public static TileEntity getSnapshotTE(int x, int y, int z) {
final WorldSlice slice = currentWorldSlice.get();
if (slice == null) return null;
return slice.getTileEntity(x, y, z);
public static WorldSlice get() {
return currentWorldSlice.get();
}
public static WorldSlice workerSlice() {
if (TessellatorManager.isOnMainThread()) return null;
return currentWorldSlice.get();
}
public static boolean hasWorldSlice() {
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.rendering;
import it.unimi.dsi.fastutil.objects.Reference2ByteOpenHashMap;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
@@ -17,25 +16,12 @@ public final class TileEntityRenderBoundsRegistry {
public static final byte INFINITE = 2;
public static final byte DYNAMIC = 3;
public static final byte PASS0_ONLY = 1;
public static final byte PASS_OVERRIDES = 2;
private static final byte NOT_OVERRIDDEN = 1;
private static final byte OVERRIDDEN = 2;
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> classRegistry = new Reference2ByteOpenHashMap<>();
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> passClassRegistry = new Reference2ByteOpenHashMap<>();
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> distanceOverrideRegistry = new Reference2ByteOpenHashMap<>();
private static final Set<String> dynamicClassNames = ConcurrentHashMap.newKeySet();
private static final String[] SHOULD_RENDER_IN_PASS_NAMES = { "shouldRenderInPass" };
private static String[] distanceFromNames;
static {
classRegistry.defaultReturnValue(UNKNOWN);
passClassRegistry.defaultReturnValue(UNKNOWN);
distanceOverrideRegistry.defaultReturnValue(UNKNOWN);
}
private TileEntityRenderBoundsRegistry() {}
@@ -73,72 +59,4 @@ public final class TileEntityRenderBoundsRegistry {
}
return result;
}
public static boolean overridesMethod(Class<?> clazz, Class<?> base, String[] candidateNames, Class<?>... params) {
for (String name : candidateNames) {
try {
return clazz.getMethod(name, params).getDeclaringClass() != base;
} catch (NoSuchMethodException ignored) {
} catch (Throwable t) {
return true;
}
}
return true;
}
private static String[] distanceFromNames() {
String[] names = distanceFromNames;
if (names == null) {
String resolved;
try {
resolved = Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment")) ? "getDistanceFrom" : "func_145835_a";
} catch (Throwable t) {
resolved = "getDistanceFrom";
}
distanceFromNames = names = new String[] { resolved };
}
return names;
}
public static byte classifyPass(TileEntity te) {
final Class<? extends TileEntity> clazz = te.getClass();
synchronized (passClassRegistry) {
final byte cached = passClassRegistry.getByte(clazz);
if (cached != UNKNOWN) return cached;
}
final byte result = overridesMethod(clazz, TileEntity.class, SHOULD_RENDER_IN_PASS_NAMES, int.class)
? PASS_OVERRIDES : PASS0_ONLY;
synchronized (passClassRegistry) {
passClassRegistry.put(clazz, result);
}
return result;
}
public static boolean overridesGetDistanceFrom(Class<? extends TileEntity> clazz) {
synchronized (distanceOverrideRegistry) {
final byte cached = distanceOverrideRegistry.getByte(clazz);
if (cached != UNKNOWN) return cached == OVERRIDDEN;
}
final boolean overrides = overridesMethod(clazz, TileEntity.class, distanceFromNames(), double.class, double.class, double.class);
synchronized (distanceOverrideRegistry) {
distanceOverrideRegistry.put(clazz, overrides ? OVERRIDDEN : NOT_OVERRIDDEN);
}
return overrides;
}
public static void clear() {
synchronized (classRegistry) {
classRegistry.clear();
}
synchronized (passClassRegistry) {
passClassRegistry.clear();
}
synchronized (distanceOverrideRegistry) {
distanceOverrideRegistry.clear();
}
}
}
@@ -0,0 +1,120 @@
package com.gtnewhorizons.angelica.rendering;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.util.Arrays;
import net.minecraft.block.Block;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
public final class WorkerWorldAccess {
private static final String REPORT_URL = "https://github.com/GTNewHorizons/angelica/issues";
private static final int INITIAL_SLOTS = 64;
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final LoggedRenderTypeErrors READS = new LoggedRenderTypeErrors();
private static final LoggedRenderTypeErrors WRITES = new LoggedRenderTypeErrors();
private WorkerWorldAccess() {}
public static void readOutsideSlice(String worldMethod, int x, int y, int z, Block renderingBlock) {
if (!READS.shouldLog(renderingBlock)) return;
LOGGER.warn(describe(worldMethod, "read outside the chunk slice", x, y, z, renderingBlock), new Throwable());
}
public static void blockedWrite(String worldMethod, int x, int y, int z, Block renderingBlock) {
if (!WRITES.shouldLog(renderingBlock)) return;
LOGGER.error(describe(worldMethod, "ignored, it would corrupt world data", x, y, z, renderingBlock), new Throwable());
}
private static String describe(String worldMethod, String outcome, int x, int y, int z, Block block) {
final StringBuilder sb = new StringBuilder(224);
sb.append("Off-thread World.").append(worldMethod).append(' ').append(outcome).append(" at ").append(x).append(',').append(y).append(',').append(z);
if (block != null) {
sb.append(". Rendering ").append(nameOf(block));
final ISimpleBlockRenderingHandler isbrh = isbrhOf(block);
if (isbrh != null) {
sb.append(" via ").append(isbrh.getClass().getName());
final String owner = modIdOf(isbrh.getClass());
if (owner != null) sb.append(" from ").append(owner);
}
}
return sb.append(". Please report with this trace: ").append(REPORT_URL).toString();
}
private static String nameOf(Block block) {
try {
final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(block);
if (id != null) return id.modId + ':' + id.name;
} catch (Throwable ignored) {}
return block.getClass().getName();
}
@SuppressWarnings("deprecation")
private static ISimpleBlockRenderingHandler isbrhOf(Block block) {
try {
return ((IRenderingRegistryExt) RenderingRegistry.instance()).getISBRH(block.getRenderType());
} catch (Throwable ignored) {
return null;
}
}
private static String modIdOf(Class<?> clazz) {
try {
final CodeSource source = clazz.getProtectionDomain() == null ? null : clazz.getProtectionDomain().getCodeSource();
if (source == null || source.getLocation() == null) return null;
final File jar = new File(jarFileUrl(source.getLocation()).toURI());
for (ModContainer mod : Loader.instance().getModList()) {
if (jar.equals(mod.getSource())) return mod.getModId();
}
} catch (Throwable ignored) {}
return null;
}
private static URL jarFileUrl(URL location) throws MalformedURLException {
if (!"jar".equals(location.getProtocol())) return location;
final String nested = location.getPath();
final int separator = nested.indexOf("!/");
return new URL(separator < 0 ? nested : nested.substring(0, separator));
}
private static final class LoggedRenderTypeErrors {
private volatile boolean[] logged = new boolean[INITIAL_SLOTS];
boolean shouldLog(Block block) {
final int renderType = block == null ? -1 : block.getRenderType();
final int slot = renderType < 0 ? 0 : renderType + 1;
final boolean[] current = this.logged;
return (slot >= current.length || !current[slot]) && markLogged(slot);
}
private synchronized boolean markLogged(int slot) {
boolean[] current = this.logged;
if (slot < current.length) {
if (current[slot]) return false;
current[slot] = true;
return true;
}
current = Arrays.copyOf(current, Math.max(slot + 1, current.length * 2));
current[slot] = true;
this.logged = current;
return true;
}
}
}
@@ -4,11 +4,13 @@ import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.mixins.interfaces.OverridesGetDistanceFrom;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVertexEncoder;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
@@ -111,6 +113,8 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
final BlockPos blockPos = new BlockPos(minX, minY, minZ);
final IBlockAccess region = getBlockAccess();
final WorldSlice reportingSlice = region instanceof WorldSlice slice ? slice : null;
if (reportingSlice != null) reportingSlice.setRenderingBlock(null);
final SmoothBiomeColorCache biomeColorCache = getBiomeColorCache();
onEnterExecute();
@@ -155,6 +159,8 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
continue;
}
if (reportingSlice != null) reportingSlice.setRenderingBlock(block);
final int meta = region.getBlockMetadata(x, y, z);
if (block.hasTileEntity(meta)) {
@@ -185,7 +191,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
renderData.culledBlockEntities.add(tileEntity);
AngelicaBuiltRenderSectionData.packSectionLocalBounds(culledBounds, aabb, minX, minY, minZ);
double teDistSq;
if (TileEntityRenderBoundsRegistry.overridesGetDistanceFrom(tileEntity.getClass())) {
if (tileEntity instanceof OverridesGetDistanceFrom) {
teDistSq = Double.POSITIVE_INFINITY;
} else {
try {
@@ -12,6 +12,7 @@ import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACK
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer;
import com.gtnewhorizons.angelica.glsm.states.FogState;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import cpw.mods.fml.common.eventhandler.EventPriority;
@@ -78,10 +79,6 @@ public class CeleritasDebugScreenHandler {
if (transferInfo != null) {
lines.add(transferInfo);
}
final String presentInfo = RENDER_BACKEND.getPresentDebugInfo();
if (presentInfo != null) {
lines.add(presentInfo);
}
if (SystemProperties.DEBUG_F3_DETAIL) {
lines.addAll(TesrBatchRenderer.INSTANCE.getDebugDetailStrings());
lines.add(ModelPartBatcher.INSTANCE.getDebugString());
@@ -21,6 +21,7 @@ import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData;
@@ -44,6 +45,7 @@ import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.mixins.interfaces.OverridesShouldRenderInPass;
import com.gtnewhorizons.angelica.profiling.RenderClassTimings;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.RenderingState;
@@ -114,6 +116,34 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return this.renderSectionManager;
}
private long asyncEwmaNanos;
private long uploadEwmaNanos;
private static long blendEwma(long ewmaNanos, long tookNanos) {
return ewmaNanos == 0L ? tookNanos : (ewmaNanos * 3 + tookNanos) / 4;
}
public void runFrameIdleWork(long deadlineNanos) {
final AngelicaRenderSectionManager rsm = this.renderSectionManager;
if (rsm == null || this.world == null) return;
RenderDevice.enterManagedCode();
try {
long start = System.nanoTime();
if (start + asyncEwmaNanos > deadlineNanos) return;
rsm.runAsyncTasks();
long now = System.nanoTime();
asyncEwmaNanos = blendEwma(asyncEwmaNanos, now - start);
start = now;
if (start + uploadEwmaNanos > deadlineNanos) return;
rsm.uploadChunks();
now = System.nanoTime();
uploadEwmaNanos = blendEwma(uploadEwmaNanos, now - start);
} finally {
RenderDevice.exitManagedCode();
}
}
@Override
public boolean isActive() {
return this.world != null;
@@ -376,7 +406,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
try {
for (int i = 0; i < frameTEs.size(); i++) {
final TileEntity te = frameTEs.get(i);
if (((ITileEntityBoundingBoxCache) te).angelica$passClass() == TileEntityRenderBoundsRegistry.PASS0_ONLY) {
if (!(te instanceof OverridesShouldRenderInPass)) {
dispatchTE(te, partialTicks);
count++;
continue;
@@ -104,6 +104,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
// The chunk origin of this slice
private ChunkSectionPos origin;
private StructureBoundingBox volume;
private Block renderingBlock;
private final SmoothBiomeColorCache biomeColorCache;
@@ -530,6 +531,18 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
return y << TABLE_BITS << TABLE_BITS | z << TABLE_BITS | x;
}
public boolean containsBlock(int x, int y, int z) {
return blockBoxContains(this.volume, x, y, z);
}
public void setRenderingBlock(Block block) {
this.renderingBlock = block;
}
public Block getRenderingBlock() {
return this.renderingBlock;
}
private static boolean blockBoxContains(StructureBoundingBox box, int x, int y, int z) {
return x >= box.minX && x <= box.maxX &&
y >= box.minY && y <= box.maxY &&
@@ -158,9 +158,8 @@ public final class TesrBatchRenderer {
boolean depthEqual;
TesrMaterial.SpecialRender special;
TesrShader shader;
boolean noPass;
LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass) {
LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader) {
this.texture = texture;
this.transparency = transparency;
this.noCull = noCull;
@@ -171,12 +170,11 @@ public final class TesrBatchRenderer {
this.depthEqual = depthEqual;
this.special = special;
this.shader = shader;
this.noPass = noPass;
return this;
}
LayerKey copy() {
return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass);
return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader);
}
@Override
@@ -186,7 +184,7 @@ public final class TesrBatchRenderer {
&& noCull == other.noCull && unlit == other.unlit && noDepthWrite == other.noDepthWrite
&& depthOnly == other.depthOnly
&& Float.floatToIntBits(cutoutAlpha) == Float.floatToIntBits(other.cutoutAlpha)
&& depthEqual == other.depthEqual && special == other.special && shader == other.shader && noPass == other.noPass;
&& depthEqual == other.depthEqual && special == other.special && shader == other.shader;
}
@Override
@@ -201,7 +199,6 @@ public final class TesrBatchRenderer {
h = h * 31 + (depthEqual ? 1 : 0);
h = h * 31 + Objects.hashCode(special);
h = h * 31 + System.identityHashCode(shader);
h = h * 31 + (noPass ? 1 : 0);
return h;
}
}
@@ -211,37 +208,23 @@ public final class TesrBatchRenderer {
private ResourceLocation lastLayerTexture;
private TesrMaterial lastLayerMaterial;
private RenderLayer lastLayer;
private ResourceLocation lastImmediateTexture;
private TesrMaterial lastImmediateMaterial;
private RenderLayer lastImmediateLayer;
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material) {
if (texture == lastLayerTexture && material == lastLayerMaterial) {
return lastLayer;
}
final RenderLayer layer = layerLookup(texture, material, false);
final RenderLayer layer = layerLookup(texture, material);
lastLayerTexture = texture;
lastLayerMaterial = material;
lastLayer = layer;
return layer;
}
private RenderLayer noPassLayerFor(ResourceLocation texture, TesrMaterial material) {
if (texture == lastImmediateTexture && material == lastImmediateMaterial) {
return lastImmediateLayer;
}
final RenderLayer layer = layerLookup(texture, material, true);
lastImmediateTexture = texture;
lastImmediateMaterial = material;
lastImmediateLayer = layer;
return layer;
}
private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass) {
final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass);
private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material) {
final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader());
RenderLayer layer = layers.get(key);
if (layer == null) {
layer = noPass ? RenderLayer.tesrNoPass(texture, material) : RenderLayer.tesr(texture, material);
layer = RenderLayer.tesr(texture, material);
layers.put(key.copy(), layer);
}
return layer;
@@ -469,7 +452,7 @@ public final class TesrBatchRenderer {
final long end = VertexTransform.writeInstance(addr, format, template, identity, scratchVec, colorABGR, packedLight, null);
immediateScratch.position((int) (end - addr));
immediateScratch.flip();
final RenderLayer layer = noPassLayerFor(texture, material);
final RenderLayer layer = layerFor(texture, material);
GLStateManager.glPushAttrib(AngelicaBufferSource.SAVED_STATE_BITS);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
layer.startDrawing();
@@ -0,0 +1,53 @@
package com.gtnewhorizons.angelica.utils;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.tileentity.TileEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.mixins.interfaces.AwaitingDescriptorTE;
import com.gtnewhorizons.angelica.mixins.interfaces.SendsDescriptionPacket;
public final class AwaitingDescriptor {
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final int WAIT_TICKS = 100;
private static final Set<Class<?>> NEVER_SENT = Collections.newSetFromMap(new ConcurrentHashMap<>());
private AwaitingDescriptor() {}
public static void begin(TileEntity te) {
if (!(te instanceof SendsDescriptionPacket) || NEVER_SENT.contains(te.getClass())) return;
final AwaitingDescriptorTE tile = (AwaitingDescriptorTE) te;
tile.angelica$setAwaitingDescriptor(true);
tile.angelica$setDescriptorWaitTicks(WAIT_TICKS);
}
public static void end(AwaitingDescriptorTE tile) {
tile.angelica$setAwaitingDescriptor(false);
tile.angelica$setDescriptorWaitTicks(0);
}
public static boolean defersUpdate(TileEntity te) {
final AwaitingDescriptorTE tile = (AwaitingDescriptorTE) te;
final int waiting = tile.angelica$getDescriptorWaitTicks();
if (waiting <= 0) return false;
tile.angelica$setDescriptorWaitTicks(waiting - 1);
if (waiting == 1) stopWaitingOn(te.getClass());
return true;
}
private static void stopWaitingOn(Class<?> cls) {
if (NEVER_SENT.add(cls)) {
LOGGER.warn("{} declares getDescriptionPacket() but never sent one", cls.getName());
}
}
}
@@ -202,7 +202,8 @@ public class ConcurrentTileEntityMap extends HashMap<ChunkPosition, TileEntity>
if (!isRenderWorkerThread()) return delegate.containsKey(key);
lock.readLock().lock();
try {
return delegate.containsKey(key);
final TileEntity te = delegate.get(key);
return te != null && !te.isInvalid();
} finally {
lock.readLock().unlock();
}
@@ -14,39 +14,63 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import java.util.Arrays;
import java.util.Locale;
public record FrameRateOptions(Option<VSyncMode> vsync, Option<Integer> maxFramerate) {
public static FrameRateOptions create(MinecraftOptionsStorage vanillaOpts, SodiumOptionsStorage sodiumOpts) {
final VSyncMode[] allowed = selectableModes();
final String[] names = modeNames(VSyncMode.values());
final OptionImpl<SodiumGameOptions, VSyncMode> vsync = OptionImpl.createBuilder(VSyncMode.class, sodiumOpts)
.setName(I18n.format("options.vsync"))
.setTooltip(I18n.format("sodium.options.v_sync.tooltip"))
.setControl(option -> new CyclingControl<>(option, VSyncMode.class,
GLStateManager.getSelectableVSyncModes().toArray(new VSyncMode[0]),
new String[]{
I18n.format("sodium.options.vsync_mode.auto"),
I18n.format("sodium.options.vsync_mode.on"),
I18n.format("sodium.options.vsync_mode.mailbox"),
I18n.format("sodium.options.vsync_mode.off")}))
.setControl(option -> new CyclingControl<>(option, VSyncMode.class, allowed, names))
.setBinding((opts, value) -> {
opts.advanced.vsyncMode = value;
final GameSettings settings = Minecraft.getMinecraft().gameSettings;
settings.enableVsync = value.tearFree();
settings.saveOptions();
GLStateManager.setVSyncMode(value, settings.enableVsync);
}, opts -> opts.advanced.vsyncMode.resolve(Minecraft.getMinecraft().gameSettings.enableVsync))
final Minecraft mc = Minecraft.getMinecraft();
mc.gameSettings.enableVsync = value.tearFree();
mc.gameSettings.saveOptions();
GLStateManager.setVSyncMode(value);
}, FrameRateOptions::storedMode)
.setImpact(OptionImpact.VARIES)
.build();
final OptionImpl<GameSettings, Integer> maxFramerate = OptionImpl.createBuilder(int.class, vanillaOpts)
.setName(I18n.format("options.framerateLimit"))
.setTooltip(I18n.format("sodium.options.fps_limit.tooltip"))
.setControl(option -> new SliderControl(option, 5, 260, 5, ControlValueFormatter.fpsLimit()))
.setControl(option -> new SliderControl(option, 5, 260, 1, ControlValueFormatter.fpsLimit()))
.setBinding((opts, value) -> opts.limitFramerate = value, opts -> opts.limitFramerate)
.build();
maxFramerate.iris$dynamicallyEnable(() -> !vsync.getValue().blocksOnVBlank());
return new FrameRateOptions(vsync, maxFramerate);
}
static VSyncMode[] selectableModes() {
final VSyncMode[] supported = Arrays.stream(VSyncMode.values())
.filter(GLStateManager::supportsVSyncMode)
.toArray(VSyncMode[]::new);
return supported.length == 0 ? new VSyncMode[]{ VSyncMode.ON } : supported;
}
static String[] modeKeys(VSyncMode[] modes) {
return Arrays.stream(modes)
.map(mode -> "sodium.options.vsync_mode." + mode.name().toLowerCase(Locale.ROOT))
.toArray(String[]::new);
}
private static String[] modeNames(VSyncMode[] modes) {
return Arrays.stream(modeKeys(modes)).map(I18n::format).toArray(String[]::new);
}
public static VSyncMode defaultMode() {
return Minecraft.getMinecraft().gameSettings.enableVsync ? GLStateManager.preferredTearFreeMode() : VSyncMode.OFF;
}
public static VSyncMode storedMode(SodiumGameOptions opts) {
final VSyncMode stored = opts.advanced.vsyncMode;
if (stored == null) return defaultMode();
return GLStateManager.supportsVSyncMode(stored) ? stored : VSyncMode.ON;
}
}
@@ -55,6 +55,9 @@ public class SodiumGameOptionPages {
private static final MinecraftOptionsStorage vanillaOpts = new MinecraftOptionsStorage();
private static final AngelicaOptionsStorage angelicaOpts = new AngelicaOptionsStorage();
private static final int MIN_RENDER_AHEAD = 0;
private static final int MAX_RENDER_AHEAD = 9;
public static OptionPage general() {
final List<OptionGroup> groups = new ArrayList<>();
final OptionGroup.Builder firstGroupBuilder = OptionGroup.createBuilder();
@@ -508,12 +511,9 @@ public class SodiumGameOptionPages {
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setName(I18n.format("sodium.options.cpu_render_ahead_limit.name"))
.setTooltip(I18n.format("sodium.options.cpu_render_ahead_limit.tooltip"))
.setControl(o -> new SliderControl(o, GLStateManager.getMinRenderAhead(), GLStateManager.getMaxRenderAhead(), 1, ControlValueFormatter.quantity("sodium.options.cpu_render_ahead_limit.value")))
.setControl(o -> new SliderControl(o, MIN_RENDER_AHEAD, MAX_RENDER_AHEAD, 1, ControlValueFormatter.quantity("sodium.options.cpu_render_ahead_limit.value")))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> {
opts.performance.cpuRenderAheadLimit = value;
GLStateManager.applyRenderAheadLimit(value);
}, opts -> GLStateManager.renderAheadLimit(opts.performance.cpuRenderAheadLimit))
.setBinding((opts, value) -> opts.performance.cpuRenderAheadLimit = value, opts -> opts.performance.cpuRenderAheadLimit)
.setEnabled(GLStateManager.capabilities != null && GLStateManager.capabilities.OpenGL32)
.build())
@@ -195,6 +195,7 @@ public class SodiumGameOptions {
}
public static class AdvancedSettings {
public VSyncMode vsyncMode;
public boolean useVertexArrayObjects = true;
public boolean useChunkMultidraw = true;
public MultiDrawMode multiDrawMode = MultiDrawMode.DIRECT;
@@ -204,7 +205,6 @@ public class SodiumGameOptions {
public boolean ignoreDriverBlacklist = false;
public StreamingUploader.UploadStrategy streamingUploadStrategy = StreamingUploader.UploadStrategy.MAP_BUFFER_RANGE;
public boolean enableDeferredBatching = true;
public VSyncMode vsyncMode = VSyncMode.AUTO;
}
public static class PerformanceSettings {
+15
View File
@@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler;
import com.gtnewhorizons.angelica.iris.IrisGLSMBridge;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
@@ -533,6 +534,20 @@ public class Iris {
}
}
public static void warmupShaderTransforms() {
if (currentPack == null) return;
try {
if (BackendManager.RENDER_BACKEND.isSDLGPU()) {
IrisGLSMBridge.installPostTransformHook();
}
final ProgramSet programs = currentPack.getProgramSet(lastDimensionName != null ? lastDimensionName : "Overworld");
PerFrameUniformBlockHarvester.harvest(programs);
DeferredWorldRenderingPipeline.warmupTransforms(programs);
} catch (Throwable t) {
logger.warn("Early shader transform warmup failed; transforms will run at pipeline creation", t);
}
}
private static boolean loadExternalShaderpack(String name) {
final Path shaderPackRoot;
final Path shaderPackConfigTxt;
@@ -119,6 +119,7 @@ import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntFunction;
import java.util.function.Supplier;
@@ -236,6 +237,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final long _t0 = System.nanoTime();
long _tLast = _t0;
final int entryTextureUnit = GLStateManager.getActiveTextureUnit();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE2);
customTextureManager = new CustomTextureManager(programs.getPackDirectives(), programs.getPack().getCustomTextureDataMap(), programs.getPack().getIrisCustomTextureDataMap(), programs.getPack().getCustomNoiseTexture());
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + entryTextureUnit);
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> prepareTransformFutures =
submitCompositeTransforms(programs.getPrepare(), TextureStage.PREPARE, programs.getPackDirectives().getTextureMap());
final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> deferredTransformFutures =
@@ -340,8 +346,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
// Don't clobber anything in texture unit 0. It probably won't cause issues, but we're just being cautious here.
GLStateManager.glActiveTexture(GL13.GL_TEXTURE2);
customTextureManager = new CustomTextureManager(programs.getPackDirectives(), programs.getPack().getCustomTextureDataMap(), programs.getPack().getIrisCustomTextureDataMap(), programs.getPack().getCustomNoiseTexture());
whitePixel = new NativeImageBackedSingleColorTexture(255, 255, 255, 255);
// Initialize custom images
@@ -488,7 +492,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.instancedAttributeTransforms = new HashMap<>();
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : instancedTransformFutures.entrySet()) {
try {
this.instancedAttributeTransforms.put(entry.getKey(), entry.getValue().join());
final Map<PatchShaderType, String> transformed = entry.getValue().join();
if (transformed == null) continue;
this.instancedAttributeTransforms.put(entry.getKey(), transformed);
} catch (Exception e) {
Iris.logger.warn("Instanced transform failed for {}; disabling TESR instancing", entry.getKey().getLeft(), e);
supportsTesrInstancing = false;
@@ -2174,20 +2180,26 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, boolean instanced) {
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>();
final Set<String> processedSourceNames = new HashSet<>();
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
for (ProgramId id : ids) {
if (id.getGroup() == ProgramGroup.Dh) continue;
final ProgramSource source = resolver.resolveNullable(id);
if (source == null || !processedSourceNames.add(source.getName())) {
continue;
}
if (instanced && referencesMvBuiltinsOutsideVertex(source)) {
Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", source.getName());
continue;
}
final String vertexSource = source.getVertexSource().orElse(null);
final boolean scrollGlint = GlintScrollInjector.shouldInject(id, source);
for (InputAvailability avail : INPUT_AVAILABILITIES) {
futures.put(Pair.of(source.getName(), avail), Iris.ShaderTransformExecutor.submitTracked(() -> {
if (instanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> {
final boolean references = referencesMvBuiltinsOutsideVertex(source);
if (references) {
Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", k);
}
return references;
})) {
return null;
}
final String geometry = source.getGeometrySource().orElse(null);
final String tessControl = source.getTessControlSource().orElse(null);
final String tessEval = source.getTessEvalSource().orElse(null);
@@ -2263,4 +2275,38 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return Optional.empty();
}
public static void warmupTransforms(ProgramSet programs) {
final Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> tm = programs.getPackDirectives().getTextureMap();
submitCompositeTransforms(programs.getPrepare(), TextureStage.PREPARE, tm);
submitCompositeTransforms(programs.getDeferred(), TextureStage.DEFERRED, tm);
submitCompositeTransforms(programs.getComposite(), TextureStage.COMPOSITE_AND_FINAL, tm);
programs.getCompositeFinal().filter(ProgramSource::isValid)
.ifPresent(source -> submitCompositeTransform(source, TextureStage.COMPOSITE_AND_FINAL, tm));
final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
submitAttributeTransforms(resolver, ProgramId.values(), false);
submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true);
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
final Optional<ProgramSource> shadowSource = programs.getShadow();
final Optional<ProgramSource> shadowTranslucentSource = first(programs.getShadowWater(), shadowSource);
terrainSource.ifPresent(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform);
translucentSource.ifPresent(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform);
shadowSource.ifPresent(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform);
shadowTranslucentSource.ifPresent(DeferredWorldRenderingPipeline::submitCeleritasTerrainTransform);
submitSetupComputeTransforms(programs.getSetup(), tm);
final ComputeSource[] shadowCompute = programs.getShadowCompute();
if (shadowCompute != null) {
for (final ComputeSource source : shadowCompute) {
if (source == null || !source.getSource().isPresent()) continue;
final String name = source.getName();
final String src = source.getSource().get();
Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchCompute(name, src, TextureStage.GBUFFERS_AND_SHADOW, tm));
}
}
}
}
@@ -1,6 +1,7 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
@@ -19,6 +20,7 @@ public class PipelineManager {
private final Map<String, WorldRenderingPipeline> pipelinesPerDimension = new HashMap<>();
private WorldRenderingPipeline pipeline = new FixedFunctionWorldRenderingPipeline();
private String lastPreparedDimension = null;
private long shaderSection;
@Getter
private int versionCounterForSodiumShaderReload = 0;
@@ -41,6 +43,9 @@ public class PipelineManager {
Iris.logger.info("Creating pipeline for dimension '{}'", currentDimension);
pipeline = pipelineFactory.apply(currentDimension);
pipelinesPerDimension.put(currentDimension, pipeline);
if (Tracy.ENABLED) {
shaderSection = Tracy.sectionEnter(Tracy.SECTION_SHADERS, "shaders " + Iris.getCurrentPackName() + " / " + currentDimension);
}
} else {
pipeline = pipelinesPerDimension.get(currentDimension);
}
@@ -70,6 +75,8 @@ public class PipelineManager {
* @see <a href="https://github.com/IrisShaders/Iris/issues/1330">this GitHub issue</a>
*/
public void destroyPipeline() {
Tracy.sectionLeave(shaderSection);
shaderSection = 0L;
pipelinesPerDimension.forEach((dimensionName, pipeline) -> {
Iris.logger.info("Destroying pipeline for dimension '{}'", dimensionName);
resetTextureState();
@@ -13,9 +13,14 @@ import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.Arrays;
import java.util.EnumMap;
@@ -108,58 +113,71 @@ public class ShaderTransformer {
return NegotiationResult.error("Shader requires GLSL " + effectiveVersion + " but hardware max is " + maxGlsl);
}
private static Pattern hoistPattern;
/** By capturing group: a prefix match's text is not the keyword, so it cannot be looked up by name. */
private static int[] hoistGroupVersions;
private static VersionRequirement[] enabledRequirements;
private static int maxSupportedHoistVersion;
public static void init() {
final StringBuilder patternBuilder = new StringBuilder();
final int[] groupVersions = new int[VERSION_REQUIREMENTS.length + 1];
int groupCount = 0;
enabledRequirements = Arrays.stream(VERSION_REQUIREMENTS)
.filter(req -> req.supported.getAsBoolean())
.toArray(VersionRequirement[]::new);
int maxVersion = 0;
for (VersionRequirement req : VERSION_REQUIREMENTS) {
if (req.supported.getAsBoolean()) {
if (!patternBuilder.isEmpty()) patternBuilder.append('|');
patternBuilder.append("(\\b").append(Pattern.quote(req.keyword)) .append(req.prefix ? "\\w*" : "\\b").append(')');
groupVersions[++groupCount] = req.minVersion;
maxVersion = Math.max(maxVersion, req.minVersion);
}
}
if (!patternBuilder.isEmpty()) {
hoistPattern = Pattern.compile(patternBuilder.toString());
hoistGroupVersions = Arrays.copyOf(groupVersions, groupCount + 1);
for (VersionRequirement req : enabledRequirements) {
maxVersion = Math.max(maxVersion, req.minVersion);
}
maxSupportedHoistVersion = maxVersion;
Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", groupCount, maxVersion > 0 ? maxVersion : "N/A");
Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", enabledRequirements.length, maxVersion > 0 ? maxVersion : "N/A");
}
private static int getRequiredVersion(String shaderSource, int declaredVersion) {
if (hoistPattern == null || declaredVersion >= maxSupportedHoistVersion) {
if (enabledRequirements == null || enabledRequirements.length == 0 || declaredVersion >= maxSupportedHoistVersion) {
return declaredVersion;
}
final Matcher m = hoistPattern.matcher(shaderSource);
final GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(shaderSource));
int required = declaredVersion;
while (m.find()) {
for (int group = 1; group < hoistGroupVersions.length; group++) {
if (m.start(group) < 0) continue;
if (hoistGroupVersions[group] > required) required = hoistGroupVersions[group];
break;
}
for (Token t = lexer.nextToken(); t.getType() != Token.EOF; t = lexer.nextToken()) {
final int channel = t.getChannel();
if (channel == GLSLLexer.COMMENTS || channel == Token.HIDDEN_CHANNEL) continue;
if (t.getStopIndex() - t.getStartIndex() < 3) continue;
required = matchRequirement(t.getText(), required);
if (required >= maxSupportedHoistVersion) break;
}
return required;
}
private static int getRequiredVersion(GLSLParser.Translation_unitContext tree, String headerTail, int declaredVersion) {
if (enabledRequirements == null || enabledRequirements.length == 0 || declaredVersion >= maxSupportedHoistVersion) {
return declaredVersion;
}
int required = headerTail.isEmpty() ? declaredVersion : getRequiredVersion(headerTail, declaredVersion);
if (required >= maxSupportedHoistVersion) return required;
return scanTree(tree, required);
}
private static int scanTree(ParseTree tree, int required) {
if (tree instanceof TerminalNode terminal) {
final String text = terminal.getSymbol().getText();
return (text == null || text.length() < 4) ? required : matchRequirement(text, required);
}
for (int i = 0; i < tree.getChildCount() && required < maxSupportedHoistVersion; i++) {
required = scanTree(tree.getChild(i), required);
}
return required;
}
private static int matchRequirement(String text, int required) {
for (VersionRequirement req : enabledRequirements) {
if (req.minVersion <= required) break;
if (req.prefix ? text.startsWith(req.keyword) : text.equals(req.keyword)) return req.minVersion;
}
return required;
}
private record StageHeader(int version, String extensions) {}
private static String finalizeStage(int version, String headerTail, String body, PatchShaderType stage) {
final int required = getRequiredVersion(headerTail + body, version);
private static String finalizeStage(int version, String headerTail, String body, GLSLParser.Translation_unitContext tree, PatchShaderType stage) {
final int required = getRequiredVersion(tree, headerTail, version);
if (required > version) {
final NegotiationResult negotiation = negotiateVersion(required, stage);
if (negotiation.isError()) {
@@ -206,7 +224,13 @@ public class ShaderTransformer {
}
}
record StageArtifact(GLSLParser.Translation_unitContext tree, int headerLen) {}
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, P parameters) {
return transform(vertex, geometry, tessControl, tessEval, fragment, parameters, null);
}
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, P parameters, EnumMap<PatchShaderType, StageArtifact> artifactsOut) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) {
return null;
} else {
@@ -227,13 +251,14 @@ public class ShaderTransformer {
result = shaderTransformationCache.getAndMoveToLast(key);
}
if(result == null || !useCache) {
result = transformInternal(inputs, patchType, parameters);
result = transformInternal(inputs, patchType, parameters, artifactsOut);
// Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null;
synchronized (shaderTransformationCache) {
// Double-check in case another thread added it while we were transforming
Map<PatchShaderType, String> existing = shaderTransformationCache.getAndMoveToLast(key);
if (existing != null) {
if (artifactsOut != null) artifactsOut.clear();
return existing;
}
if(shaderTransformationCache.size() >= CACHE_SIZE) {
@@ -248,6 +273,10 @@ public class ShaderTransformer {
}
public static <P extends Parameters> Map<PatchShaderType, String> transformCompute(String compute, P parameters) {
return transformCompute(compute, parameters, null);
}
public static <P extends Parameters> Map<PatchShaderType, String> transformCompute(String compute, P parameters, EnumMap<PatchShaderType, StageArtifact> artifactsOut) {
if (compute == null) {
return null;
} else {
@@ -264,13 +293,14 @@ public class ShaderTransformer {
result = shaderTransformationCache.getAndMoveToLast(key);
}
if (result == null || !useCache) {
result = transformComputeInternal(compute, patchType, parameters);
result = transformComputeInternal(compute, patchType, parameters, artifactsOut);
// Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null;
synchronized (shaderTransformationCache) {
// Double-check in case another thread added it while we were transforming
final Map<PatchShaderType, String> existing = shaderTransformationCache.getAndMoveToLast(key);
if (existing != null) {
if (artifactsOut != null) artifactsOut.clear();
return existing;
}
if (shaderTransformationCache.size() >= CACHE_SIZE) {
@@ -284,7 +314,7 @@ public class ShaderTransformer {
}
}
private static <P extends Parameters> Map<PatchShaderType, String> transformComputeInternal(String compute, Patch patchType, P parameters) {
private static <P extends Parameters> Map<PatchShaderType, String> transformComputeInternal(String compute, Patch patchType, P parameters, EnumMap<PatchShaderType, StageArtifact> artifactsOut) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
@@ -348,19 +378,28 @@ public class ShaderTransformer {
final String headerTail = extensions.isEmpty() ? "" : "\n" + extensions;
final StringBuilder formattedShaderBuilder = new StringBuilder();
final GLSLParser.Translation_unitContext[] treeHolder = new GLSLParser.Translation_unitContext[1];
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, "")));
transformer.mutateTree(tree -> {
GlslTransformUtils.restoreReservedWordsInTree(tree);
treeHolder[0] = tree;
formattedShaderBuilder.append(GlslTransformUtils.getFormattedShaderRebased(tree, ""));
});
final String formattedShader = GlslTransformUtils.restoreReservedWords(finalizeStage(versionInt, headerTail, formattedShaderBuilder.toString(), PatchShaderType.COMPUTE));
final String printedBody = formattedShaderBuilder.toString();
final String formattedShader = finalizeStage(versionInt, headerTail, printedBody, treeHolder[0], PatchShaderType.COMPUTE);
result.put(PatchShaderType.COMPUTE, formattedShader);
if (artifactsOut != null) {
artifactsOut.put(PatchShaderType.COMPUTE, new StageArtifact(treeHolder[0], formattedShader.length() - printedBody.length()));
}
watch.stop();
Iris.logger.info("[Load #{}] Transformed compute shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
return result;
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters, EnumMap<PatchShaderType, StageArtifact> artifactsOut) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, StageHeader> prepatched = new EnumMap<>(PatchShaderType.class);
@@ -446,12 +485,21 @@ public class ShaderTransformer {
}
final StringBuilder formattedShaderBuilder = new StringBuilder();
final GLSLParser.Translation_unitContext[] treeHolder = new GLSLParser.Translation_unitContext[1];
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, "")));
transformer.mutateTree(tree -> {
GlslTransformUtils.restoreReservedWordsInTree(tree);
treeHolder[0] = tree;
formattedShaderBuilder.append(GlslTransformUtils.getFormattedShaderRebased(tree, ""));
});
final String formattedShader = GlslTransformUtils.restoreReservedWords( finalizeStage(stageHeader.version(), headerTail, formattedShaderBuilder.toString(), shaderType));
final String printedBody = formattedShaderBuilder.toString();
final String formattedShader = finalizeStage(stageHeader.version(), headerTail, printedBody, treeHolder[0], shaderType);
result.put(shaderType, formattedShader);
if (artifactsOut != null && !(patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX)) {
artifactsOut.put(shaderType, new StageArtifact(treeHolder[0], formattedShader.length() - printedBody.length()));
}
}
maybeExtractRwImageStores(result, patchType);
watch.stop();
@@ -2,6 +2,7 @@ package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.EnumMap;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
@@ -92,8 +93,9 @@ public class TransformPatcher {
}
// if there is no cache result, transform the shaders
final EnumMap<PatchShaderType, ShaderTransformer.StageArtifact> artifacts = new EnumMap<>(PatchShaderType.class);
if (result == null) {
result = ShaderTransformer.transform(vertex, geometry, tessControl, tessEval, fragment, parameters);
result = ShaderTransformer.transform(vertex, geometry, tessControl, tessEval, fragment, parameters, artifacts);
if (useCache) {
synchronized (cache) {
// Double-check in case another thread added it while we were transforming
@@ -122,7 +124,12 @@ public class TransformPatcher {
for (Map.Entry<PatchShaderType, String> entry : result.entrySet()) {
final String src = entry.getValue();
if (src == null) continue;
processor.onTransformed(src, entry.getKey().glShaderType);
final ShaderTransformer.StageArtifact art = artifacts.get(entry.getKey());
if (art != null) {
processor.onTransformed(src, art.tree(), art.headerLen(), entry.getKey().glShaderType);
} else {
processor.onTransformed(src, entry.getKey().glShaderType);
}
}
}
}
@@ -183,12 +190,18 @@ public class TransformPatcher {
if (compute == null) {
return null;
}
Map<PatchShaderType, String> result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap));
final EnumMap<PatchShaderType, ShaderTransformer.StageArtifact> artifacts = new EnumMap<>(PatchShaderType.class);
Map<PatchShaderType, String> result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap), artifacts);
final String transformed = result != null ? result.get(PatchShaderType.COMPUTE) : null;
if (transformed != null && BackendManager.RENDER_BACKEND.isSDLGPU()) {
final ShaderTransformPostProcessor processor = GLSMHooks.postTransformProcessor;
if (processor != null) {
processor.onTransformed(transformed, PatchShaderType.COMPUTE.glShaderType);
final ShaderTransformer.StageArtifact art = artifacts.get(PatchShaderType.COMPUTE);
if (art != null) {
processor.onTransformed(transformed, art.tree(), art.headerLen(), PatchShaderType.COMPUTE.glShaderType);
} else {
processor.onTransformed(transformed, PatchShaderType.COMPUTE.glShaderType);
}
}
}
return transformed;
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more