repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Angelica
src\main\java\com\gtnewhorizons\angelica\client\font\FontProvider.java
package com.gtnewhorizons.angelica.client.font; import net.minecraft.util.ResourceLocation; public interface FontProvider { /** * For use with §k. Should fetch a character of the same width as provided. */ char getRandomReplacement(char chr); boolean isGlyphAvailable(char chr); float getUStart(char chr); float getVStart(char chr); float getXAdvance(char chr); float getGlyphW(char chr); float getUSize(char chr); float getVSize(char chr); float getShadowOffset(); ResourceLocation getTexture(char chr); float getYScaleMultiplier(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\font\FontProviderCustom.java
package com.gtnewhorizons.angelica.client.font; import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; import com.gtnewhorizons.angelica.config.FontConfig; import lombok.Setter; import lombok.Value; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.imageio.ImageIO; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; import java.util.Objects; public final class FontProviderCustom implements FontProvider { public static final Logger LOGGER = LogManager.getLogger("Angelica"); public static final String FONT_DIR = "fonts/custom/"; static final int ATLAS_SIZE = 128; static final int ATLAS_COUNT = 512; private final byte id; // 0 - primary font, 1 - fallback font private FontAtlas[] fontAtlases = new FontAtlas[ATLAS_COUNT]; private float currentFontQuality = FontConfig.customFontQuality; @Setter private Font font; private FontProviderCustom(byte id) { this.id = id; Font[] availableFonts = FontStrategist.getAvailableFonts(); if (availableFonts.length == 0) { LOGGER.fatal("There seem to be no fonts available on this system! Disabling custom font and throwing an exception in an attempt to restore the session."); FontConfig.enableCustomFont = false; ConfigurationManager.save(FontConfig.class); throw new RuntimeException(); } String myFontName = switch (this.id) { case 0 -> FontConfig.customFontNamePrimary; case 1 -> FontConfig.customFontNameFallback; default -> null; }; if (Objects.equals(myFontName, "(none)")) { font = null; return; } int fontPos = -1; for (int i = 0; i < availableFonts.length; i++) { if (Objects.equals(myFontName, availableFonts[i].getFontName())) { fontPos = i; break; } } if (fontPos == -1) { LOGGER.info("Could not find previously set font \"{}\". ", myFontName); font = null; return; } font = availableFonts[fontPos].deriveFont(currentFontQuality); } private static class InstLoader { static final FontProviderCustom instance0 = new FontProviderCustom((byte)0); static final FontProviderCustom instance1 = new FontProviderCustom((byte)1); } public static FontProviderCustom getPrimary() { return InstLoader.instance0; } public static FontProviderCustom getFallback() { return InstLoader.instance1; } public void reloadFont(int fontID) { currentFontQuality = FontConfig.customFontQuality; font = FontStrategist.getAvailableFonts()[fontID].deriveFont(currentFontQuality); File[] files = new File(getFontDir()).listFiles(); if (files != null) { for (File f : files) { if (!Files.isSymbolicLink(f.toPath())) { f.delete(); } } } TextureManager tm = Minecraft.getMinecraft().getTextureManager(); Map mapTextureObjects = tm.mapTextureObjects; for (int i = 0; i < ATLAS_COUNT; i++) { ResourceLocation key = new ResourceLocation(getAtlasResourceName(i)); if (mapTextureObjects.containsKey(key)) { ITextureObject obj = (ITextureObject) mapTextureObjects.get(key); TextureUtil.deleteTexture(obj.getGlTextureId()); mapTextureObjects.remove(key); } } fontAtlases = new FontAtlas[ATLAS_COUNT]; } private String getFontDir() { return FONT_DIR + "f" + this.id + "/"; } private String getAtlasFilename(int atlasId) { return "f" + this.id + "p" + atlasId; } String getAtlasResourceName(int atlasId) { return "minecraft:angelica_c" + getAtlasFilename(atlasId); } String getAtlasFullPath(int atlasId) { return getFontDir() + getAtlasFilename(atlasId) + ".png"; } @Value private class GlyphData { float uStart; float vStart; float xAdvance; float glyphW; float uSz; float vSz; } private class FontAtlas { GlyphData[] glyphData = new GlyphData[ATLAS_SIZE]; private ResourceLocation texture; private final int id; FontAtlas(int id) { this.id = id; } void construct(Font font) { float separator = currentFontQuality / 3f; BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setFont(font); FontMetrics fm = g2d.getFontMetrics(); g2d.dispose(); int width = 0; int actualChars = 0; for (int i = 0; i < ATLAS_SIZE; i++) { final char ch = (char)(i + ATLAS_SIZE * this.id); if (font.canDisplay(ch)) { width += (int) (separator + fm.charWidth(ch)); actualChars++; } } if (actualChars == 0) { return; } final int atlasTilesX = (int) Math.ceil(Math.sqrt(actualChars) * 1.5f); final int atlasTilesY = (int) Math.ceil((double) actualChars / atlasTilesX); LOGGER.info("constructing custom font atlas (ID {}) of nominal size {} chars, actual: {}, {} rows by {} columns", this.id, ATLAS_SIZE, actualChars, atlasTilesX, atlasTilesY); width = 0; actualChars = 0; int maxRowWidth = 0; for (int i = 0; i < ATLAS_SIZE; i++) { if (actualChars % atlasTilesX == 0) { maxRowWidth = Math.max(maxRowWidth, width); width = 0; } final char ch = (char)(i + ATLAS_SIZE * this.id); if (font.canDisplay(ch)) { width += (int) (separator + fm.charWidth(ch)); actualChars++; } } maxRowWidth = Math.max(maxRowWidth, width); final int lineHeight = fm.getHeight(); final float desc = fm.getDescent(); final int imageWidth = (int) (maxRowWidth + separator); final int imageHeight = (int) ((separator + lineHeight) * atlasTilesY + separator); image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setFont(font); fm = g2d.getFontMetrics(); int tileX = 0, tileY = 0; // position in atlas tiles int imgX = (int) separator; // position in pixels for (int i = 0; i < ATLAS_SIZE; i++) { final char ch = (char)(i + ATLAS_SIZE * this.id); if (!font.canDisplay(ch)) { continue; } if (tileX >= atlasTilesX) { tileX = 0; imgX = (int) separator; tileY++; } final int charWidth = fm.charWidth(ch); final float charAspectRatio = (float) charWidth / lineHeight; final float inset = currentFontQuality / 16; g2d.drawString(Character.toString(ch), imgX, (lineHeight + separator) * (tileY + 1) - desc); final float uStart = (float) (imgX - inset * charAspectRatio) / imageWidth; final float vStart = ((lineHeight + separator) * (tileY + 1) - lineHeight - inset) / imageHeight; final float xAdvance = charAspectRatio * 8 * charWidth / (charWidth + 2 * inset * charAspectRatio); final float glyphW = charAspectRatio * 8 + 1; final float uSz = (float) (charWidth + 2 * inset * charAspectRatio) / imageWidth; final float vSz = (float) (lineHeight + 2 * inset) / imageHeight; glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz); imgX += (int) (charWidth + separator); tileX++; } g2d.dispose(); try { LOGGER.info("writing custom font atlas texture ({}x{} px) to {}", imageWidth, imageHeight, getAtlasFullPath(this.id)); Files.createDirectories(Paths.get(getFontDir())); ImageIO.write(image, "png", new File(getAtlasFullPath(this.id))); } catch (IOException e) { e.printStackTrace(); } this.texture = new ResourceLocation(getAtlasResourceName(this.id)); } } private FontAtlas getAtlas(char chr) { int id = chr / ATLAS_SIZE; FontAtlas fa = fontAtlases[id]; if (fa == null) { fa = new FontAtlas(id); fa.construct(font); } fontAtlases[id] = fa; return fa; } @Override public boolean isGlyphAvailable(char chr) { if (font == null) { return false; } return (getAtlas(chr).glyphData[chr % ATLAS_SIZE] != null); } @Override public char getRandomReplacement(char chr) { return chr; } @Override public float getUStart(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].uStart; } @Override public float getVStart(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].vStart; } @Override public float getXAdvance(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance * FontConfig.customFontScale; } @Override public float getGlyphW(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW * FontConfig.customFontScale; } @Override public float getUSize(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].uSz; } @Override public float getVSize(char chr) { return getAtlas(chr).glyphData[chr % ATLAS_SIZE].vSz; } @Override public float getShadowOffset() { return FontConfig.fontShadowOffset; } @Override public ResourceLocation getTexture(char chr) { return getAtlas(chr).texture; } @Override public float getYScaleMultiplier() { return FontConfig.customFontScale; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\font\FontProviderMC.java
package com.gtnewhorizons.angelica.client.font; import com.gtnewhorizons.angelica.config.FontConfig; import it.unimi.dsi.fastutil.chars.Char2ShortOpenHashMap; import jss.util.RandomXoshiro256StarStar; import net.minecraft.util.ResourceLocation; public final class FontProviderMC implements FontProvider { /** * The full list of characters present in the default Minecraft font, excluding the Unicode font */ @SuppressWarnings("UnnecessaryUnicodeEscape") private static final String MCFONT_CHARS = "\u00c0\u00c1\u00c2\u00c8\u00ca\u00cb\u00cd\u00d3\u00d4\u00d5\u00da\u00df\u00e3\u00f5\u011f\u0130\u0131\u0152\u0153\u015e\u015f\u0174\u0175\u017e\u0207\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u03b2\u0393\u03c0\u03a3\u03c3\u03bc\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u2205\u2208\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u0000"; private FontProviderMC() {} private static class InstLoader { static final FontProviderMC instance = new FontProviderMC(); static final FontProviderMC instanceSGA = new FontProviderMC(); } public static FontProviderMC get(boolean isSGA) { return (isSGA ? InstLoader.instanceSGA : InstLoader.instance); } private static final Char2ShortOpenHashMap MCFONT_ASCII_MAP = new Char2ShortOpenHashMap(); ResourceLocation locationFontTexture = null; private final RandomXoshiro256StarStar fontRandom = new RandomXoshiro256StarStar(); public int[] charWidth; static { for (short i = 0; i < MCFONT_CHARS.length(); i++) { MCFONT_ASCII_MAP.put(MCFONT_CHARS.charAt(i), i); } } public int lookupMcFontPosition(char ch) { if (isGlyphAvailable(ch)) { return MCFONT_ASCII_MAP.get(ch); } return -1; } @Override public boolean isGlyphAvailable(char chr) { return MCFONT_ASCII_MAP.containsKey(chr); } public char getRandomReplacement(char chr){ int lutIndex = lookupMcFontPosition(chr); if (lutIndex != -1) { int randomReplacementIndex; do { randomReplacementIndex = fontRandom.nextInt(this.charWidth.length); } while (this.charWidth[lutIndex] != this.charWidth[randomReplacementIndex]); lutIndex = randomReplacementIndex; return MCFONT_CHARS.charAt(lutIndex); } return chr; } @Override public float getUStart(char chr) { int lutIndex = lookupMcFontPosition(chr); return ((lutIndex % 16) * 8) / 128.0F; } @Override public float getVStart(char chr) { int lutIndex = lookupMcFontPosition(chr); return (float) ((lutIndex / 16) * 8) / 128.0F; } @Override public float getXAdvance(char chr) { int lutIndex = lookupMcFontPosition(chr); return charWidth[lutIndex]; } @Override public float getGlyphW(char chr) { int lutIndex = lookupMcFontPosition(chr); return charWidth[lutIndex] - 0.01F; } @Override public float getUSize(char chr) { int lutIndex = lookupMcFontPosition(chr); return (charWidth[lutIndex] - 1.01F) / 128.0F; } @Override public float getVSize(char chr) { return 7.99F / 128.0F; } @Override public float getShadowOffset() { return FontConfig.fontShadowOffset; } @Override public ResourceLocation getTexture(char chr) { return locationFontTexture; } @Override public float getYScaleMultiplier() { return 1; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\font\FontProviderUnicode.java
package com.gtnewhorizons.angelica.client.font; import com.gtnewhorizons.angelica.config.FontConfig; import net.minecraft.util.ResourceLocation; public final class FontProviderUnicode implements FontProvider { private FontProviderUnicode() {} private static class InstLoader { static final FontProviderUnicode instance = new FontProviderUnicode(); } public static FontProviderUnicode get() { return FontProviderUnicode.InstLoader.instance; } private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256]; public byte[] glyphWidth; private ResourceLocation getUnicodePageLocation(int page) { final ResourceLocation lookup = unicodePageLocations[page]; if (lookup == null) { final ResourceLocation rl = new ResourceLocation(String.format( "textures/font/unicode_page_%02x.png", page)); unicodePageLocations[page] = rl; return rl; } else { return lookup; } } @Override public boolean isGlyphAvailable(char chr) { return true; } @Override public char getRandomReplacement(char chr) { return chr; } @Override public float getUStart(char chr) { final float startColumnF = (float)((this.glyphWidth[chr] >>> 4) & 15); return ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f; } @Override public float getVStart(char chr) { return ((float) ((chr & 255) / 16 * 16) + 0.21f) / 256.0f; } @Override public float getXAdvance(char chr) { final int startColumn = (this.glyphWidth[chr] >>> 4) & 15; final int endColumn = this.glyphWidth[chr] & 15; final float startColumnF = (float) startColumn; final float endColumnF = (float) (endColumn + 1); return (endColumnF - startColumnF) / 2.0F + 1.0F; } @Override public float getGlyphW(char chr) { final int startColumn = (this.glyphWidth[chr] >>> 4) & 15; final int endColumn = this.glyphWidth[chr] & 15; final float startColumnF = (float) startColumn; final float endColumnF = (float) (endColumn + 1); final float chrWidth = endColumnF - startColumnF - 0.02F; return chrWidth / 2.0f + 1.0f; } @Override public float getUSize(char chr) { final int startColumn = (this.glyphWidth[chr] >>> 4) & 15; final int endColumn = this.glyphWidth[chr] & 15; final float startColumnF = (float) startColumn; final float endColumnF = (float) (endColumn + 1); final float chrWidth = endColumnF - startColumnF - 0.02F; return (chrWidth - 0.42f) / 256.0f; } @Override public float getVSize(char chr) { return (16.0f - 0.42f) / 256.0f; } @Override public float getShadowOffset() { return FontConfig.fontShadowOffset; } @Override public ResourceLocation getTexture(char chr) { final int uniPage = chr / 256; return getUnicodePageLocation(uniPage); } @Override public float getYScaleMultiplier() { return 1; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\font\FontStrategist.java
package com.gtnewhorizons.angelica.client.font; import com.google.common.collect.HashMultiset; import com.gtnewhorizons.angelica.config.FontConfig; import com.gtnewhorizons.angelica.mixins.interfaces.ResourceAccessor; import cpw.mods.fml.client.SplashProgress; import lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.resources.DefaultResourcePack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.io.File; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Objects; public class FontStrategist { @Getter private static final Font[] availableFonts; public static final Logger LOGGER = LogManager.getLogger("Angelica"); static { // get available fonts without duplicates (250 copies of dialog.plain need not apply) Font[] availableFontsDirty = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); HashMap<String, Font> fontSet = new HashMap<>(); HashMultiset<String> duplicates = HashMultiset.create(); // for debugging for (Font font : availableFontsDirty) { String fontName = font.getFontName(); if (fontSet.containsKey(fontName)) { duplicates.add(fontName); } else { fontSet.put(fontName, font); } } if (!duplicates.isEmpty()) { StringBuilder sb = new StringBuilder(duplicates.size() + " duplicate font(s) found in the list reported by Java: "); for (Iterator<String> iter = duplicates.stream().distinct().iterator(); iter.hasNext(); ) { String dupe = iter.next(); sb.append(duplicates.count(dupe)).append("x ").append(dupe); if (iter.hasNext()) { sb.append(", "); } } sb.append(". Some fonts may be missing from the font selection menu."); LOGGER.warn(sb.toString()); } availableFonts = fontSet.values().stream().sorted(Comparator.comparing(Font::getFontName)).toArray(Font[]::new); // create and add the resource pack that provides fonts HashMap<String, File> packMap = new HashMap<>(); for (int i = 0; i < FontProviderCustom.ATLAS_COUNT; i++) { packMap.put(FontProviderCustom.getPrimary().getAtlasResourceName(i), new File(FontProviderCustom.getPrimary().getAtlasFullPath(i))); packMap.put(FontProviderCustom.getFallback().getAtlasResourceName(i), new File(FontProviderCustom.getFallback().getAtlasFullPath(i))); } DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap); List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks(); defaultResourcePacks.add(fontResourcePack); Minecraft.getMinecraft().refreshResources(); } /** Lets you get a FontProvider per char while respecting font priority and fallbacks, the unicode flag, whether or not SGA is on, if we're in a splash screen, if a font can even display a character in the first place, etc. */ public static FontProvider getFontProvider(BatchingFontRenderer me, char chr, boolean customFontEnabled, boolean forceUnicode) { if (me.isSGA && FontProviderMC.get(true).isGlyphAvailable(chr)) { return FontProviderMC.get(true); } if (customFontEnabled && !me.isSplash) { FontProvider fp; fp = FontProviderCustom.getPrimary(); if (fp.isGlyphAvailable(chr)) { return fp; } fp = FontProviderCustom.getFallback(); if (fp.isGlyphAvailable(chr)) { return fp; } return FontProviderUnicode.get(); } else { if (!forceUnicode && FontProviderMC.get(false).isGlyphAvailable(chr)) { return FontProviderMC.get(false); } else { return FontProviderUnicode.get(); } } } public static void reloadCustomFontProviders() { FontProviderCustom.getPrimary().setFont(null); FontProviderCustom.getFallback().setFont(null); for (int i = 0; i < availableFonts.length; i++) { if (Objects.equals(FontConfig.customFontNamePrimary, availableFonts[i].getFontName())) { FontProviderCustom.getPrimary().reloadFont(i); } if (Objects.equals(FontConfig.customFontNameFallback, availableFonts[i].getFontName())) { FontProviderCustom.getFallback().reloadFont(i); } } } public static boolean isSplashFontRendererActive(FontRenderer fontRenderer) { // noinspection deprecation boolean active = fontRenderer instanceof SplashProgress.SplashFontRenderer; try { Class<?> customSplashClass = Class.forName("gkappa.modernsplash.CustomSplash$SplashFontRenderer"); active = active || customSplashClass.isInstance(fontRenderer); } catch (ClassNotFoundException ignored) { } return active; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\gui\FontConfigScreen.java
package com.gtnewhorizons.angelica.client.gui; import com.gtnewhorizon.gtnhlib.config.ConfigException; import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; import com.gtnewhorizons.angelica.client.font.FontStrategist; import com.gtnewhorizons.angelica.config.FontConfig; import net.coderbot.iris.gui.element.widget.IrisButton; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSlot; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.resources.I18n; import net.minecraft.util.MathHelper; import org.lwjgl.input.Keyboard; import java.awt.Font; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class FontConfigScreen extends GuiScreen { private static final Font[] availableFonts = FontStrategist.getAvailableFonts(); private final GuiScreen parent; private final String title; private final String searchPrompt; private final String testAreaPrompt; private List<String> testAreaInfo; private String currentPrimaryFontName; private String currentFallbackFontName; private FontList fontList; private int selectedPrimaryFontListPos = -1; private int selectedFallbackFontListPos = -1; private ArrayList<Font> displayedFonts; private GuiTextField searchBox; private GuiTextField testArea; private int sliderPages = 0; private int displayedSliderPage = 0; private final int sliderWidth = 160; private final int sliderHeight = 20; // need to save these separately private IrisButton fwdButton; private IrisButton backButton; SliderClone.Option optFontQuality = new SliderClone.Option(6, 72, 6); SliderClone.Option optShadowOffset = new SliderClone.Option(0, 2, 0.05f); SliderClone.Option optShadowCopies = new SliderClone.Option(1, 8, 1); SliderClone.Option optBoldCopies = new SliderClone.Option(1, 8, 1); SliderClone.Option optGlyphAspect = new SliderClone.Option(-1, 1, 0.05f); SliderClone.Option optGlyphScale = new SliderClone.Option(0.1f, 3, 0.05f); SliderClone.Option optWhitespaceScale = new SliderClone.Option(0.1f, 3, 0.05f); SliderClone.Option optGlyphSpacing = new SliderClone.Option(-2f, 2f, 0.05f); SliderClone.Option optFontAAMode = new SliderClone.Option(0, 2, 1); SliderClone.Option optFontAAStrength = new SliderClone.Option(1, 24, 1); SliderClone.Option optCustomFontScale = new SliderClone.Option(0.1f, 3, 0.05f); public FontConfigScreen(GuiScreen parent) { this.title = I18n.format("options.angelica.fontconfig.title"); this.searchPrompt = I18n.format("options.angelica.fontconfig.searchprompt"); this.testAreaPrompt = I18n.format("options.angelica.fontconfig.testareaprompt"); this.parent = parent; this.currentPrimaryFontName = FontConfig.customFontNamePrimary; this.currentFallbackFontName = FontConfig.customFontNameFallback; this.displayedFonts = new ArrayList<>(Arrays.asList(availableFonts)); for (int i = 0; i < availableFonts.length; i++) { if (Objects.equals(this.currentPrimaryFontName, availableFonts[i].getFontName())) { selectedPrimaryFontListPos = i; } if (Objects.equals(this.currentFallbackFontName, availableFonts[i].getFontName())) { selectedFallbackFontListPos = i; } } } public void initGui() { Keyboard.enableRepeatEvents(true); searchBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 120, 24, 240, 20); searchBox.setMaxStringLength(64); fontList = new FontList(); testArea = new GuiTextField(this.fontRendererObj, this.width * 5 / 6 - this.width / 7, 63 - 10, this.width * 2 / 7, 20); testArea.setMaxStringLength(512); testArea.setText(I18n.format("options.angelica.fontconfig.testareaexample")); initButtons(); } private void initButtons() { final int halfWidth = this.width / 2; final int sliderSpacing = 4; final int x1 = halfWidth - sliderWidth - sliderSpacing; final int x2 = halfWidth; final int x3 = halfWidth + sliderWidth + sliderSpacing; final int y3 = this.height - 65 + 2 * (sliderHeight + sliderSpacing); this.buttonList.add(new IrisButton(x1 - sliderWidth / 2, y3 - sliderHeight / 2, sliderWidth, sliderHeight, FontConfig.enableCustomFont ? I18n.format("options.angelica.fontconfig.disable_custom_font") : I18n.format("options.angelica.fontconfig.enable_custom_font"), this::toggleCustomFont)); this.buttonList.add(new IrisButton(x2 - sliderWidth / 2, y3 - sliderHeight / 2, sliderWidth, sliderHeight, I18n.format("options.angelica.fontconfig.reset_values"), this::resetValues)); this.buttonList.add(new IrisButton(x3 - sliderWidth / 2, y3 - sliderHeight / 2, sliderWidth, sliderHeight, I18n.format("gui.done"), button -> this.onClose())); backButton = new IrisButton(halfWidth - 20 - 224, this.height - 89 - 10, 40, 20, "<", button -> this.switchPage(-1)); fwdButton = new IrisButton(halfWidth - 20 + 224, this.height - 89 - 10, 40, 20, ">", button -> this.switchPage(1)); this.buttonList.add(fwdButton); this.buttonList.add(backButton); initSliders(); } private void initSliders() { ArrayList<SliderClone> sliders = new ArrayList<>(); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optFontQuality) .initialValue(FontConfig.customFontQuality) .setter(this::setFontQuality) .langKey("options.angelica.fontconfig.font_quality") .formatString("%2.0f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optShadowOffset) .initialValue(FontConfig.fontShadowOffset) .setter(value -> FontConfig.fontShadowOffset = value) .langKey("options.angelica.fontconfig.shadow_offset") .formatString("x%3.2f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optGlyphAspect) .initialValue(FontConfig.glyphAspect) .setter(value -> FontConfig.glyphAspect = value) .langKey("options.angelica.fontconfig.glyph_aspect") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optGlyphScale) .initialValue(FontConfig.glyphScale) .setter(value -> FontConfig.glyphScale = value) .langKey("options.angelica.fontconfig.glyph_scale") .formatString("x%3.2f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optFontAAStrength) .initialValue(FontConfig.fontAAStrength) .setter(value -> FontConfig.fontAAStrength = value.intValue()) .langKey("options.angelica.fontconfig.font_aa_strength") .formatString("%.0f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optFontAAMode) .initialValue(FontConfig.fontAAMode) .setter(value -> FontConfig.fontAAMode = value.intValue()) .formatter(this::fontAAModeFormat) .langKey("options.angelica.fontconfig.aamode") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optWhitespaceScale) .initialValue(FontConfig.whitespaceScale) .setter(value -> FontConfig.whitespaceScale = value) .langKey("options.angelica.fontconfig.whitespace_scale") .formatString("x%3.2f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optGlyphSpacing) .initialValue(FontConfig.glyphSpacing) .setter(value -> FontConfig.glyphSpacing = value) .langKey("options.angelica.fontconfig.glyph_spacing") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optShadowCopies) .initialValue(FontConfig.shadowCopies) .setter(value -> FontConfig.shadowCopies = value.intValue()) .langKey("options.angelica.fontconfig.shadow_copies") .formatString("%.0f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optBoldCopies) .initialValue(FontConfig.boldCopies) .setter(value -> FontConfig.boldCopies = value.intValue()) .langKey("options.angelica.fontconfig.bold_copies") .formatString("%.0f") .build() ); sliders.add(new SliderClone.SliderCloneBuilder() .width(sliderWidth) .height(sliderHeight) .option(optCustomFontScale) .initialValue(FontConfig.customFontScale) .setter(value -> FontConfig.customFontScale = value) .langKey("options.angelica.fontconfig.custom_font_scale") .formatString("x%3.2f") .build() ); final int halfWidth = this.width / 2; final int sliderSpacing = 4; final int x1 = halfWidth - sliderWidth - sliderSpacing; final int x2 = halfWidth; final int x3 = halfWidth + sliderWidth + sliderSpacing; final int y1 = this.height - 65; final int y2 = this.height - 65 + sliderHeight + sliderSpacing; this.sliderPages = sliders.size() / 6; this.displayedSliderPage = Math.min(this.displayedSliderPage, this.sliderPages); this.backButton.enabled = (this.displayedSliderPage != 0); this.fwdButton.enabled = (this.displayedSliderPage != this.sliderPages); final int start = 6 * this.displayedSliderPage; final int end = Math.min(6 * (this.displayedSliderPage + 1), sliders.size()); List<SliderClone> s = sliders.subList(start, end); try { s.get(0).setCenterPosition(x1, y1); s.get(1).setCenterPosition(x1, y2); s.get(2).setCenterPosition(x2, y1); s.get(3).setCenterPosition(x2, y2); s.get(4).setCenterPosition(x3, y1); s.get(5).setCenterPosition(x3, y2); } catch (IndexOutOfBoundsException ignored) { // we're on the last page and it has less than 6 sliders to display } this.buttonList.addAll(s); } private void onClose() { applyChanges(true); this.mc.displayGuiScreen(parent); } private void applyChanges(boolean finalApply) { int pos; pos = selectedPrimaryFontListPos; if (pos >= 0 && pos < displayedFonts.size()) { FontConfig.customFontNamePrimary = displayedFonts.get(pos).getFontName(); } pos = selectedFallbackFontListPos; if (pos >= 0 && pos < displayedFonts.size()) { FontConfig.customFontNameFallback = displayedFonts.get(pos).getFontName(); } FontStrategist.reloadCustomFontProviders(); if (finalApply) { ConfigurationManager.save(FontConfig.class); } } private void resetValues(IrisButton button) { try { ConfigurationManager.getConfigElements(FontConfig.class).forEach(elem -> elem.set(elem.getDefault())); } catch (ConfigException e) { throw new RuntimeException(e); } currentPrimaryFontName = null; currentFallbackFontName = null; selectedPrimaryFontListPos = -1; selectedFallbackFontListPos = -1; super.buttonList.clear(); this.initButtons(); } private void toggleCustomFont(IrisButton button) { FontConfig.enableCustomFont = !FontConfig.enableCustomFont; applyChanges(false); button.displayString = FontConfig.enableCustomFont ? I18n.format("options.angelica.fontconfig.disable_custom_font") : I18n.format("options.angelica.fontconfig.enable_custom_font"); } private void switchPage(int offset) { this.displayedSliderPage = MathHelper.clamp_int(this.displayedSliderPage + offset, 0, this.sliderPages); this.buttonList.removeIf(guiButton -> guiButton instanceof SliderClone); this.initSliders(); } private int qualityLast = FontConfig.customFontQuality; private void setFontQuality(float quality) { FontConfig.customFontQuality = (int) quality; if (qualityLast != (int) quality) { applyChanges(false); } qualityLast = (int) quality; } private String fontAAModeFormat(float AAmode) { return switch ((int) AAmode) { case 2 -> I18n.format("options.angelica.fontconfig.aamode.aa_16x"); case 1 -> I18n.format("options.angelica.fontconfig.aamode.aa_4x"); default -> I18n.format("options.angelica.fontconfig.aamode.aa_none"); }; } private float lastMouseX = 0; private float lastMouseY = 0; private long lastStillTime = 0; @Override public void drawScreen(int mouseX, int mouseY, float delta) { drawBackground(0); fontList.drawScreen(mouseX, mouseY, delta); searchBox.drawTextBox(); // I bet you thought this was drawn inside the search box, not on top of it. if (!this.searchBox.isFocused() && this.searchBox.getText().isEmpty()) { this.drawCenteredString(this.fontRendererObj, this.searchPrompt, this.searchBox.xPosition + this.fontRendererObj.getStringWidth(this.searchPrompt) / 2 + 4, this.searchBox.yPosition + this.searchBox.height / 2 - 4, 0xFFFFFF); } drawCenteredString(this.fontRendererObj, this.title, (int) (this.width * 0.5), 8, 0xFFFFFF); drawCenteredString(this.fontRendererObj, I18n.format("options.angelica.fontconfig.currentfonts", FontConfig.customFontNamePrimary, FontConfig.customFontNameFallback), (int) (this.width * 0.5), this.height - 92, 0xFFFFFF); if (this.testAreaInfo == null) { this.testAreaInfo = this.fontRendererObj.listFormattedStringToWidth( I18n.format("options.angelica.fontconfig.testareainfo"), this.width / 4 ); } int cumulativeY = 73; for (String s : this.testAreaInfo) { drawCenteredString(this.fontRendererObj, s, this.width * 5 / 6, cumulativeY, 0xFFFFFF); cumulativeY += this.fontRendererObj.FONT_HEIGHT; } cumulativeY += 4; this.testArea.yPosition = cumulativeY; this.testArea.drawTextBox(); if (!this.testArea.isFocused() && this.testArea.getText().isEmpty()) { this.drawCenteredString(this.fontRendererObj, this.testAreaPrompt, this.testArea.xPosition + this.fontRendererObj.getStringWidth(this.testAreaPrompt) / 2 + 4, this.testArea.yPosition + this.testArea.height / 2 - 4, 0xFFFFFF); } List<String> testText = this.fontRendererObj.listFormattedStringToWidth( this.testArea.getText().replace('&', '§'), this.width / 4 ); cumulativeY += this.testArea.height + 4; for (String s : testText) { drawCenteredString(this.fontRendererObj, s, this.width * 5 / 6, cumulativeY, 0xFFFFFF); cumulativeY += this.fontRendererObj.FONT_HEIGHT; } super.drawScreen(mouseX, mouseY, delta); for (GuiButton guiButton : buttonList) { if (!(guiButton instanceof SliderClone slider)) { continue; } final int top = slider.yPosition; final int bot = slider.yPosition + slider.height; final int left = slider.xPosition; final int right = slider.xPosition + slider.width; if (mouseY < top || mouseY >= bot || mouseX < left || mouseX >= right) { continue; } if (mouseX == lastMouseX && mouseY == lastMouseY) { if (lastStillTime == 0) { lastStillTime = System.currentTimeMillis(); } if (lastStillTime + 500L < System.currentTimeMillis()) { displayTooltip(mouseX, mouseY, slider.tooltipKey); } } else { lastStillTime = 0; } break; } lastMouseX = mouseX; lastMouseY = mouseY; } private void displayTooltip(int x, int y, String langKey) { List<String> lines = this.fontRendererObj.listFormattedStringToWidth(I18n.format(langKey), this.width / 2); this.drawHoveringText(lines, x, y, this.fontRendererObj); } @Override protected void actionPerformed(GuiButton guiButton) { if (guiButton.enabled) { if (guiButton instanceof IrisButton irisButton) { irisButton.onPress(); } } } @Override protected void keyTyped(char typedChar, int keyCode) { if (this.searchBox.isFocused()) { if (keyCode == Keyboard.KEY_ESCAPE) { this.searchBox.setFocused(false); return; } this.searchBox.textboxKeyTyped(typedChar, keyCode); this.displayedFonts = filterFonts(this.searchBox.getText().toLowerCase()); } if (this.testArea.isFocused()) { if (keyCode == Keyboard.KEY_ESCAPE) { this.testArea.setFocused(false); return; } this.testArea.textboxKeyTyped(typedChar, keyCode); } if (keyCode == Keyboard.KEY_ESCAPE) { this.onClose(); } } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { super.mouseClicked(mouseX, mouseY, mouseButton); this.searchBox.mouseClicked(mouseX, mouseY, mouseButton); this.testArea.mouseClicked(mouseX, mouseY, mouseButton); this.fontList.mouseClicked(mouseX, mouseY, mouseButton); } @Override public void updateScreen() { this.searchBox.updateCursorCounter(); this.testArea.updateCursorCounter(); } // this could be more efficient, but it's good enough as is private ArrayList<Font> filterFonts(String search) { ArrayList<Font> results; if (search == null || search.isEmpty()) { results = new ArrayList<>(Arrays.asList(availableFonts)); } else { results = Arrays.stream(availableFonts).filter((font -> font.getFontName().toLowerCase().contains(search))).collect(Collectors.toCollection(ArrayList::new)); } selectedPrimaryFontListPos = -1; selectedFallbackFontListPos = -1; for (int i = 0; i < results.size(); i++) { if (Objects.equals(currentPrimaryFontName, results.get(i).getFontName())) { selectedPrimaryFontListPos = i; } if (Objects.equals(currentFallbackFontName, results.get(i).getFontName())) { selectedFallbackFontListPos = i; } } return results; } class FontList extends GuiSlot { public FontList() { super(FontConfigScreen.this.mc, FontConfigScreen.this.width * 2 / 3, FontConfigScreen.this.height, 52, FontConfigScreen.this.height - 102, 18); } private void mouseClicked(int mouseX, int mouseY, int mouseButton) { if (mouseY < this.top || mouseY > this.bottom) { return; } int listLeftBound = this.width / 2 - this.getListWidth() / 2; int listRightBound = this.width / 2 + this.getListWidth() / 2; if (mouseX < listLeftBound || mouseX > listRightBound) { return; } int mousePosInList = mouseY - this.top - this.headerPadding + (int)this.amountScrolled - 4; int slotIndex = mousePosInList / this.slotHeight; if (slotIndex < 0 || slotIndex >= this.getSize()) { return; } if (mouseButton == 0) { onElemClicked(slotIndex, false); } else if (mouseButton == 1) { onElemClicked(slotIndex, true); } } protected void onElemClicked(int index, boolean rightClick) { if (!rightClick) { selectedPrimaryFontListPos = index; currentPrimaryFontName = displayedFonts.get(index).getFontName(); } else { selectedFallbackFontListPos = index; currentFallbackFontName = displayedFonts.get(index).getFontName(); } applyChanges(false); } protected boolean isSelected(int index) { return (index == selectedPrimaryFontListPos || index == selectedFallbackFontListPos); } protected int getSize() { return displayedFonts.size(); } @Override protected int getContentHeight() { return this.getSize() * 18; } @Override protected int getScrollBarX() { return this.width * 15 / 16 - 5; } @Override public int getListWidth() { return this.width * 2 / 3; } // see onElemClicked for the proper version that supports right-clicking protected void elementClicked(int index, boolean doubleClicked, int mouseX, int mouseY) {} protected void drawBackground() { // do nothing, the font list doesn't occupy the entire screen } protected void drawSlot(int index, int x, int y, int p_148126_4_, Tessellator tessellator, int p_148126_6_, int p_148126_7_) { int color = 0xffffff; if (index == selectedPrimaryFontListPos) { color &= 0xffff55; } if (index == selectedFallbackFontListPos) { color &= 0x55ffff; } drawCenteredString(fontRendererObj, displayedFonts.get(index).getFontName(), this.width / 2, y + 1, color); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\gui\ScrollableGuiScreen.java
package com.gtnewhorizons.angelica.client.gui; import com.gtnewhorizons.angelica.compat.mojang.Element; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.util.List; public abstract class ScrollableGuiScreen extends GuiScreen { @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); handleMouseScroll(mouseX, mouseY, partialTicks); } public abstract List<? extends Element> children(); protected void handleMouseScroll(int mouseX, int mouseY, float partialTicks) { for (; !this.mc.gameSettings.touchscreen && Mouse.next(); this.mc.currentScreen.handleMouseInput()) { int dWheel = Mouse.getEventDWheel(); if (dWheel != 0) { for(Element child : children()) { child.mouseScrolled(mouseX, mouseY, dWheel); } } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\client\gui\SliderClone.java
package com.gtnewhorizons.angelica.client.gui; import lombok.AllArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import org.lwjgl.opengl.GL11; import java.util.function.Consumer; import java.util.function.Function; public class SliderClone extends GuiButton { private final Function<Float, String> displayStringFormatter; private final Consumer<Float> valueSetter; private final Option option; private float sliderPercentage; public final String tooltipKey; public boolean mouseDragging; @AllArgsConstructor public static class Option { float min; float max; float step; float denormalize(float alpha) { float lerp = min * (1 - alpha) + max * alpha; return Math.round(lerp / step) * step; } float normalize(float value) { return (value - min) / (max - min); } } public SliderClone(int x, int y, int width, int height, Option option, float initialValue, Consumer<Float> setter, Function<Float, String> formatter, String tooltipKey) { super(0, x, y, width, height, ""); this.option = option; this.sliderPercentage = option.normalize(initialValue); this.displayString = formatter.apply(initialValue); this.valueSetter = setter; this.displayStringFormatter = formatter; this.tooltipKey = tooltipKey; } public static SliderCloneBuilder builder() { return new SliderCloneBuilder(); } public void setCenterPosition(int x, int y) { this.xPosition = x - this.width / 2; this.yPosition = y - this.height / 2; } @Accessors(fluent = true) @Setter public static class SliderCloneBuilder { private int x = 0, y = 0; // center position, not a corner private int width = 144, height = 20; private Option option; private float initialValue; private Consumer<Float> setter; private String formatString = "%3.2f"; private String langKey; // overrides: if null, these get set to default values private String tooltipKey; private Function<Float, String> formatter; public SliderClone build() { if (this.formatter == null) { this.formatter = value -> I18n.format(this.langKey, String.format(this.formatString, value)); } if (this.tooltipKey == null) { this.tooltipKey = this.langKey + ".tooltip"; } return new SliderClone( this.x - this.width / 2, this.y - this.height / 2, this.width, this.height, this.option, this.initialValue, this.setter, this.formatter, this.tooltipKey ); } } /** * Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over this button and 2 if it IS hovering over * this button. */ public int getHoverState(boolean mouseOver) { return 0; } /** * Fired when the mouse button is dragged. Equivalent of MouseListener.mouseDragged(MouseEvent e). */ protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { if (this.mouseDragging) { this.sliderPercentage = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); if (this.sliderPercentage < 0.0F) { this.sliderPercentage = 0.0F; } if (this.sliderPercentage > 1.0F) { this.sliderPercentage = 1.0F; } float f = this.option.denormalize(this.sliderPercentage); valueSetter.accept(f); this.sliderPercentage = this.option.normalize(f); this.displayString = displayStringFormatter.apply(f); } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); } } /** * Returns true if the mouse has been pressed on this control. Equivalent of MouseListener.mousePressed(MouseEvent e). */ public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { if (super.mousePressed(mc, mouseX, mouseY)) { this.sliderPercentage = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); if (this.sliderPercentage < 0.0F) { this.sliderPercentage = 0.0F; } if (this.sliderPercentage > 1.0F) { this.sliderPercentage = 1.0F; } float f = this.option.denormalize(this.sliderPercentage); valueSetter.accept(f); this.sliderPercentage = this.option.normalize(f); this.displayString = displayStringFormatter.apply(f); this.mouseDragging = true; return true; } else { return false; } } /** * Fired when the mouse button is released. Equivalent of MouseListener.mouseReleased(MouseEvent e). */ public void mouseReleased(int mouseX, int mouseY) { this.mouseDragging = false; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\backhand\BackhandReflectionCompat.java
package com.gtnewhorizons.angelica.compat.backhand; import com.gtnewhorizons.angelica.helpers.LoadControllerHelper; import cpw.mods.fml.common.versioning.DefaultArtifactVersion; import cpw.mods.fml.relauncher.ReflectionHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import static com.gtnewhorizons.angelica.compat.ModStatus.LOGGER; public class BackhandReflectionCompat { private static final String BACKHAND_CLASS = "xonin.backhand.Backhand"; private static final String ITEM_RENDERER_HOOKS_CLASS = "xonin.backhand.client.hooks.ItemRendererHooks"; private static final String BACKHAND_UTILS_CLASS = "xonin.backhand.api.core.BackhandUtils"; private static boolean isLoaded; private static final MethodHandle renderOffhandReturn; private static final MethodHandle getOffhandItem; static { MethodHandle renderOffhandReturnTemp = null; MethodHandle getOffhandItemTemp = null; try { final Class<?> backhandClass = ReflectionHelper.getClass(BackhandReflectionCompat.class.getClassLoader(), BACKHAND_CLASS); final boolean versionCheck = new DefaultArtifactVersion("1.6.9").compareTo(LoadControllerHelper.getOwningMod(backhandClass).getProcessedVersion()) <= 0; if (versionCheck) { final MethodHandles.Lookup lookup = MethodHandles.lookup(); final Class<?> itemRendererHooksClass = ReflectionHelper.getClass(BackhandReflectionCompat.class.getClassLoader(), ITEM_RENDERER_HOOKS_CLASS); final Class<?> backhandUtilsClass = ReflectionHelper.getClass(BackhandReflectionCompat.class.getClassLoader(), BACKHAND_UTILS_CLASS); renderOffhandReturnTemp = lookup.findStatic(itemRendererHooksClass, "renderOffhandReturn", MethodType.methodType(void.class, float.class)); getOffhandItemTemp = lookup.findStatic(backhandUtilsClass, "getOffhandItem", MethodType.methodType(ItemStack.class, EntityPlayer.class)); isLoaded = true; LOGGER.info("Backhand compat loaded"); } } catch (Exception e) { LOGGER.error("Failed to load Backhand compat", e); isLoaded = false; } renderOffhandReturn = renderOffhandReturnTemp; getOffhandItem = getOffhandItemTemp; } public static boolean isBackhandLoaded() { return isLoaded; } public static void renderOffhand(float partialTicks) { if (isLoaded && renderOffhandReturn != null) { try { renderOffhandReturn.invokeExact(partialTicks); } catch (Error e) { throw e; } catch (Throwable t) { LOGGER.error("Failed to invoke HoloInventory renderEvent", t); isLoaded = false; } } } public static ItemStack getOffhandItem(EntityPlayer player) { if (isLoaded && getOffhandItem != null) { try { return (ItemStack) getOffhandItem.invokeExact(player); } catch (Error e) { throw e; } catch (Throwable t) { LOGGER.error("Failed to invoke HoloInventory renderEvent", t); isLoaded = false; } } return null; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\battlegear2\Battlegear2Compat.java
package com.gtnewhorizons.angelica.compat.battlegear2; import mods.battlegear2.api.core.IInventoryPlayerBattle; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; /** * This class exists to isolate classes that exist in Battlegear 2 but not * in Battlegear 2 for Backhand in order to avoid class loading exceptions. */ public class Battlegear2Compat { public static ItemStack getBattlegear2Offhand(EntityPlayer player) { return ((IInventoryPlayerBattle) player.inventory).battlegear2$getCurrentOffhandWeapon(); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\bettercrashes\BetterCrashesCompat.java
package com.gtnewhorizons.angelica.compat.bettercrashes; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.IRenderGlobalExt; import cpw.mods.fml.common.Optional; import net.minecraft.client.Minecraft; import vfyjxf.bettercrashes.utils.StateManager; import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; @Optional.Interface(modid = "angelica", iface = "vfyjxf.bettercrashes.utils.StateManager.IResettable") public class BetterCrashesCompat implements StateManager.IResettable { private static BetterCrashesCompat INSTANCE; public static void init() { if (INSTANCE == null) { INSTANCE = new BetterCrashesCompat(); } } public BetterCrashesCompat() { LOGGER.info("BetterCrashesCompat initialized"); this.register(); } @Override public void resetState() { LOGGER.info("Reloading SodiumRenderer"); ((IRenderGlobalExt) Minecraft.getMinecraft().renderGlobal).reload(); LOGGER.info("Resetting GLStateManager"); GLStateManager.reset(); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\endlessids\EndlessIDsCompat.java
package com.gtnewhorizons.angelica.compat.endlessids; import com.falsepattern.endlessids.mixin.helpers.ChunkBiomeHook; import lombok.val; import net.minecraft.world.chunk.Chunk; import static com.falsepattern.endlessids.constants.ExtendedConstants.biomeIDMask; import static com.falsepattern.endlessids.constants.ExtendedConstants.biomeIDNull; public class EndlessIDsCompat { public static void sodium$populateBiomes(Chunk chunk) { if (!(chunk instanceof ChunkBiomeHook hook)) return; val biomes = hook.getBiomeShortArray(); if (biomes == null) return; val cX = chunk.xPosition << 4; val cZ = chunk.zPosition << 4; val manager = chunk.worldObj.getWorldChunkManager(); for(var z = 0; z < 16; z++) { for(var x = 0; x < 16; x++) { val idx = (z << 4) + x; val biome = biomes[idx] & biomeIDMask; if(biome == biomeIDNull) { val generated = manager.getBiomeGenAt(cX + x, cZ + z); if (generated == null) continue; biomes[idx] = (short)(generated.biomeID & biomeIDMask); } } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\holoinventory\HoloInventoryReflectionCompat.java
package com.gtnewhorizons.angelica.compat.holoinventory; import net.minecraftforge.client.event.RenderGameOverlayEvent; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Field; import static com.gtnewhorizons.angelica.compat.ModStatus.LOGGER; public class HoloInventoryReflectionCompat { private static final String RENDERER_CLASS = "net.dries007.holoInventory.client.Renderer"; private static boolean isLoaded; private static final MethodHandle renderEventPostMethod; private static final MethodHandle renderEventMethod; private static final MethodHandle angelicaOverrideSetter; static { MethodHandle renderEventPostMethodTemp = null; MethodHandle renderEventMethodTemp = null; MethodHandle angelicaOverrideSetterTemp = null; final Object rendererInstance; final Class<?> rendererClass; try { rendererClass = Class.forName(RENDERER_CLASS); // Get and cache the Renderer.INSTANCE final Field instanceField = rendererClass.getDeclaredField("INSTANCE"); instanceField.setAccessible(true); rendererInstance = instanceField.get(null); final MethodHandles.Lookup lookup = MethodHandles.lookup(); try { renderEventPostMethodTemp = lookup.findVirtual(rendererClass, "renderEvent", MethodType.methodType(void.class, RenderGameOverlayEvent.Post.class)); } catch (NoSuchMethodException e) { // Fallback for 2.5.0-GTNH and earlier renderEventMethodTemp = lookup.findVirtual(rendererClass, "renderEvent", MethodType.methodType(void.class, RenderGameOverlayEvent.class)); } final Field angelicaOverrideField = rendererClass.getDeclaredField("angelicaOverride"); angelicaOverrideField.setAccessible(true); angelicaOverrideSetterTemp = lookup.unreflectSetter(angelicaOverrideField); // Bind the method handles to the instance if (rendererInstance != null) { if (renderEventPostMethodTemp != null) { renderEventPostMethodTemp = renderEventPostMethodTemp.bindTo(rendererInstance); } if (renderEventMethodTemp != null) { renderEventMethodTemp = renderEventMethodTemp.bindTo(rendererInstance); } angelicaOverrideSetterTemp = angelicaOverrideSetterTemp.bindTo(rendererInstance); } isLoaded = true; LOGGER.info("Successfully initialized HoloInventory compatibility layer"); } catch (Exception e) { LOGGER.warn("Failed to initialize HoloInventory compatibility layer", e); isLoaded = false; } renderEventPostMethod = renderEventPostMethodTemp; renderEventMethod = renderEventMethodTemp; angelicaOverrideSetter = angelicaOverrideSetterTemp; } public static void renderEvent(RenderGameOverlayEvent event) { if (!isLoaded) return; try { if (event instanceof RenderGameOverlayEvent.Post && renderEventPostMethod != null) { renderEventPostMethod.invokeExact((RenderGameOverlayEvent.Post) event); } else { renderEventMethod.invokeExact(event); } } catch (Error e) { throw e; } catch (Throwable t) { LOGGER.error("Failed to invoke HoloInventory renderEvent", t); isLoaded = false; } } public static void setAngelicaOverride(boolean value) { if (!isLoaded) return; try { angelicaOverrideSetter.invokeExact(value); } catch (Error e) { throw e; } catch (Throwable t) { LOGGER.error("Failed to invoke HoloInventory renderEvent", t); isLoaded = false; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\iris\BiomeCategoryCache.java
package com.gtnewhorizons.angelica.compat.iris; /** * Interface implemented by BiomeGenBase via mixin to cache biome category. * This avoids recomputing the category every frame for shader uniforms. */ public interface BiomeCategoryCache { /** * Gets the cached biome category ordinal, or -1 if not yet computed. */ int iris$getCachedCategory(); /** * Sets the cached biome category ordinal. */ void iris$setCachedCategory(int category); }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\iris\ModdedBiomeDetector.java
package com.gtnewhorizons.angelica.compat.iris; import net.coderbot.iris.parsing.BiomeCategories; import net.minecraft.world.biome.BiomeGenBase; import java.util.LinkedHashMap; import java.util.Map; /** * Detects and categorizes biomes from popular modded biome mods using cached class checks. * Currently supports: BiomesOPlenty (BOP), Realistic World Gen (RWG) */ public class ModdedBiomeDetector { private static boolean initialized = false; // BiomesOPlenty (BOP) cache - dimension-specific base classes // BOP 1.7.10 hierarchy: BOPBiome -> BOPEndBiome/BOPNetherBiome/BOPOverworldBiome -> specific biomes private static Class<?> bopEndBiomeClass = null; private static Class<?> bopNetherBiomeClass = null; private static Class<?> bopOceanBiomeClass = null; // Realistic World Gen (RWG) cache - base biome classes that extend BiomeGenBase // LinkedHashMap maintains insertion order for deterministic behavior private static final Map<Class<?>, BiomeCategories> rwgClassMap = new LinkedHashMap<>(); private static synchronized void initialize() { if (initialized) return; initialized = true; initializeBOP(); initializeRWG(); } private static void initializeBOP() { try { bopEndBiomeClass = Class.forName("biomesoplenty.common.biome.BOPEndBiome"); bopNetherBiomeClass = Class.forName("biomesoplenty.common.biome.BOPNetherBiome"); bopOceanBiomeClass = Class.forName("biomesoplenty.common.biome.BOPOceanBiome"); } catch (ClassNotFoundException ignored) { // BOP not installed } } private static void initializeRWG() { // RWG adds actual BiomeGenBase subclasses in rwg.biomes.base package tryAddRWGClass("rwg.biomes.base.BaseBiomeOcean", BiomeCategories.OCEAN); tryAddRWGClass("rwg.biomes.base.BaseBiomeRiver", BiomeCategories.RIVER); tryAddRWGClass("rwg.biomes.base.BaseBiomePlains", BiomeCategories.PLAINS); tryAddRWGClass("rwg.biomes.base.BaseBiomeColdPlains", BiomeCategories.PLAINS); tryAddRWGClass("rwg.biomes.base.BaseBiomeHotPlains", BiomeCategories.PLAINS); tryAddRWGClass("rwg.biomes.base.BaseBiomeHotDesert", BiomeCategories.DESERT); tryAddRWGClass("rwg.biomes.base.BaseBiomeSnowDesert", BiomeCategories.DESERT); // Cold desert, but still desert tryAddRWGClass("rwg.biomes.base.BaseBiomeJungle", BiomeCategories.JUNGLE); tryAddRWGClass("rwg.biomes.base.BaseBiomeTropicalIsland", BiomeCategories.JUNGLE); // Tropical islands are jungle-like tryAddRWGClass("rwg.biomes.base.BaseBiomeRedwood", BiomeCategories.FOREST); // Redwood/Sequoia forests tryAddRWGClass("rwg.biomes.base.BaseBiomeTemperateForest", BiomeCategories.FOREST); tryAddRWGClass("rwg.biomes.base.BaseBiomeColdForest", BiomeCategories.TAIGA); // Cold forests are taiga-like tryAddRWGClass("rwg.biomes.base.BaseBiomeHotForest", BiomeCategories.FOREST); tryAddRWGClass("rwg.biomes.base.BaseBiomeSnowForest", BiomeCategories.TAIGA); // Snow forests are taiga } private static void tryAddRWGClass(String className, BiomeCategories category) { try { final Class<?> clazz = Class.forName(className); rwgClassMap.put(clazz, category); } catch (ClassNotFoundException ignored) { // Class not available, RWG not installed or different version } } /** * Attempts to detect the biome category for modded biomes. * Returns null if no modded biome detection applies. */ public static BiomeCategories detectModdedBiome(BiomeGenBase biome) { if (!initialized) { initialize(); } // BiomesOPlenty detection - dimension-specific classes give us clear categories if (bopEndBiomeClass != null && bopEndBiomeClass.isInstance(biome)) { return BiomeCategories.THE_END; } if (bopNetherBiomeClass != null && bopNetherBiomeClass.isInstance(biome)) { return BiomeCategories.NETHER; } if (bopOceanBiomeClass != null && bopOceanBiomeClass.isInstance(biome)) { return BiomeCategories.OCEAN; } // For other BOP overworld biomes (e.g., Alps, Arctic, BambooForest), // fall through to name/property-based detection // Realistic World Gen detection for (Map.Entry<Class<?>, BiomeCategories> entry : rwgClassMap.entrySet()) { if (entry.getKey().isInstance(biome)) { return entry.getValue(); } } return null; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\AutoClosableAbstractTexture.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.renderer.texture.AbstractTexture; import org.lwjgl.opengl.GL11; public abstract class AutoClosableAbstractTexture extends AbstractTexture implements AutoCloseable { @Override public void close() throws Exception {} // TODO: Is this needed? public void bind() { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, getGlTextureId()); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ByteBufferBackedInputStream.java
package com.gtnewhorizons.angelica.compat.mojang; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; public class ByteBufferBackedInputStream extends InputStream { ByteBuffer buf; public ByteBufferBackedInputStream(ByteBuffer buf) { this.buf = buf; } @Override public int read() throws IOException { if (!buf.hasRemaining()) { return -1; } return buf.get() & 0xFF; } @Override public int read(byte @NotNull [] bytes, int off, int len) throws IOException { if (!buf.hasRemaining()) { return -1; } len = Math.min(len, buf.remaining()); buf.get(bytes, off, len); return len; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\Camera.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import com.gtnewhorizons.angelica.rendering.RenderingState; import lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.MathHelper; import org.joml.Matrix4f; import org.joml.Vector3d; import org.joml.Vector3f; /** * Singleton camera instance that tracks the current camera position and orientation. */ @Getter public class Camera { public static final Camera INSTANCE = new Camera(); private final Vector3d pos = new Vector3d(); private final BlockPos blockPos = new BlockPos(); private final Vector3f offset = new Vector3f(); private final Matrix4f inverseModelView = new Matrix4f(); private float pitch; private float yaw; private EntityLivingBase entity; private boolean thirdPerson; private float partialTicks; private Camera() { } /** * Updates the camera position and orientation based on the current entity and partial ticks. * * @param entity The entity to track (usually the render view entity) * @param partialTicks The partial tick time for interpolation */ public void update(EntityLivingBase entity, float partialTicks) { this.partialTicks = partialTicks; this.entity = entity; // Entity position (interpolated, at feet level) final double entityX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks; final double entityY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks; final double entityZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks; final double eyeHeight = entity.getEyeHeight(); thirdPerson = Minecraft.getMinecraft().gameSettings.thirdPersonView > 0; final double camX, camY, camZ; offset.set(0, 0, 0); if (thirdPerson) { // Third person: use inverse modelview to find camera offset inverseModelView.set(RenderingState.INSTANCE.getModelViewMatrix()).invert(); inverseModelView.transformPosition(offset); } camX = entityX + offset.x; camY = entityY + eyeHeight + offset.y; camZ = entityZ + offset.z; pos.set(camX, camY, camZ); blockPos.set(MathHelper.floor_double(camX), MathHelper.floor_double(camY), MathHelper.floor_double(camZ)); pitch = entity.cameraPitch; yaw = entity.rotationYaw; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ChunkOcclusionData.java
package com.gtnewhorizons.angelica.compat.mojang; import net.minecraftforge.common.util.ForgeDirection; import java.util.BitSet; import java.util.Set; public class ChunkOcclusionData { private static final int DIRECTION_COUNT = ForgeDirection.values().length; private final BitSet visibility; public ChunkOcclusionData() { this.visibility = new BitSet(DIRECTION_COUNT * DIRECTION_COUNT); } public void addOpenEdgeFaces(Set<ForgeDirection> faces) { for (ForgeDirection dirFrom : faces) { for (ForgeDirection dirTo : faces) { this.setVisibleThrough(dirFrom, dirTo, true); } } for (ForgeDirection direction : faces) { this.visibility.set(direction.ordinal() * DIRECTION_COUNT + direction.ordinal()); } } public void setVisibleThrough(ForgeDirection from, ForgeDirection to, boolean visible) { this.visibility.set(from.ordinal() + to.ordinal() * DIRECTION_COUNT, visible); this.visibility.set(to.ordinal() + from.ordinal() * DIRECTION_COUNT, visible); } public boolean isVisibleThrough(ForgeDirection from, ForgeDirection to) { return this.visibility.get(from.ordinal() + to.ordinal() * DIRECTION_COUNT); } public void fill(boolean visible) { this.visibility.set(0, this.visibility.size(), visible); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ChunkOcclusionDataBuilder.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; import it.unimi.dsi.fastutil.ints.IntPriorityQueue; import net.minecraftforge.common.util.ForgeDirection; import java.util.BitSet; import java.util.EnumSet; import java.util.Set; /** * WARNING: Minecraft 1.16 code rip!! */ public class ChunkOcclusionDataBuilder { private static final int STEP_X = (int)Math.pow(16.0, 0.0); private static final int STEP_Z = (int)Math.pow(16.0, 1.0); private static final int STEP_Y = (int)Math.pow(16.0, 2.0); private static final ForgeDirection[] DIRECTIONS = ForgeDirection.VALID_DIRECTIONS; private final BitSet closed = new BitSet(4096); private static final int[] EDGE_POINTS = new int[1352]; static { int k = 0; for(int l = 0; l < 16; ++l) { for(int m = 0; m < 16; ++m) { for(int n = 0; n < 16; ++n) { if (l == 0 || l == 15 || m == 0 || m == 15 || n == 0 || n == 15) { EDGE_POINTS[k++] = pack(l, m, n); } } } } } private int openCount = 4096; public void markClosed(BlockPos pos) { this.closed.set(pack(pos), true); --this.openCount; } private static int pack(BlockPos pos) { return pack(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15); } private static int pack(int x, int y, int z) { return x << 0 | y << 8 | z << 4; } public ChunkOcclusionData build() { final ChunkOcclusionData lv = new ChunkOcclusionData(); if (4096 - this.openCount < 256) { lv.fill(true); } else if (this.openCount == 0) { lv.fill(false); } else { for(int i : EDGE_POINTS) { if (!this.closed.get(i)) { lv.addOpenEdgeFaces(this.getOpenFaces(i)); } } } return lv; } private Set<ForgeDirection> getOpenFaces(int pos) { final Set<ForgeDirection> set = EnumSet.noneOf(ForgeDirection.class); final IntPriorityQueue intPriorityQueue = new IntArrayFIFOQueue(); intPriorityQueue.enqueue(pos); this.closed.set(pos, true); while(!intPriorityQueue.isEmpty()) { final int j = intPriorityQueue.dequeueInt(); this.addEdgeFaces(j, set); for(ForgeDirection lv : DIRECTIONS) { final int k = this.offset(j, lv); if (k >= 0 && !this.closed.get(k)) { this.closed.set(k, true); intPriorityQueue.enqueue(k); } } } return set; } private void addEdgeFaces(int pos, Set<ForgeDirection> openFaces) { final int j = pos >> 0 & 15; if (j == 0) { openFaces.add(ForgeDirection.WEST); } else if (j == 15) { openFaces.add(ForgeDirection.EAST); } final int k = pos >> 8 & 15; if (k == 0) { openFaces.add(ForgeDirection.DOWN); } else if (k == 15) { openFaces.add(ForgeDirection.UP); } final int l = pos >> 4 & 15; if (l == 0) { openFaces.add(ForgeDirection.NORTH); } else if (l == 15) { openFaces.add(ForgeDirection.SOUTH); } } private int offset(int pos, ForgeDirection arg) { return switch (arg) { case DOWN -> { if ((pos >> 8 & 15) == 0) { yield -1; } yield pos - STEP_Y; } case UP -> { if ((pos >> 8 & 15) == 15) { yield -1; } yield pos + STEP_Y; } case NORTH -> { if ((pos >> 4 & 15) == 0) { yield -1; } yield pos - STEP_Z; } case SOUTH -> { if ((pos >> 4 & 15) == 15) { yield -1; } yield pos + STEP_Z; } case WEST -> { if ((pos >> 0 & 15) == 0) { yield -1; } yield pos - STEP_X; } case EAST -> { if ((pos >> 0 & 15) == 15) { yield -1; } yield pos + STEP_X; } default -> -1; }; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ChunkPos.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; // See if we can merge/mixin/extend ChunkCoordIntPair? public class ChunkPos { public static long INT_MASK = (1L << Integer.SIZE) - 1; public final int x; public final int z; public ChunkPos(int x, int z) { this.x = x; this.z = z; } public ChunkPos(BlockPos pos) { this.x = pos.getX() >> 4; this.z = pos.getZ() >> 4; } public ChunkPos(long pos) { this.x = (int)pos; this.z = (int)(pos >> 32); } public static int getPackedX(long pos) { return (int)(pos & INT_MASK); } public static int getPackedZ(long pos) { return (int)(pos >>> 32 & INT_MASK); } public long toLong() { return toLong(this.x, this.z); } public static long toLong(int x, int z) { return (long)x & 4294967295L | ((long)z & 4294967295L) << 32; } @Override public int hashCode() { final int i = 1664525 * this.x + 1013904223; final int j = 1664525 * (this.z ^ -559038737) + 1013904223; return i ^ j; } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof ChunkPos lv) { return this.x == lv.x && this.z == lv.z; } return false; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ChunkSectionPos.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizon.gtnhlib.blockpos.BlockPos; import org.joml.Vector3i; // See if we can merge/mixin/extend ChunkPosition maybe? public class ChunkSectionPos extends Vector3i { public static int getSectionCoord(int coord) { return coord >> 4; } public static int getBlockCoord(int sectionCoord) { return sectionCoord << 4; } private ChunkSectionPos(int x, int y, int z) { super(x, y, z); } public static ChunkSectionPos from(int x, int y, int z) { return new ChunkSectionPos(x, y, z); } public static ChunkSectionPos from(BlockPos pos) { return new ChunkSectionPos(getSectionCoord(pos.getX()), getSectionCoord(pos.getY()), getSectionCoord(pos.getZ())); } public static long asLong(int x, int y, int z) { long l = 0L; l |= ((long)x & 4194303L) << 42; l |= ((long)y & 1048575L) << 0; l |= ((long)z & 4194303L) << 20; return l; } public static int getLocalCoord(int coord) { return coord & 15; } public static short packLocal(int x, int y, int z) { final int i = getLocalCoord(x); final int j = getLocalCoord(y); final int k = getLocalCoord(z); return (short)(i << 8 | k << 4 | j << 0); } public long asLong() { return asLong(this.x, this.y, this.z); } public int getSectionX() { return this.x; } public int getSectionY() { return this.y; } public int getSectionZ() { return this.z; } public int getMinX() { return this.x << 4; } public int getMinY() { return this.y << 4; } public int getMinZ() { return this.z << 4; } public int getMaxX() { return (this.x << 4) + 15; } public int getMaxY() { return (this.y << 4) + 15; } public int getMaxZ() { return (this.z << 4) + 15; } public ChunkPos toChunkPos() { return new ChunkPos(this.getSectionX(), this.getSectionZ()); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\CompatMathHelper.java
package com.gtnewhorizons.angelica.compat.mojang; public class CompatMathHelper { public static int smallestEncompassingPowerOfTwo(int value) { int j = value - 1; j |= j >> 1; j |= j >> 2; j |= j >> 4; j |= j >> 8; j |= j >> 16; return j + 1; } public static int roundUpToMultiple(int value, int divisor) { if (divisor == 0) { return 0; } else if (value == 0) { return divisor; } else { if (value < 0) { divisor *= -1; } int k = value % divisor; return k == 0 ? value : value + divisor - k; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\Constants.java
package com.gtnewhorizons.angelica.compat.mojang; public class Constants { public static final float DEGREES_TO_RADIANS = (float)Math.PI / 180.0F; }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\Drawable.java
package com.gtnewhorizons.angelica.compat.mojang; public interface Drawable { default void render(int mouseX, int mouseY, float delta) {} }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\Element.java
package com.gtnewhorizons.angelica.compat.mojang; public interface Element { default boolean mouseClicked(double mouseX, double mouseY, int button) { return false; } default boolean mouseDragged(double mouseX, double mouseY, int button) { return false; } default boolean mouseReleased(double mouseX, double mouseY, int button) { return false; } default boolean mouseScrolled(double mouseX, double mouseY, double amount) { return false; } default boolean keyTyped(char typedChar, int keyCode) { return false; } default boolean isMouseOver(double mouseX, double mouseY) { return false; } default boolean changeFocus(boolean lookForwards) { return false; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\GameModeUtil.java
package com.gtnewhorizons.angelica.compat.mojang; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.PlayerControllerMP; public final class GameModeUtil { private GameModeUtil() { } public static boolean isSpectator() { final PlayerControllerMP controller = Minecraft.getMinecraft().playerController; if (controller == null) { return false; } return controller.currentGameType.getID() == 3; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\InteractionHand.java
package com.gtnewhorizons.angelica.compat.mojang; import com.gtnewhorizons.angelica.compat.ModStatus; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public enum InteractionHand { MAIN_HAND, OFF_HAND; InteractionHand() { } public ItemStack getItemInHand(EntityPlayer player){ if (ModStatus.isBackhandLoaded && this == InteractionHand.OFF_HAND){ // off hand (requires backhand) return ModStatus.backhandCompat.getOffhandItem(player); } else { // main hand return player.getHeldItem(); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\NativeImage.java
package com.gtnewhorizons.angelica.compat.mojang; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.IntBuffer; import javax.imageio.ImageIO; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import lombok.Getter; import net.coderbot.iris.Iris; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; // TBD public class NativeImage extends BufferedImage { @Getter private final Format format; @Getter private final int width; @Getter private final int height; @Getter private final int size; public NativeImage(int width, int height, boolean useStb) { this(NativeImage.Format.RGBA, width, height, useStb); } public NativeImage(Format format, int width, int height, boolean useStb) { super(width, height, BufferedImage.TYPE_INT_ARGB); this.format = format; this.width = width; this.height = height; this.size = width * height * format.components; } public NativeImage(Format format, int width, int height, BufferedImage image) { super(image.getColorModel(), image.getRaster(), image.isAlphaPremultiplied(), null); this.format = format; this.width = width; this.height = height; this.size = width * height * format.components; } public static NativeImage read(ByteBuffer buf) throws IOException { return read(new ByteBufferBackedInputStream(buf)); } public static NativeImage read(InputStream inputStream) throws IOException { BufferedImage image = ImageIO.read(inputStream); return new NativeImage(Format.RGBA, image.getWidth(), image.getHeight(), image); } public void downloadTexture(int level, boolean bl) { // this.checkAllocated(); GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, format.components); // GlStateManager._getTexImage(3553, level, format.glFormat, GL11.GL_UNSIGNED_BYTE, this.pixels); // final int width = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_WIDTH); // final int height = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_HEIGHT); final IntBuffer buffer = MemoryUtilities.memAllocInt(size); try { GL11.glGetTexImage(GL11.GL_TEXTURE_2D, level, format.glFormat, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, buffer); int[] data = new int[size]; buffer.get(data); setRGB(0, 0, width, height, data, 0, width); } finally { MemoryUtilities.memFree(buffer); } } public void writeToFile(File file) throws IOException{ try { ImageIO.write(this, "png", file); } catch(IOException ioexception) { Iris.logger.info("[TextureDump] Unable to write: ", ioexception); } } public static int combine(int i, int j, int k, int l) { return (i & 255) << 24 | (j & 255) << 16 | (k & 255) << 8 | (l & 255); } public static int getA(int i) { return i >> 24 & 255; } public static int getR(int i) { return i >> 0 & 255; } public static int getG(int i) { return i >> 8 & 255; } public static int getB(int i) { return i >> 16 & 255; } public int getPixelRGBA(int x, int y) { return getRGB(x, y); } public void setPixelRGBA(int x, int y, int rgb) { setRGB(x, y, rgb); } public enum Format { RGBA(4, GL11.GL_RGBA), RGB(3, GL11.GL_RGB); private final int components; private final int glFormat; Format(int components, int glFormat) { this.components = components; this.glFormat = glFormat; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\mojang\ParentElement.java
package com.gtnewhorizons.angelica.compat.mojang; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.ListIterator; import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Supplier; public interface ParentElement extends Element { List<? extends Element> children(); default Optional<Element> hoveredElement(double mouseX, double mouseY) { for(Element element : this.children()) { if (element.isMouseOver(mouseX, mouseY)) { return Optional.of(element); } } return Optional.empty(); } default boolean mouseClicked(double mouseX, double mouseY, int button) { for(Element element : this.children()) { if (element.mouseClicked(mouseX, mouseY, button)) { this.setFocused(element); if (button == 0) { this.setDragging(true); } return true; } } return false; } default boolean mouseReleased(double mouseX, double mouseY, int button) { this.setDragging(false); return this.hoveredElement(mouseX, mouseY).filter((element) -> element.mouseReleased(mouseX, mouseY, button)).isPresent(); } default boolean mouseDragged(double mouseX, double mouseY, int button) { return this.getFocused() != null && this.isDragging() && button == 0 && this.getFocused().mouseDragged(mouseX, mouseY, button); } boolean isDragging(); void setDragging(boolean dragging); default boolean mouseScrolled(double mouseX, double mouseY, double amount) { return this.hoveredElement(mouseX, mouseY).filter((element) -> element.mouseScrolled(mouseX, mouseY, amount)).isPresent(); } default boolean keyTyped(char typedChar, int keyCode) { return this.getFocused() != null && this.getFocused().keyTyped(typedChar, keyCode); } @Nullable Element getFocused(); void setFocused(@Nullable Element focused); default boolean changeFocus(boolean lookForwards) { final Element element = this.getFocused(); if (element != null && element.changeFocus(lookForwards)) { return true; } else { final List<? extends Element> list = this.children(); final int i = list.indexOf(element); final int j; if (element != null && i >= 0) { j = i + (lookForwards ? 1 : 0); } else if (lookForwards) { j = 0; } else { j = list.size(); } final ListIterator<? extends Element> listIterator = list.listIterator(j); final BooleanSupplier booleanSupplier = lookForwards ? listIterator::hasNext : listIterator::hasPrevious; final Supplier<? extends Element> supplier = lookForwards ? listIterator::next : listIterator::previous; Element element2; do { if (!booleanSupplier.getAsBoolean()) { this.setFocused(null); return false; } element2 = supplier.get(); } while(!element2.changeFocus(lookForwards)); this.setFocused(element2); return true; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\toremove\MatrixStack.java
package com.gtnewhorizons.angelica.compat.toremove; import com.google.common.collect.Queues; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Quaternionf; import java.util.Deque; public class MatrixStack { private final Deque<Entry> matrixStack; public MatrixStack() { this.matrixStack = Queues.newArrayDeque(); matrixStack.add(new Entry(new Matrix4f().identity(), new Matrix3f().identity())); } public MatrixStack(Matrix4f initial) { this.matrixStack = Queues.newArrayDeque(); Matrix3f normal = new Matrix3f(); matrixStack.add(new Entry(initial, initial.normal(normal))); } public Entry peek() { return (Entry)this.matrixStack.getLast(); } public void push() { final Entry lv = (Entry)this.matrixStack.getLast(); this.matrixStack.addLast(new Entry(new Matrix4f(lv.model), new Matrix3f(lv.normal))); } public void pop() { this.matrixStack.removeLast(); } public boolean clear() { return this.matrixStack.size() == 1; } public void translate(double d, double e, double f) { final Entry lv = (Entry)this.matrixStack.getLast(); lv.model.translate((float)d, (float)e, (float)f); } public void rotateX(float f) { final Entry lv = (Entry)this.matrixStack.getLast(); lv.model.rotateX(f); lv.normal.rotateX(f); } public void rotateY(float f) { final Entry lv = (Entry)this.matrixStack.getLast(); lv.model.rotateY(f); lv.normal.rotateY(f); } public void rotateZ(float f) { final Entry lv = (Entry)this.matrixStack.getLast(); lv.model.rotateZ(f); lv.normal.rotateZ(f); } public void scale(float f, float g, float h) { final Entry lv = (Entry)this.matrixStack.getLast(); lv.model.scale(f, g, h); if (f == g && g == h) { if (f > 0.0F) { return; } lv.normal.scale(-1.0F); } float i = 1.0F / f; float j = 1.0F / g; float k = 1.0F / h; float l = invSqrt(i * j * k); lv.normal.scale(l * i, l * j, l * k); } public void multiply(Quaternionf quaternion) { MatrixStack.Entry entry = this.matrixStack.getLast(); entry.model.rotate(quaternion); entry.normal.rotate(quaternion); } public void multiply(Quaternionf quaternion, float originX, float originY, float originZ) { MatrixStack.Entry entry = this.matrixStack.getLast(); entry.model.rotateAround(quaternion, originX, originY, originZ); entry.normal.rotate(quaternion); } public void loadIdentity() { MatrixStack.Entry entry = this.matrixStack.getLast(); entry.model.identity(); entry.normal.identity(); } public void multiplyPositionMatrix(Matrix4f matrix) { this.matrixStack.getLast().model.mul(matrix); } private static float invSqrt(float x) { float xhalf = 0.5f * x; int i = Float.floatToIntBits(x); i = 0x5f3759df - (i >> 1); x = Float.intBitsToFloat(i); x *= (1.5f - xhalf * x * x); return x; } public static final class Entry { private final Matrix4f model; private final Matrix3f normal; private Entry(Matrix4f model, Matrix3f normal) { this.model = model; this.normal = normal; } public Matrix4f getModel() { return model; } public Matrix3f getNormal() { return normal; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\toremove\RenderLayer.java
package com.gtnewhorizons.angelica.compat.toremove; import com.google.common.collect.ImmutableList; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; import lombok.Getter; import net.minecraft.util.ResourceLocation; import javax.annotation.Nullable; import java.util.Objects; import java.util.Optional; public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris) private static final RenderLayer SOLID = of("solid", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 2097152, true, false, RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(MIPMAP_BLOCK_ATLAS_TEXTURE).build(true)); private static final RenderLayer CUTOUT = of("cutout", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 131072, true, false, RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(BLOCK_ATLAS_TEXTURE).alpha(HALF_ALPHA).build(true)); private static final RenderLayer TRANSLUCENT = of("translucent", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 262144, true, true, createTranslucentPhaseData()); @Getter private final VertexFormat vertexFormat; @Getter private final int drawMode; @Getter private final int expectedBufferSize; public RenderLayer(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, Runnable startAction, Runnable endAction) { super(name, startAction, endAction); this.vertexFormat = vertexFormat; this.drawMode = drawMode; this.expectedBufferSize = expectedBufferSize; } public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, MultiPhaseParameters phaseData) { return of(name, vertexFormat, drawMode, expectedBufferSize, false, false, phaseData); } public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) { return RenderLayer.MultiPhase.of(name, vertexFormat, drawMode, expectedBufferSize, hasCrumbling, translucent, phases); } public static RenderLayer solid() { return SOLID; } public static RenderLayer cutout() { return CUTOUT; } private static MultiPhaseParameters createTranslucentPhaseData() { return RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(MIPMAP_BLOCK_ATLAS_TEXTURE).transparency(TRANSLUCENT_TRANSPARENCY).target(TRANSLUCENT_TARGET).build(true); } public static RenderLayer translucent() { return TRANSLUCENT; } 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)); } public int mode() { return this.drawMode; } static final class MultiPhase extends RenderLayer { private static final ObjectOpenCustomHashSet<MultiPhase> CACHE; private final MultiPhaseParameters phases; private final int hash; private final Optional<RenderLayer> affectedOutline; private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) { super(name, vertexFormat, drawMode, expectedBufferSize, () -> { phases.phases.forEach(RenderPhase::startDrawing); }, () -> { phases.phases.forEach(RenderPhase::endDrawing); }); this.phases = phases; this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE ? phases.texture.getId().map((arg2) -> { return getOutline(arg2, phases.cull); }) : Optional.empty(); this.hash = Objects.hash(new Object[]{super.hashCode(), phases}); } public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) { return (MultiPhase)CACHE.addOrGet(new MultiPhase(name, vertexFormat, drawMode, expectedBufferSize, hasCrumbling, translucent, phases)); } public Optional<RenderLayer> getAffectedOutline() { return this.affectedOutline; } @Override public boolean equals(@Nullable Object object) { return this == object; } @Override public int hashCode() { return this.hash; } @Override public String toString() { return "RenderType[" + this.phases + ']'; } static { CACHE = new ObjectOpenCustomHashSet<>(RenderLayer.MultiPhase.HashStrategy.INSTANCE); } static enum HashStrategy implements Hash.Strategy<MultiPhase> { INSTANCE; private HashStrategy() { } public int hashCode(@Nullable MultiPhase arg) { return arg == null ? 0 : arg.hash; } public boolean equals(@Nullable MultiPhase arg, @Nullable MultiPhase arg2) { if (arg == arg2) { return true; } else { return arg != null && arg2 != null ? Objects.equals(arg.phases, arg2.phases) : false; } } } } public static final class MultiPhaseParameters { private final RenderPhase.Texture texture; private final RenderPhase.Transparency transparency; private final RenderPhase.DiffuseLighting diffuseLighting; private final RenderPhase.ShadeModel shadeModel; private final RenderPhase.Alpha alpha; private final RenderPhase.DepthTest depthTest; private final RenderPhase.Cull cull; private final RenderPhase.Lightmap lightmap; private final RenderPhase.Fog fog; private final RenderPhase.Layering layering; private final RenderPhase.Target target; private final RenderPhase.Texturing texturing; private final RenderPhase.WriteMaskState writeMaskState; private final OutlineMode outlineMode; private final ImmutableList<RenderPhase> phases; private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, OutlineMode outlineMode) { this.texture = texture; this.transparency = transparency; this.diffuseLighting = diffuseLighting; this.shadeModel = shadeModel; this.alpha = alpha; this.depthTest = depthTest; this.cull = cull; this.lightmap = lightmap; this.fog = fog; this.layering = layering; this.target = target; this.texturing = texturing; this.writeMaskState = writeMaskState; 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); } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { MultiPhaseParameters rendertype$state = (MultiPhaseParameters)object; return this.outlineMode == rendertype$state.outlineMode && this.phases.equals(rendertype$state.phases); } else { return false; } } @Override public int hashCode() { return Objects.hash(new Object[]{this.phases, this.outlineMode}); } @Override public String toString() { return "CompositeState[" + this.phases + ", outlineProperty=" + this.outlineMode + ']'; } public static Builder builder() { return new Builder(); } public static class Builder { private RenderPhase.Texture texture; private RenderPhase.Transparency transparency; private RenderPhase.DiffuseLighting diffuseLighting; private RenderPhase.ShadeModel shadeModel; private RenderPhase.Alpha alpha; private RenderPhase.DepthTest depthTest; private RenderPhase.Cull cull; private RenderPhase.Lightmap lightmap; private RenderPhase.Fog fog; private RenderPhase.Layering layering; private RenderPhase.Target target; private RenderPhase.Texturing texturing; private RenderPhase.WriteMaskState writeMaskState; 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; } public Builder texture(RenderPhase.Texture texture) { this.texture = texture; return this; } public Builder transparency(RenderPhase.Transparency transparency) { this.transparency = transparency; return this; } public Builder shadeModel(RenderPhase.ShadeModel shadeModel) { this.shadeModel = shadeModel; return this; } public Builder alpha(RenderPhase.Alpha alpha) { this.alpha = alpha; return this; } public Builder depthTest(RenderPhase.DepthTest depthTest) { this.depthTest = depthTest; return this; } public Builder cull(RenderPhase.Cull cull) { this.cull = cull; return this; } public Builder lightmap(RenderPhase.Lightmap lightmap) { this.lightmap = lightmap; return this; } public Builder fog(RenderPhase.Fog fog) { this.fog = fog; return this; } public Builder target(RenderPhase.Target target) { this.target = target; return this; } public Builder texturing(RenderPhase.Texturing texturing) { this.texturing = texturing; return this; } public MultiPhaseParameters build(boolean affectsOutline) { return this.build(affectsOutline ? RenderLayer.OutlineMode.AFFECTS_OUTLINE : RenderLayer.OutlineMode.NONE); } public MultiPhaseParameters build(OutlineMode outlineMode) { return new MultiPhaseParameters(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, outlineMode); } } } enum OutlineMode { NONE("none"), IS_OUTLINE("is_outline"), AFFECTS_OUTLINE("affects_outline"); private final String name; OutlineMode(String name) { this.name = name; } @Override public String toString() { return this.name; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\toremove\RenderPhase.java
package com.gtnewhorizons.angelica.compat.toremove; import com.gtnewhorizons.angelica.glsm.GLStateManager; import me.jellysquid.mods.sodium.client.SodiumClientMod; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import javax.annotation.Nullable; import java.util.Objects; import java.util.Optional; public abstract class RenderPhase { protected final String name; protected Runnable beginAction; private final Runnable endAction; protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", GLStateManager::disableBlend, () -> { }); protected static final Transparency ADDITIVE_TRANSPARENCY = new Transparency("additive_transparency", () -> { GLStateManager.enableBlend(); GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); protected static final Transparency LIGHTNING_TRANSPARENCY = new Transparency("lightning_transparency", () -> { GLStateManager.enableBlend(); GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", () -> { GLStateManager.enableBlend(); GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", () -> { GLStateManager.enableBlend(); GLStateManager.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); protected static final Transparency TRANSLUCENT_TRANSPARENCY = new Transparency("translucent_transparency", () -> { GLStateManager.enableBlend(); GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); }, () -> { GLStateManager.disableBlend(); GLStateManager.defaultBlendFunc(); }); protected static final Alpha ZERO_ALPHA = new Alpha(0.0F); protected static final Alpha ONE_TENTH_ALPHA = new Alpha(0.003921569F); protected static final Alpha HALF_ALPHA = new Alpha(0.5F); protected static final ShadeModel SHADE_MODEL = new ShadeModel(false); protected static final ShadeModel SMOOTH_SHADE_MODEL = new ShadeModel(true); protected static final Texture MIPMAP_BLOCK_ATLAS_TEXTURE; protected static final Texture BLOCK_ATLAS_TEXTURE; protected static final Texture NO_TEXTURE; protected static final Texturing DEFAULT_TEXTURING; protected static final Lightmap ENABLE_LIGHTMAP; protected static final Lightmap DISABLE_LIGHTMAP; protected static final DiffuseLighting ENABLE_DIFFUSE_LIGHTING; protected static final DiffuseLighting DISABLE_DIFFUSE_LIGHTING; protected static final Cull ENABLE_CULLING; protected static final Cull DISABLE_CULLING; protected static final DepthTest ALWAYS_DEPTH_TEST; protected static final DepthTest EQUAL_DEPTH_TEST; protected static final DepthTest LEQUAL_DEPTH_TEST; protected static final WriteMaskState ALL_MASK; protected static final WriteMaskState COLOR_MASK; protected static final WriteMaskState DEPTH_MASK; protected static final Layering NO_LAYERING; protected static final Fog NO_FOG; protected static final Fog FOG; protected static final Fog BLACK_FOG; protected static final Target MAIN_TARGET; protected static final Target OUTLINE_TARGET; protected static final Target TRANSLUCENT_TARGET; public RenderPhase(String name, Runnable beginAction, Runnable endAction) { this.name = name; this.beginAction = beginAction; this.endAction = endAction; } public void startDrawing() { this.beginAction.run(); } public void endDrawing() { this.endAction.run(); } @Override public boolean equals(@Nullable Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { RenderPhase lv = (RenderPhase)object; return this.name.equals(lv.name); } else { return false; } } @Override public int hashCode() { return this.name.hashCode(); } @Override public String toString() { return this.name; } private static ResourceLocation ATLAS = TextureMap.locationBlocksTexture; static { // TODO: Sodium - SpriteAtlasTexture MIPMAP_BLOCK_ATLAS_TEXTURE = new Texture(ATLAS, false, true); BLOCK_ATLAS_TEXTURE = new Texture(ATLAS, false, false); NO_TEXTURE = new Texture(); DEFAULT_TEXTURING = new Texturing("default_texturing", () -> { }, () -> { }); ENABLE_LIGHTMAP = new Lightmap(true); DISABLE_LIGHTMAP = new Lightmap(false); ENABLE_DIFFUSE_LIGHTING = new DiffuseLighting(true); DISABLE_DIFFUSE_LIGHTING = new DiffuseLighting(false); ENABLE_CULLING = new Cull(true); DISABLE_CULLING = new Cull(false); ALWAYS_DEPTH_TEST = new DepthTest("always", GL11.GL_ALWAYS); EQUAL_DEPTH_TEST = new DepthTest("==", GL11.GL_EQUAL); LEQUAL_DEPTH_TEST = new DepthTest("<=", GL11.GL_LEQUAL); ALL_MASK = new WriteMaskState(true, true); COLOR_MASK = new WriteMaskState(true, false); DEPTH_MASK = new WriteMaskState(false, true); NO_LAYERING = new Layering("no_layering", () -> {}, () -> {}); NO_FOG = new Fog("no_fog", () -> { }, () -> { }); FOG = new Fog("fog", () -> { // Unclear what this should do // BackgroundRenderer.setFogBlack(), also levelFogColor() SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color"); GLStateManager.enableFog(); }, GLStateManager::disableFog); BLACK_FOG = new Fog("black_fog", () -> { GLStateManager.fogColor(0.0F, 0.0F, 0.0F, 1.0F); GLStateManager.enableFog(); }, () -> { // Unclear what this should do // BackgroundRenderer.setFogBlack(), also levelFogColor() SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color"); GLStateManager.disableFog(); }); MAIN_TARGET = new Target("main_target", () -> { }, () -> { }); OUTLINE_TARGET = new Target("outline_target", () -> { // TODO: Sodium SodiumClientMod.LOGGER.debug("NOT enabling the entity outline framebuffer"); //MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false); }, () -> { Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); }); TRANSLUCENT_TARGET = new Target("translucent_target", () -> { if (Minecraft.isFancyGraphicsEnabled()) { // TODO: Sodium SodiumClientMod.LOGGER.debug("NOT enabling the translucent framebuffer"); // MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false); } }, () -> { if (Minecraft.isFancyGraphicsEnabled()) { Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); } }); } public static class Target extends RenderPhase { public Target(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); } } public static class Fog extends RenderPhase { public Fog(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); } } public static class Layering extends RenderPhase { public Layering(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); } } public static class WriteMaskState extends RenderPhase { private final boolean color; private final boolean depth; public WriteMaskState(boolean color, boolean depth) { super("write_mask_state", () -> { if (!depth) { GLStateManager.glDepthMask(depth); } if (!color) { GLStateManager.glColorMask(color, color, color, color); } }, () -> { if (!depth) { GLStateManager.glDepthMask(true); } if (!color) { GLStateManager.glColorMask(true, true, true, true); } }); this.color = color; this.depth = depth; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { WriteMaskState lv = (WriteMaskState)object; return this.color == lv.color && this.depth == lv.depth; } else { return false; } } @Override public int hashCode() { return Objects.hash(this.color, this.depth); } @Override public String toString() { return this.name + "[writeColor=" + this.color + ", writeDepth=" + this.depth + ']'; } } public static class DepthTest extends RenderPhase { private final String depthFunction; private final int func; public DepthTest(String string, int i) { super("depth_test", () -> { if (i != GL11.GL_ALWAYS) { GLStateManager.enableDepthTest(); GLStateManager.glDepthFunc(i); } }, () -> { if (i != GL11.GL_ALWAYS) { GLStateManager.disableDepthTest(); GLStateManager.glDepthFunc(GL11.GL_LEQUAL); } }); this.depthFunction = string; this.func = i; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { DepthTest lv = (DepthTest)object; return this.func == lv.func; } else { return false; } } @Override public int hashCode() { return Integer.hashCode(this.func); } @Override public String toString() { return this.name + '[' + this.depthFunction + ']'; } } public static class Cull extends Toggleable { public Cull(boolean culling) { super("cull", () -> { if (!culling) { GLStateManager.disableCull(); } }, () -> { if (!culling) { GLStateManager.enableCull(); } }, culling); } } public static class DiffuseLighting extends Toggleable { public DiffuseLighting(boolean guiLighting) { super("diffuse_lighting", () -> { if (guiLighting) { throw new RuntimeException("Not Implemented Yet"); // net.minecraft.client.drawScreen.DiffuseLighting.enable(); } }, () -> { if (guiLighting) { throw new RuntimeException("Not Implemented Yet"); // net.minecraft.client.drawScreen.DiffuseLighting.disable(); } }, guiLighting); } } public static class Lightmap extends Toggleable { public Lightmap(boolean lightmap) { super("lightmap", () -> { if (lightmap) { // TODO: Sodium - LightmapTextureManager SodiumClientMod.LOGGER.debug("Lightmap - enable (not implemented)"); // throw new RuntimeException("Not Implemented Yet"); // MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable(); } }, () -> { if (lightmap) { // TODO: Sodium - LightmapTextureManager SodiumClientMod.LOGGER.debug("Lightmap - disable (not implemented)"); // throw new RuntimeException("Not Implemented Yet"); // MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable(); } }, lightmap); } } static class Toggleable extends RenderPhase { private final boolean enabled; public Toggleable(String string, Runnable runnable, Runnable runnable2, boolean bl) { super(string, runnable, runnable2); this.enabled = bl; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { Toggleable lv = (Toggleable)object; return this.enabled == lv.enabled; } else { return false; } } @Override public int hashCode() { return Boolean.hashCode(this.enabled); } @Override public String toString() { return this.name + '[' + this.enabled + ']'; } } public static class Texturing extends RenderPhase { public Texturing(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); } } public static class Texture extends RenderPhase { private final Optional<ResourceLocation> id; protected boolean bilinear; protected boolean mipmap; public Texture(ResourceLocation id, boolean bilinear, boolean mipmap) { super("texture", () -> { GLStateManager.enableTexture(); TextureManager lv = Minecraft.getMinecraft().getTextureManager(); lv.bindTexture(id); //GLStateManager.setFilter(bilinear, mipmap); // breaks textures. TODO find out why }, () -> { }); this.id = Optional.of(id); this.bilinear = bilinear; this.mipmap = mipmap; } public Texture() { super("texture", GLStateManager::disableTexture, GLStateManager::enableTexture); this.id = Optional.empty(); this.bilinear = false; this.mipmap = false; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { Texture lv = (Texture)object; return this.id.equals(lv.id) && this.bilinear == lv.bilinear && this.mipmap == lv.mipmap; } else { return false; } } @Override public int hashCode() { return this.id.hashCode(); } @Override public String toString() { return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ")]"; } protected Optional<ResourceLocation> getId() { return this.id; } } public static class ShadeModel extends RenderPhase { private final boolean smooth; public ShadeModel(boolean smooth) { super("shade_model", () -> GLStateManager.glShadeModel(smooth ? GL11.GL_SMOOTH : GL11.GL_FLAT), () -> GLStateManager.glShadeModel(GL11.GL_FLAT)); this.smooth = smooth; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { ShadeModel lv = (ShadeModel)object; return this.smooth == lv.smooth; } else { return false; } } @Override public int hashCode() { return Boolean.hashCode(this.smooth); } @Override public String toString() { return this.name + '[' + (this.smooth ? "smooth" : "flat") + ']'; } } public static class Alpha extends RenderPhase { private final float alpha; public Alpha(float alpha) { super("alpha", () -> { if (alpha > 0.0F) { GLStateManager.enableAlphaTest(); GLStateManager.glAlphaFunc(GL11.GL_GREATER, alpha); } else { GLStateManager.disableAlphaTest(); } }, () -> { GLStateManager.disableAlphaTest(); GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); }); this.alpha = alpha; } @Override public boolean equals(@Nullable Object object) { if (this == object) { return true; } else if (object != null && this.getClass() == object.getClass()) { if (!super.equals(object)) { return false; } else { return this.alpha == ((Alpha)object).alpha; } } else { return false; } } @Override public int hashCode() { return Objects.hash(super.hashCode(), this.alpha); } @Override public String toString() { return this.name + '[' + this.alpha + ']'; } } public static class Transparency extends RenderPhase { public Transparency(String string, Runnable runnable, Runnable runnable2) { super(string, runnable, runnable2); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\compat\toremove\VertexConsumer.java
package com.gtnewhorizons.angelica.compat.toremove; import javax.annotation.Nonnull; public interface VertexConsumer { VertexConsumer vertex(double d, double e, double f); @Nonnull VertexConsumer color(int r, int g, int b, int a); @Nonnull VertexConsumer texture(float u, float v); @Nonnull VertexConsumer overlay(int u, int v); @Nonnull VertexConsumer light(int u, int v); @Nonnull VertexConsumer normal(float x, float y, float z); void next(); default VertexConsumer overlay(int overlay) { return this.overlay(overlay & 0xFFFF, overlay >> 16 & 0xFFFF); } default VertexConsumer light(int light) { return this.light(light & 0xFFFF, light >> 16 & 0xFFFF); } default VertexConsumer color(float red, float green, float blue, float alpha) { return this.color((int)(red * 255.0F), (int)(green * 255.0F), (int)(blue * 255.0F), (int)(alpha * 255.0F)); } default void vertex(float x, float y, float z, float red, float green, float blue, float alpha, float u, float v, int overlay, int light, float normalX, float normalY, float normalZ) { this.vertex((double)x, (double)y, (double)z); this.color(red, green, blue, alpha); this.texture(u, v); this.overlay(overlay); this.light(light); this.normal(normalX, normalY, normalZ); this.next(); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\debug\OpenGLDebugging.java
package com.gtnewhorizons.angelica.glsm.debug; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joml.Matrix4f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; // Adapted from https://github.com/makamys/CoreTweaks/blob/master/src/main/java/makamys/coretweaks/util/OpenGLDebugging.java; // originally from https://github.com/TheGreyGhost/MinecraftByExample/blob/1-8final/src/main/java/minecraftbyexample/usefultools/OpenGLdebugging.java public class OpenGLDebugging { public static final Logger LOGGER = LogManager.getLogger("gldumper"); private static final Consumer<String> LINE_LOGGER = LOGGER::debug; private static final Set<String> seenErrors = new HashSet<>(); public static final String GL_IS_ENABLED = "glIsEnabled()"; public static final String GL_GET_BOOLEANV = "glGetBooleanv()"; public static final String GL_GET_INTEGERV = "glGetIntegerv()"; public static final String GL_GET_FLOATV = "glGetFloatv()"; public static class GLproperty { public GLproperty(int glConstant, String name, String description, String category, String fetchCommand) { this.gLConstant = glConstant; this.name = name; this.description = description; this.category = category; this.fetchCommand = fetchCommand; } public int gLConstant; public String name; public String description; public String category; public String fetchCommand; static final ByteBuffer byteBuffer = BufferUtils.createByteBuffer(16); static final IntBuffer intBuffer = BufferUtils.createIntBuffer(16); static final FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(16); public String getAsString(boolean glsm) { switch(fetchCommand) { case GL_IS_ENABLED: { return "" + (glsm ? GLStateManager.glIsEnabled(gLConstant) : GL11.glIsEnabled(gLConstant)); } case GL_GET_BOOLEANV: { if(GLStateManager.HAS_MULTIPLE_SET.contains(gLConstant)) { byteBuffer.clear(); if(glsm) { GLStateManager.glGetBoolean(gLConstant, byteBuffer); } else { GL11.glGetBoolean(gLConstant, byteBuffer); } final StringBuilder out = new StringBuilder(); for (int i = 0; i < byteBuffer.capacity(); ++i) { out.append(i == 0 ? "" : ", ").append(byteBuffer.get(i)); } return out.toString(); } else { return "" + (glsm ? GLStateManager.glGetBoolean(gLConstant) : GL11.glGetBoolean(gLConstant)); } } case GL_GET_INTEGERV: { if(GLStateManager.HAS_MULTIPLE_SET.contains(gLConstant)) { intBuffer.clear(); if(glsm) { GLStateManager.glGetInteger(gLConstant, intBuffer); } else { GL11.glGetInteger(gLConstant, intBuffer); } final StringBuilder out = new StringBuilder(); for (int i = 0; i < intBuffer.remaining(); ++i) { out.append(i == 0 ? "" : ", ").append(intBuffer.get(i)); } return out.toString(); } else { return "" + (glsm ? GLStateManager.glGetInteger(gLConstant) : GL11.glGetInteger(gLConstant)); } } case GL_GET_FLOATV: { if(GLStateManager.HAS_MULTIPLE_SET.contains(gLConstant)) { floatBuffer.clear(); if(glsm) { GLStateManager.glGetFloat(gLConstant, floatBuffer); } else { GL11.glGetFloat(gLConstant, floatBuffer); } final StringBuilder out = new StringBuilder(); for (int i = 0; i < floatBuffer.remaining(); ++i) { out.append(i == 0 ? "" : ", ").append(String.format("%f", floatBuffer.get(i))); } return out.toString(); } else { return "" + (glsm ? GLStateManager.glGetFloat(gLConstant) : GL11.glGetFloat(gLConstant)); } } default: return ""; } } static final Matrix4f cachedMatrix = new Matrix4f(); static final Matrix4f uncachedMatrix = new Matrix4f(); public Matrix4f getAsMatrix4f(boolean glsm) { if(!fetchCommand.equals(GL_GET_FLOATV)) { throw new IllegalArgumentException("This property does not return a matrix"); } floatBuffer.clear(); if(glsm) { GLStateManager.glGetFloat(gLConstant, floatBuffer); return cachedMatrix.set(0, floatBuffer); } else { GL11.glGetFloat(gLConstant, floatBuffer); return uncachedMatrix.set(0, floatBuffer); } } } public static OpenGLDebugging instance = new OpenGLDebugging(); public GLproperty[] propertyList = { new GLproperty(GL11.GL_ACCUM_ALPHA_BITS, "GL_ACCUM_ALPHA_BITS", "Number of bits per alpha component in the accumulation buffer", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_ACCUM_BLUE_BITS, "GL_ACCUM_BLUE_BITS", "Number of bits per blue component in the accumulation buffer", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_ACCUM_CLEAR_VALUE, "GL_ACCUM_CLEAR_VALUE", "Accumulation-buffer clear value", "accum-buffer", GL_GET_FLOATV), new GLproperty(GL11.GL_ACCUM_GREEN_BITS, "GL_ACCUM_GREEN_BITS", "Number of bits per green component in the accumulation buffer", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_ACCUM_RED_BITS, "GL_ACCUM_RED_BITS", "Number of bits per red component in the accumulation buffer", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_ALPHA_BITS, "GL_ALPHA_BITS", "Number of bits per alpha component in color buffers", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_ALPHA_TEST, "GL_ALPHA_TEST", "Alpha test enabled", "color-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_ALPHA_TEST_FUNC, "GL_ALPHA_TEST_FUNC", "Alpha test function", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_ALPHA_TEST_REF, "GL_ALPHA_TEST_REF", "Alpha test reference value", "color-buffer", GL_GET_FLOATV), new GLproperty(GL11.GL_AMBIENT, "GL_AMBIENT", "Ambient intensity of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_AMBIENT, "GL_AMBIENT", "Ambient material color", "lighting", "glGetMaterialfv()"), new GLproperty(GL11.GL_ATTRIB_STACK_DEPTH, "GL_ATTRIB_STACK_DEPTH", "Attribute stack pointer", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_AUTO_NORMAL, "GL_AUTO_NORMAL", "True if automatic normal generation enabled", "eval", GL_IS_ENABLED), new GLproperty(GL11.GL_AUX_BUFFERS, "GL_AUX_BUFFERS", "Number of auxiliary buffers", "capability", GL_GET_BOOLEANV), new GLproperty(GL11.GL_BLEND, "GL_BLEND", "Blending enabled", "color-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_BLEND_DST, "GL_BLEND_DST", "Blending destination function", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_BLEND_SRC, "GL_BLEND_SRC", "Blending source function", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_BLUE_BITS, "GL_BLUE_BITS", "Number of bits per blue component in color buffers", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_CLIENT_ATTRIB_STACK_DEPTH, "GL_CLIENT_ATTRIB_STACK_DEPTH", "Client attribute stack pointer", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_COEFF, "GL_COEFF", "1D control points", "capability", "glGetMapfv()"), new GLproperty(GL11.GL_COEFF, "GL_COEFF", "2D control points", "capability", "glGetMapfv()"), new GLproperty(GL11.GL_COLOR_ARRAY, "GL_COLOR_ARRAY", "RGBA color array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_COLOR_ARRAY_POINTER, "GL_COLOR_ARRAY_POINTER", "Pointer to the color array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_COLOR_ARRAY_SIZE, "GL_COLOR_ARRAY_SIZE", "Colors per vertex", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_COLOR_ARRAY_STRIDE, "GL_COLOR_ARRAY_STRIDE", "Stride between colors", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_COLOR_ARRAY_TYPE, "GL_COLOR_ARRAY_TYPE", "Type of color components", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_COLOR_CLEAR_VALUE, "GL_COLOR_CLEAR_VALUE", "Color-buffer clear value (RGBA mode)", "color-buffer", GL_GET_FLOATV), new GLproperty(GL11.GL_COLOR_INDEXES, "GL_COLOR_INDEXES", "ca, cd, and cs for color-index lighting", "lighting/e nable", "glGetMaterialfv()"), new GLproperty(GL11.GL_COLOR_LOGIC_OP, "GL_COLOR_LOGIC_OP", "RGBA color logical operation enabled", "color-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_COLOR_MATERIAL, "GL_COLOR_MATERIAL", "True if color tracking is enabled", "lighting", GL_IS_ENABLED), new GLproperty(GL11.GL_COLOR_MATERIAL_FACE, "GL_COLOR_MATERIAL_FACE", "Face(s) affected by color tracking", "lighting", GL_GET_INTEGERV), new GLproperty(GL11.GL_COLOR_MATERIAL_PARAMETER, "GL_COLOR_MATERIAL_PARAMETER", "Material properties tracking current color", "lighting", GL_GET_INTEGERV), new GLproperty(GL11.GL_COLOR_WRITEMASK, "GL_COLOR_WRITEMASK", "Color write enables; R, G, B, or A", "color-buffer", GL_GET_BOOLEANV), new GLproperty(GL11.GL_CONSTANT_ATTENUATION, "GL_CONSTANT_ATTENUATION", "Constant attenuation factor", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_CULL_FACE, "GL_CULL_FACE", "Polygon culling enabled", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_CULL_FACE_MODE, "GL_CULL_FACE_MODE", "Cull front-/back-facing polygons", "polygon", GL_GET_INTEGERV), new GLproperty(GL11.GL_CURRENT_COLOR, "GL_CURRENT_COLOR", "Current color", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_INDEX, "GL_CURRENT_INDEX", "Current color index", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_NORMAL, "GL_CURRENT_NORMAL", "Current normal", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_RASTER_COLOR, "GL_CURRENT_RASTER_COLOR", "Color associated with raster position", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_RASTER_DISTANCE, "GL_CURRENT_RASTER_DISTANCE", "Current raster distance", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_RASTER_INDEX, "GL_CURRENT_RASTER_INDEX", "Color index associated with raster position", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_RASTER_POSITION, "GL_CURRENT_RASTER_POSITION", "Current raster position", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_RASTER_POSITION_VALID, "GL_CURRENT_RASTER_POSITION_VALID", "Raster position valid bit", "current", GL_GET_BOOLEANV), new GLproperty(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS, "GL_CURRENT_RASTER_TEXTURE_COORDS", "Texture coordinates associated with raster position", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_CURRENT_TEXTURE_COORDS, "GL_CURRENT_TEXTURE_COORDS", "Current texture coordinates", "current", GL_GET_FLOATV), new GLproperty(GL11.GL_DEPTH_BITS, "GL_DEPTH_BITS", "Number of depth-buffer bitplanes", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_DEPTH_CLEAR_VALUE, "GL_DEPTH_CLEAR_VALUE", "Depth-buffer clear value", "depth-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_DEPTH_FUNC, "GL_DEPTH_FUNC", "Depth buffer test function", "depth-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_DEPTH_RANGE, "GL_DEPTH_RANGE", "Depth range near and far", "viewport", GL_GET_FLOATV), new GLproperty(GL11.GL_DEPTH_TEST, "GL_DEPTH_TEST", "Depth buffer enabled", "depth-buffer/ena ble", GL_IS_ENABLED), new GLproperty(GL11.GL_DEPTH_WRITEMASK, "GL_DEPTH_WRITEMASK", "Depth buffer enabled for writing", "depth-buffer", GL_GET_BOOLEANV), new GLproperty(GL11.GL_DIFFUSE, "GL_DIFFUSE", "Diffuse intensity of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_DIFFUSE, "GL_DIFFUSE", "Diffuse material color", "lighting", "glGetMaterialfv()"), new GLproperty(GL11.GL_DITHER, "GL_DITHER", "Dithering enabled", "color-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_DOMAIN, "GL_DOMAIN", "1D domain endpoints", "capability", "glGetMapfv()"), new GLproperty(GL11.GL_DOMAIN, "GL_DOMAIN", "2D domain endpoints", "capability", "glGetMapfv()"), new GLproperty(GL11.GL_DOUBLEBUFFER, "GL_DOUBLEBUFFER", "True if front and back buffers exist", "capability", GL_GET_BOOLEANV), new GLproperty(GL11.GL_DRAW_BUFFER, "GL_DRAW_BUFFER", "Buffers selected for drawing", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_EDGE_FLAG, "GL_EDGE_FLAG", "Edge flag", "current", GL_GET_BOOLEANV), new GLproperty(GL11.GL_EDGE_FLAG_ARRAY, "GL_EDGE_FLAG_ARRAY", "Edge flag array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_EDGE_FLAG_ARRAY_POINTER, "GL_EDGE_FLAG_ARRAY_POINTER", "Pointer to the edge flag array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_EDGE_FLAG_ARRAY_STRIDE, "GL_EDGE_FLAG_ARRAY_STRIDE", "Stride between edge flags", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_EMISSION, "GL_EMISSION", "Emissive material color", "lighting", "glGetMaterialfv()"), new GLproperty(GL11.GL_EYE_PLANE, "GL_EYE_PLANE", "Texgen plane equation coefficients", "texture", "glGetTexGenfv()"), new GLproperty(GL11.GL_FEEDBACK_BUFFER_POINTER, "GL_FEEDBACK_BUFFER_POINTER", "Pointer to feedback buffer", "feedback", "glGetPointerv()"), new GLproperty(GL11.GL_FEEDBACK_BUFFER_SIZE, "GL_FEEDBACK_BUFFER_SIZE", "Size of feedback buffer", "feedback", GL_GET_INTEGERV), new GLproperty(GL11.GL_FEEDBACK_BUFFER_TYPE, "GL_FEEDBACK_BUFFER_TYPE", "Type of feedback buffer", "feedback", GL_GET_INTEGERV), new GLproperty(GL11.GL_FOG, "GL_FOG", "True if fog enabled", "fog/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_FOG_COLOR, "GL_FOG_COLOR", "Fog color", "fog", GL_GET_FLOATV), new GLproperty(GL11.GL_FOG_DENSITY, "GL_FOG_DENSITY", "Exponential fog density", "fog", GL_GET_FLOATV), new GLproperty(GL11.GL_FOG_END, "GL_FOG_END", "Linear fog end", "fog", GL_GET_FLOATV), new GLproperty(GL11.GL_FOG_HINT, "GL_FOG_HINT", "Fog hint", "hint", GL_GET_INTEGERV), new GLproperty(GL11.GL_FOG_INDEX, "GL_FOG_INDEX", "Fog index", "fog", GL_GET_FLOATV), new GLproperty(GL11.GL_FOG_MODE, "GL_FOG_MODE", "Fog mode", "fog", GL_GET_INTEGERV), new GLproperty(GL11.GL_FOG_START, "GL_FOG_START", "Linear fog start", "fog", GL_GET_FLOATV), new GLproperty(GL11.GL_FRONT_FACE, "GL_FRONT_FACE", "Polygon front-face CW/CCW indicator", "polygon", GL_GET_INTEGERV), new GLproperty(GL11.GL_GREEN_BITS, "GL_GREEN_BITS", "Number of bits per green component in color buffers", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_ARRAY, "GL_INDEX_ARRAY", "Color-index array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_INDEX_ARRAY_POINTER, "GL_INDEX_ARRAY_POINTER", "Pointer to the index array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_INDEX_ARRAY_STRIDE, "GL_INDEX_ARRAY_STRIDE", "Stride between color indices", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_ARRAY_TYPE, "GL_INDEX_ARRAY_TYPE", "Type of color indices", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_BITS, "GL_INDEX_BITS", "Number of bits per index in color buffers", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_CLEAR_VALUE, "GL_INDEX_CLEAR_VALUE", "Color-buffer clear value (color-index mode)", "color-buffer", GL_GET_FLOATV), new GLproperty(GL11.GL_INDEX_LOGIC_OP, "GL_INDEX_LOGIC_OP", "Color index logical operation enabled", "color-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_INDEX_MODE, "GL_INDEX_MODE", "True if color buffers store indices", "capability", GL_GET_BOOLEANV), new GLproperty(GL11.GL_INDEX_OFFSET, "GL_INDEX_OFFSET", "Value of GL_INDEX_OFFSET", "pixel", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_SHIFT, "GL_INDEX_SHIFT", "Value of GL_INDEX_SHIFT", "pixel", GL_GET_INTEGERV), new GLproperty(GL11.GL_INDEX_WRITEMASK, "GL_INDEX_WRITEMASK", "Color-index writemask", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_LIGHT0, "GL_LIGHT0", "True if light 0 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT1, "GL_LIGHT1", "True if light 1 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT2, "GL_LIGHT2", "True if light 2 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT3, "GL_LIGHT3", "True if light 3 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT4, "GL_LIGHT4", "True if light 4 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT5, "GL_LIGHT5", "True if light 5 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT6, "GL_LIGHT6", "True if light 6 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT7, "GL_LIGHT7", "True if light 7 enabled", "lighting/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHTING, "GL_LIGHTING", "True if lighting is enabled", "lighting/e nable", GL_IS_ENABLED), new GLproperty(GL11.GL_LIGHT_MODEL_AMBIENT, "GL_LIGHT_MODEL_AMBIENT", "Ambient scene color", "lighting", GL_GET_FLOATV), new GLproperty(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, "GL_LIGHT_MODEL_LOCAL_VIEWER", "Viewer is local", "lighting", GL_GET_BOOLEANV), new GLproperty(GL11.GL_LIGHT_MODEL_TWO_SIDE, "GL_LIGHT_MODEL_TWO_SIDE", "Use two-sided lighting", "lighting", GL_GET_BOOLEANV), new GLproperty(GL11.GL_LINEAR_ATTENUATION, "GL_LINEAR_ATTENUATION", "Linear attenuation factor", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_LINE_SMOOTH, "GL_LINE_SMOOTH", "Line antialiasing on", "line/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LINE_SMOOTH_HINT, "GL_LINE_SMOOTH_HINT", "Line smooth hint", "hint", GL_GET_INTEGERV), new GLproperty(GL11.GL_LINE_STIPPLE, "GL_LINE_STIPPLE", "Line stipple enable", "line/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_LINE_STIPPLE_PATTERN, "GL_LINE_STIPPLE_PATTERN", "Line stipple", "line", GL_GET_INTEGERV), new GLproperty(GL11.GL_LINE_STIPPLE_REPEAT, "GL_LINE_STIPPLE_REPEAT", "Line stipple repeat", "line", GL_GET_INTEGERV), new GLproperty(GL11.GL_LINE_WIDTH, "GL_LINE_WIDTH", "Line width", "line", GL_GET_FLOATV), new GLproperty(GL11.GL_LINE_WIDTH_GRANULARITY, "GL_LINE_WIDTH_GRANULARITY", "Antialiased line-width granularity", "capability", GL_GET_FLOATV), new GLproperty(GL11.GL_LINE_WIDTH_RANGE, "GL_LINE_WIDTH_RANGE", "Range (low to high) of antialiased line widths", "capability", GL_GET_FLOATV), new GLproperty(GL11.GL_LIST_BASE, "GL_LIST_BASE", "Setting of glListBase()", "list", GL_GET_INTEGERV), new GLproperty(GL11.GL_LIST_INDEX, "GL_LIST_INDEX", "Number of display list under construction; 0 if none", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_LIST_MODE, "GL_LIST_MODE", "Mode of display list under construction; undefined if none", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_LOGIC_OP_MODE, "GL_LOGIC_OP_MODE", "Logical operation function", "color-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAP1_GRID_DOMAIN, "GL_MAP1_GRID_DOMAIN", "1D grid endpoints", "eval", GL_GET_FLOATV), new GLproperty(GL11.GL_MAP1_GRID_SEGMENTS, "GL_MAP1_GRID_SEGMENTS", "1D grid divisions", "eval", GL_GET_FLOATV), new GLproperty(GL11.GL_MAP2_GRID_DOMAIN, "GL_MAP2_GRID_DOMAIN", "2D grid endpoints", "eval", GL_GET_FLOATV), new GLproperty(GL11.GL_MAP2_GRID_SEGMENTS, "GL_MAP2_GRID_SEGMENTS", "2D grid divisions", "eval", GL_GET_FLOATV), new GLproperty(GL11.GL_MAP_COLOR, "GL_MAP_COLOR", "True if colors are mapped", "pixel", GL_GET_BOOLEANV), new GLproperty(GL11.GL_MAP_STENCIL, "GL_MAP_STENCIL", "True if stencil values are mapped", "pixel", GL_GET_BOOLEANV), new GLproperty(GL11.GL_MATRIX_MODE, "GL_MATRIX_MODE", "Current matrix mode", "transform", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_ATTRIB_STACK_DEPTH, "GL_MAX_ATTRIB_STACK_DEPTH", "Maximum depth of the attribute stack", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_CLIENT_ATTRIB_STACK_DEPTH, "GL_MAX_CLIENT_ATTRIB_STACK_DEPTH", "Maximum depth of the client attribute stack", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_CLIP_PLANES, "GL_MAX_CLIP_PLANES", "Maximum number of user clipping planes", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_EVAL_ORDER, "GL_MAX_EVAL_ORDER", "Maximum evaluator polynomial order", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_LIGHTS, "GL_MAX_LIGHTS", "Maximum number of lights", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_LIST_NESTING, "GL_MAX_LIST_NESTING", "Maximum display-list call nesting", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_MODELVIEW_STACK_DEPTH, "GL_MAX_MODELVIEW_STACK_DEPTH", "Maximum modelview-matrix stack depth", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_NAME_STACK_DEPTH, "GL_MAX_NAME_STACK_DEPTH", "Maximum selection-name stack depth", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_PIXEL_MAP_TABLE, "GL_MAX_PIXEL_MAP_TABLE", "Maximum size of a glPixelMap() translation table", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_PROJECTION_STACK_DEPTH, "GL_MAX_PROJECTION_STACK_DEPTH", "Maximum projection-matrix stack depth", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_TEXTURE_SIZE, "GL_MAX_TEXTURE_SIZE", "See discussion in Texture Proxy in Chapter 9", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_TEXTURE_STACK_DEPTH, "GL_MAX_TEXTURE_STACK_DEPTH", "Maximum depth of texture matrix stack", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MAX_VIEWPORT_DIMS, "GL_MAX_VIEWPORT_DIMS", "Maximum viewport dimensions", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_MODELVIEW_MATRIX, "GL_MODELVIEW_MATRIX", "Modelview matrix stack", "matrix", GL_GET_FLOATV), new GLproperty(GL11.GL_MODELVIEW_STACK_DEPTH, "GL_MODELVIEW_STACK_DEPTH", "Modelview matrix stack pointer", "matrix", GL_GET_INTEGERV), new GLproperty(GL11.GL_NAME_STACK_DEPTH, "GL_NAME_STACK_DEPTH", "Name stack depth", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_NORMALIZE, "GL_NORMALIZE", "Current normal normalization on/off", "transform/ enable", GL_IS_ENABLED), new GLproperty(GL11.GL_NORMAL_ARRAY, "GL_NORMAL_ARRAY", "Normal array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_NORMAL_ARRAY_POINTER, "GL_NORMAL_ARRAY_POINTER", "Pointer to the normal array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_NORMAL_ARRAY_STRIDE, "GL_NORMAL_ARRAY_STRIDE", "Stride between normals", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_NORMAL_ARRAY_TYPE, "GL_NORMAL_ARRAY_TYPE", "Type of normal coordinates", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_OBJECT_PLANE, "GL_OBJECT_PLANE", "Texgen object linear coefficients", "texture", "glGetTexGenfv()"), new GLproperty(GL11.GL_ORDER, "GL_ORDER", "1D map order", "capability", "glGetMapiv()"), new GLproperty(GL11.GL_ORDER, "GL_ORDER", "2D map orders", "capability", "glGetMapiv()"), new GLproperty(GL11.GL_PACK_ALIGNMENT, "GL_PACK_ALIGNMENT", "Value of GL_PACK_ALIGNMENT", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_PACK_LSB_FIRST, "GL_PACK_LSB_FIRST", "Value of GL_PACK_LSB_FIRST", "pixel-store", GL_GET_BOOLEANV), new GLproperty(GL11.GL_PACK_ROW_LENGTH, "GL_PACK_ROW_LENGTH", "Value of GL_PACK_ROW_LENGTH", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_PACK_SKIP_PIXELS, "GL_PACK_SKIP_PIXELS", "Value of GL_PACK_SKIP_PIXELS", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_PACK_SKIP_ROWS, "GL_PACK_SKIP_ROWS", "Value of GL_PACK_SKIP_ROWS", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_PACK_SWAP_BYTES, "GL_PACK_SWAP_BYTES", "Value of GL_PACK_SWAP_BYTES", "pixel-store", GL_GET_BOOLEANV), new GLproperty(GL11.GL_PERSPECTIVE_CORRECTION_HINT, "GL_PERSPECTIVE_CORRECTION_HINT", "Perspective correction hint", "hint", GL_GET_INTEGERV), new GLproperty(GL11.GL_POINT_SIZE, "GL_POINT_SIZE", "Point size", "point", GL_GET_FLOATV), new GLproperty(GL11.GL_POINT_SIZE_GRANULARITY, "GL_POINT_SIZE_GRANULARITY", "Antialiased point-size granularity", "capability", GL_GET_FLOATV), new GLproperty(GL11.GL_POINT_SIZE_RANGE, "GL_POINT_SIZE_RANGE", "Range (low to high) of antialiased point sizes", "capability", GL_GET_FLOATV), new GLproperty(GL11.GL_POINT_SMOOTH, "GL_POINT_SMOOTH", "Point antialiasing on", "point/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POINT_SMOOTH_HINT, "GL_POINT_SMOOTH_HINT", "Point smooth hint", "hint", GL_GET_INTEGERV), new GLproperty(GL11.GL_POLYGON_MODE, "GL_POLYGON_MODE", "Polygon rasterization mode (front and back)", "polygon", GL_GET_INTEGERV), new GLproperty(GL11.GL_POLYGON_OFFSET_FACTOR, "GL_POLYGON_OFFSET_FACTOR", "Polygon offset factor", "polygon", GL_GET_FLOATV), new GLproperty(GL11.GL_POLYGON_OFFSET_FILL, "GL_POLYGON_OFFSET_FILL", "Polygon offset enable for GL_FILL mode rasterization", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POLYGON_OFFSET_LINE, "GL_POLYGON_OFFSET_LINE", "Polygon offset enable for GL_LINE mode rasterization", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POLYGON_OFFSET_POINT, "GL_POLYGON_OFFSET_POINT", "Polygon offset enable for GL_POINT mode rasterization", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POLYGON_SMOOTH, "GL_POLYGON_SMOOTH", "Polygon antialiasing on", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POLYGON_SMOOTH_HINT, "GL_POLYGON_SMOOTH_HINT", "Polygon smooth hint", "hint", GL_GET_INTEGERV), new GLproperty(GL11.GL_POLYGON_STIPPLE, "GL_POLYGON_STIPPLE", "Polygon stipple enable", "polygon/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_POSITION, "GL_POSITION", "Position of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_PROJECTION_MATRIX, "GL_PROJECTION_MATRIX", "Projection matrix stack", "matrix", GL_GET_FLOATV), new GLproperty(GL11.GL_PROJECTION_STACK_DEPTH, "GL_PROJECTION_STACK_DEPTH", "Projection matrix stack pointer", "matrix", GL_GET_INTEGERV), new GLproperty(GL11.GL_QUADRATIC_ATTENUATION, "GL_QUADRATIC_ATTENUATION", "Quadratic attenuation factor", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_READ_BUFFER, "GL_READ_BUFFER", "Read source buffer", "pixel", GL_GET_INTEGERV), new GLproperty(GL11.GL_RED_BITS, "GL_RED_BITS", "Number of bits per red component in color buffers", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_RENDER_MODE, "GL_RENDER_MODE", "glRenderMode() setting", "current", GL_GET_INTEGERV), new GLproperty(GL11.GL_RGBA_MODE, "GL_RGBA_MODE", "True if color buffers store RGBA", "capability", GL_GET_BOOLEANV), new GLproperty(GL11.GL_SCISSOR_BOX, "GL_SCISSOR_BOX", "Scissor box", "scissor", GL_GET_INTEGERV), new GLproperty(GL11.GL_SCISSOR_TEST, "GL_SCISSOR_TEST", "Scissoring enabled", "scissor/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_SELECTION_BUFFER_POINTER, "GL_SELECTION_BUFFER_POINTER", "Pointer to selection buffer", "select", "glGetPointerv()"), new GLproperty(GL11.GL_SELECTION_BUFFER_SIZE, "GL_SELECTION_BUFFER_SIZE", "Size of selection buffer", "select", GL_GET_INTEGERV), new GLproperty(GL11.GL_SHADE_MODEL, "GL_SHADE_MODEL", "glShadeModel() setting", "lighting", GL_GET_INTEGERV), new GLproperty(GL11.GL_SHININESS, "GL_SHININESS", "Specular exponent of material", "lighting", "glGetMaterialfv()"), new GLproperty(GL11.GL_SPECULAR, "GL_SPECULAR", "Specular intensity of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_SPECULAR, "GL_SPECULAR", "Specular material color", "lighting", "glGetMaterialfv()"), new GLproperty(GL11.GL_SPOT_CUTOFF, "GL_SPOT_CUTOFF", "Spotlight angle of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_SPOT_DIRECTION, "GL_SPOT_DIRECTION", "Spotlight direction of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_SPOT_EXPONENT, "GL_SPOT_EXPONENT", "Spotlight exponent of light i", "lighting", "glGetLightfv()"), new GLproperty(GL11.GL_STENCIL_BITS, "GL_STENCIL_BITS", "Number of stencil bitplanes", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_CLEAR_VALUE, "GL_STENCIL_CLEAR_VALUE", "Stencil-buffer clear value", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_FAIL, "GL_STENCIL_FAIL", "Stencil fail action", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_FUNC, "GL_STENCIL_FUNC", "Stencil function", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_PASS_DEPTH_FAIL, "GL_STENCIL_PASS_DEPTH_FAIL", "Stencil depth buffer fail action", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_PASS_DEPTH_PASS, "GL_STENCIL_PASS_DEPTH_PASS", "Stencil depth buffer pass action", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_REF, "GL_STENCIL_REF", "Stencil reference value", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_TEST, "GL_STENCIL_TEST", "Stenciling enabled", "stencil-buffer/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_STENCIL_VALUE_MASK, "GL_STENCIL_VALUE_MASK", "Stencil mask", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STENCIL_WRITEMASK, "GL_STENCIL_WRITEMASK", "Stencil-buffer writemask", "stencil-buffer", GL_GET_INTEGERV), new GLproperty(GL11.GL_STEREO, "GL_STEREO", "True if left and right buffers exist", "capability", GL_GET_BOOLEANV), new GLproperty(GL11.GL_SUBPIXEL_BITS, "GL_SUBPIXEL_BITS", "Number of bits of subpixel precision in x and y", "capability", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE, "GL_TEXTURE", "x-D texture image at level of detail i", "UNUSED", "glGetTexImage()"), new GLproperty(GL11.GL_TEXTURE_1D, "GL_TEXTURE_1D", "True if 1-D texturing enabled ", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_2D, "GL_TEXTURE_2D", "True if 2-D texturing enabled ", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_ALPHA_SIZE, "GL_TEXTURE_ALPHA_SIZE", "x-D texture image i's alpha resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_BINDING_1D, "GL_TEXTURE_BINDING_1D", "Texture object bound to GL_TEXTURE_1D", "texture", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_BINDING_2D, "GL_TEXTURE_BINDING_2D", "Texture object bound to GL_TEXTURE_2D", "texture", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_BLUE_SIZE, "GL_TEXTURE_BLUE_SIZE", "x-D texture image i's blue resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_BORDER, "GL_TEXTURE_BORDER", "x-D texture image i's border width", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_BORDER_COLOR, "GL_TEXTURE_BORDER_COLOR", "Texture border color", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_TEXTURE_COORD_ARRAY, "GL_TEXTURE_COORD_ARRAY", "Texture coordinate array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_COORD_ARRAY_POINTER, "GL_TEXTURE_COORD_ARRAY_POINTER", "Pointer to the texture coordinate array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_TEXTURE_COORD_ARRAY_SIZE, "GL_TEXTURE_COORD_ARRAY_SIZE", "Texture coordinates per element", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_COORD_ARRAY_STRIDE, "GL_TEXTURE_COORD_ARRAY_STRIDE", "Stride between texture coordinates", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_COORD_ARRAY_TYPE, "GL_TEXTURE_COORD_ARRAY_TYPE", "Type of texture coordinates", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_ENV_COLOR, "GL_TEXTURE_ENV_COLOR", "Texture environment color", "texture", "glGetTexEnvfv()"), new GLproperty(GL11.GL_TEXTURE_ENV_MODE, "GL_TEXTURE_ENV_MODE", "Texture application function", "texture", "glGetTexEnviv()"), new GLproperty(GL11.GL_TEXTURE_GEN_MODE, "GL_TEXTURE_GEN_MODE", "Function used for texgen", "texture", "glGetTexGeniv()"), new GLproperty(GL11.GL_TEXTURE_GEN_Q, "GL_TEXTURE_GEN_Q", "Texgen enabled (x is S, T, R, or Q)", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_GEN_R, "GL_TEXTURE_GEN_R", "Texgen enabled (x is S, T, R, or Q)", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_GEN_S, "GL_TEXTURE_GEN_S", "Texgen enabled (x is S, T, R, or Q)", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_GEN_T, "GL_TEXTURE_GEN_T", "Texgen enabled (x is S, T, R, or Q)", "texture/enable", GL_IS_ENABLED), new GLproperty(GL11.GL_TEXTURE_GREEN_SIZE, "GL_TEXTURE_GREEN_SIZE", "x-D texture image i's green resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_HEIGHT, "GL_TEXTURE_HEIGHT", "x-D texture image i's height", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_INTENSITY_SIZE, "GL_TEXTURE_INTENSITY_SIZE", "x-D texture image i's intensity resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_LUMINANCE_SIZE, "GL_TEXTURE_LUMINANCE_SIZE", "x-D texture image i's luminance resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_MAG_FILTER, "GL_TEXTURE_MAG_FILTER", "Texture magnification function", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_TEXTURE_MATRIX, "GL_TEXTURE_MATRIX", "Texture matrix stack", "matrix", GL_GET_FLOATV), new GLproperty(GL11.GL_TEXTURE_MIN_FILTER, "GL_TEXTURE_MIN_FILTER", "Texture minification function", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_TEXTURE_PRIORITY, "GL_TEXTURE_PRIORITY", "Texture object priority", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_TEXTURE_RED_SIZE, "GL_TEXTURE_RED_SIZE", "x-D texture image i's red resolution", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_STACK_DEPTH, "GL_TEXTURE_STACK_DEPTH", "Texture matrix stack pointer", "matrix", GL_GET_INTEGERV), new GLproperty(GL11.GL_TEXTURE_WIDTH, "GL_TEXTURE_WIDTH", "x-D texture image i's width", "UNUSED", "glGetTexLevelParameter*()"), new GLproperty(GL11.GL_TEXTURE_WRAP_S, "GL_TEXTURE_WRAP_S", "Texture wrap mode (x is S or T)", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_TEXTURE_WRAP_T, "GL_TEXTURE_WRAP_T", "Texture wrap mode (x is S or T)", "texture", "glGetTexParameter*()"), new GLproperty(GL11.GL_UNPACK_ALIGNMENT, "GL_UNPACK_ALIGNMENT", "Value of GL_UNPACK_ALIGNMENT", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_UNPACK_LSB_FIRST, "GL_UNPACK_LSB_FIRST", "Value of GL_UNPACK_LSB_FIRST", "pixel-store", GL_GET_BOOLEANV), new GLproperty(GL11.GL_UNPACK_ROW_LENGTH, "GL_UNPACK_ROW_LENGTH", "Value of GL_UNPACK_ROW_LENGTH", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_UNPACK_SKIP_PIXELS, "GL_UNPACK_SKIP_PIXELS", "Value of GL_UNPACK_SKIP_PIXELS", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_UNPACK_SKIP_ROWS, "GL_UNPACK_SKIP_ROWS", "Value of GL_UNPACK_SKIP_ROWS", "pixel-store", GL_GET_INTEGERV), new GLproperty(GL11.GL_UNPACK_SWAP_BYTES, "GL_UNPACK_SWAP_BYTES", "Value of GL_UNPACK_SWAP_BYTES", "pixel-store", GL_GET_BOOLEANV), new GLproperty(GL11.GL_VERTEX_ARRAY, "GL_VERTEX_ARRAY", "Vertex array enable", "vertex-array", GL_IS_ENABLED), new GLproperty(GL11.GL_VERTEX_ARRAY_POINTER, "GL_VERTEX_ARRAY_POINTER", "Pointer to the vertex array", "vertex-array", "glGetPointerv()"), new GLproperty(GL11.GL_VERTEX_ARRAY_SIZE, "GL_VERTEX_ARRAY_SIZE", "Coordinates per vertex", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_VERTEX_ARRAY_STRIDE, "GL_VERTEX_ARRAY_STRIDE", "Stride between vertices", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_VERTEX_ARRAY_TYPE, "GL_VERTEX_ARRAY_TYPE", "Type of vertex coordinates", "vertex-array", GL_GET_INTEGERV), new GLproperty(GL11.GL_VIEWPORT, "GL_VIEWPORT", "Viewport origin and extent", "viewport", GL_GET_INTEGERV), new GLproperty(GL11.GL_ZOOM_X, "GL_ZOOM_X", "x zoom factor", "pixel", GL_GET_FLOATV), new GLproperty(GL11.GL_ZOOM_Y, "GL_ZOOM_Y", "y zoom factor", "pixel", GL_GET_FLOATV), }; public static void dumpToFile(Consumer<Consumer<String>> dumper, String fileName) { final List<String> lines = new ArrayList<>(); dumper.accept(lines::add); try { FileUtils.writeLines(new File(fileName), lines); } catch (IOException e) { LOGGER.error("Failed to write file"); e.printStackTrace(); } } public static void dumpStateToFile() { dumpToFile(p -> dumpState(p, false), "gl-dump-state.txt"); } public static void dumpGLSMStateToFile() { dumpToFile(p -> dumpState(p, true), "glsm-dump-state.txt"); } public static void dumpState(boolean glsm) { dumpState(LINE_LOGGER, glsm); } public static void dumpState(Consumer<String> printer, boolean glsm) { for (int i = 0; i < instance.propertyList.length; ++i) { final GLproperty gLProperty = instance.propertyList[i]; printer.accept(gLProperty.name + ":" + gLProperty.getAsString(glsm) + " (" + gLProperty.description + ")"); } } public static void dumpIsEnabledToFile(boolean glsm) { dumpToFile(p -> dumpIsEnabled(p, glsm), (glsm ? "glsm" : "gl") + "-dump-enabled.txt"); } public static void dumpIsEnabled(boolean glsm) { dumpIsEnabled(LINE_LOGGER, glsm); } public static void dumpIsEnabled(Consumer<String> printer, boolean glsm) { for (int i = 0; i < instance.propertyList.length; ++i) { final GLproperty gLProperty = instance.propertyList[i]; if (gLProperty.fetchCommand.equals(GL_IS_ENABLED)) { printer.accept(gLProperty.name + ":"); printer.accept("" + gLProperty.getAsString(glsm)); printer.accept(" (" + gLProperty.description + ")"); } } } public static void dumpTypeToFile(String type, boolean glsm) { dumpToFile(p -> dumpType(type, p, glsm), (glsm ? "glsm" : "gl") + "-dump-type-" + type + ".txt"); } public static void dumpType(String type, boolean glsm) { dumpType(type, LINE_LOGGER, glsm); } public static void dumpType(String type, Consumer<String> printer, boolean glsm) { for (int i = 0; i < instance.propertyList.length; ++i) { final GLproperty gLProperty = instance.propertyList[i]; if (gLProperty.category.equals(type)) { printer.accept(gLProperty.name + ":"); printer.accept(gLProperty.getAsString(glsm)); printer.accept(" (" + gLProperty.description + ")"); } } } public static String getGLSMErrorLog() { return getGLSMErrorLog(null, false, false); } // Re-entrancy guard - getGLSMErrorLog calls glActiveTexture which could trigger checkGLSMOnce private static boolean inCheck = false; /** * Enhanced GLSM error logging with context, stack trace, and first-occurrence filtering. * * @param context Optional context string to include in error messages (e.g., "During rendering") * @param logStacktrace If true, includes the current stack trace in the error output * @param onlyFirstOccurrence If true, only logs each unique error once * @return Error log string if mismatches found, null otherwise */ public static String getGLSMErrorLog(String context, boolean logStacktrace, boolean onlyFirstOccurrence) { if (inCheck) return null; if (!GLStateManager.isCachingEnabled() || GLStateManager.isRecordingDisplayList()) { return null; } inCheck = true; try { String group = "checkGLSM" + (context == null ? "" : " " + context); GLDebug.pushGroup(group); final StringBuilder error = new StringBuilder(); boolean mismatch = false; if (context != null && !context.isEmpty()) { error.append("[").append(context).append("] "); } for (int i = 0; i < instance.propertyList.length; ++i) { final GLproperty gLProperty = instance.propertyList[i]; if (gLProperty.fetchCommand.equals(GL_GET_FLOATV) && gLProperty.name.endsWith("_MATRIX")) { final Matrix4f cached = gLProperty.getAsMatrix4f(true); final Matrix4f uncached = gLProperty.getAsMatrix4f(false); // Skip comparison if either matrix is degenerate (contains NaN/Infinity) these represent invalid GL state from bad parameters, not cache bugs if (isMatrixDegenerate(cached) || isMatrixDegenerate(uncached)) continue; if (!matricesEquivalent(cached, uncached, 0.001f)) { final String errorKey = "MATRIX:" + gLProperty.name; if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { final String errorMsg = "GLSM mismatch: " + gLProperty.name + "\ncached:\n" + cached + "uncached:\n" + uncached; LOGGER.error(errorMsg); error.append(errorMsg).append('\n'); mismatch = true; } } } else { final String cached = gLProperty.getAsString(true); final String uncached = gLProperty.getAsString(false); if (!cached.equals(uncached)) { final String errorKey = "PROPERTY:" + gLProperty.name + ":" + cached + ":" + uncached; if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { error.append("GLSM mismatch: ").append(gLProperty.name).append(" cached: ").append(cached).append(" uncached: ").append(uncached); error.append('\n'); mismatch = true; } } } } final TextureUnitArray textureUnits = GLStateManager.getTextures(); final int currentActiveTexture = GLStateManager.getActiveTextureUnit(); // Check GL_ACTIVE_TEXTURE final int glActiveUnit = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE) - GL13.GL_TEXTURE0; if (glActiveUnit != currentActiveTexture) { final String errorKey = "ACTIVE_TEXTURE:" + currentActiveTexture + ":" + glActiveUnit; if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { error.append("GLSM mismatch: GL_ACTIVE_TEXTURE cached: ").append(currentActiveTexture) .append(" uncached: ").append(glActiveUnit).append('\n'); mismatch = true; } } // Check per-unit texture state for (int i = 0; i < textureUnits.textureMatricies.length; i++) { GL13.glActiveTexture(GL13.GL_TEXTURE0 + i); // Check GL_TEXTURE_2D enabled final boolean cachedEnabled = textureUnits.getTextureUnitStates(i).isEnabled(); final boolean uncachedEnabled = GL11.glIsEnabled(GL11.GL_TEXTURE_2D); if (cachedEnabled != uncachedEnabled) { final String errorKey = "TEXTURE_2D:" + i + ":" + cachedEnabled + ":" + uncachedEnabled; if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { error.append("GLSM mismatch: GL_TEXTURE_2D cached: ").append(cachedEnabled) .append(" uncached: ").append(uncachedEnabled) .append(", texture unit: GL_TEXTURE").append(i).append('\n'); mismatch = true; } } // Check GL_TEXTURE_BINDING_2D final int cachedBinding = textureUnits.getTextureUnitBindings(i).getBinding(); final int uncachedBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); if (cachedBinding != uncachedBinding) { final String errorKey = "TEXTURE_BINDING_2D:" + i + ":" + cachedBinding + ":" + uncachedBinding; if (!onlyFirstOccurrence || seenErrors.add(errorKey)) { error.append("GLSM mismatch: GL_TEXTURE_BINDING_2D cached: ").append(cachedBinding) .append(" uncached: ").append(uncachedBinding) .append(", texture unit: GL_TEXTURE").append(i).append('\n'); mismatch = true; } } } GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentActiveTexture); // Add stack trace if requested if (mismatch && logStacktrace) { error.append("\nStack trace:\n"); final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (int i = 2; i < stackTrace.length; i++) { error.append(" at ").append(stackTrace[i].toString()).append('\n'); } } GLDebug.popGroup(); return mismatch ? error.toString() : null; } finally { inCheck = false; } } public static boolean checkGLSMOnce(String context) { final String output = getGLSMErrorLog(context, true, true); if (output != null) { // Only log on actual mismatch LOGGER.error("[{}] MISMATCH thread={}\n{}", context, Thread.currentThread().getName(), output); return false; } return true; } /** * Check if a matrix contains any non-finite values (NaN or Infinity). * Such matrices represent invalid/degenerate GL state (e.g., zero near/far in projection). */ private static boolean isMatrixDegenerate(Matrix4f matrix) { for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { if (!Float.isFinite(matrix.get(col, row))) { return true; } } } return false; } /** * Compare two matrices with tolerance for NaN/Infinity. * Treats NaN == NaN and Infinity == Infinity as equal (both are degenerate states). * For finite values, uses epsilon comparison. */ private static boolean matricesEquivalent(Matrix4f a, Matrix4f b, float epsilon) { // Compare all 16 elements for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { final float aVal = a.get(col, row); final float bVal = b.get(col, row); // If both are non-finite (NaN or Infinity), consider them equal if (!Float.isFinite(aVal) && !Float.isFinite(bVal)) { // Both non-finite: check if both NaN or both same Infinity if (Float.isNaN(aVal) && Float.isNaN(bVal)) continue; if (Float.isInfinite(aVal) && Float.isInfinite(bVal)) { // Check same sign of infinity if ((aVal > 0) == (bVal > 0)) continue; } return false; // Different non-finite values } // If one is finite and other is not, they differ if (Float.isFinite(aVal) != Float.isFinite(bVal)) { return false; } // Both finite: use epsilon comparison if (Math.abs(aVal - bVal) > epsilon) { return false; } } } return true; } public static void checkGLSM() { final String output = getGLSMErrorLog(); if (output == null) { LOGGER.info("GLSM state matches!"); } else { LOGGER.error(output); } } public static void copyTexture(ResourceLocation resource, File output) { final Object object = Minecraft.getMinecraft().renderEngine.mapTextureObjects.get(resource); if (object != null) { copyTexture(((ITextureObject) object).getGlTextureId(), output); } } public static void copyTexture(int textureID, File output) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, textureID); int width = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); int height = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); BufferedImage bufferedimage = new BufferedImage(width, height, 1); final int[] pixelValues = ((DataBufferInt) bufferedimage.getRaster().getDataBuffer()).getData(); IntBuffer pixelBuffer = BufferUtils.createIntBuffer(pixelValues.length); GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixelBuffer); pixelBuffer.get(pixelValues); // Flip texture final int halfHeight = height / 2; final int[] rowBuffer = new int[width]; for (int y = 0; y < halfHeight; y++) { final int top = y * width; final int bottom = (height - 1 - y) * width; System.arraycopy(pixelValues, top, rowBuffer, 0, width); System.arraycopy(pixelValues, bottom, pixelValues, top, width); System.arraycopy(rowBuffer, 0, pixelValues, bottom, width); } File dir = output.getParentFile(); dir.mkdirs(); copyBufferedImageToFile(bufferedimage, output); bufferedimage.flush(); } private static void copyBufferedImageToFile(BufferedImage image, File file) { try { ImageIO.write(image, "png", file); } catch (Exception e) { e.printStackTrace(); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\dsa\DSAAccess.java
package com.gtnewhorizons.angelica.glsm.dsa; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; public interface DSAAccess { void generateMipmaps(int texture, int target); // Texture image upload - DSA allows specifying texture directly without binding void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels); void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels); void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels); void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels); void texParameteri(int texture, int target, int pname, int param); void texParameterf(int texture, int target, int pname, float param); void texParameteriv(int texture, int target, int pname, IntBuffer params); void readBuffer(int framebuffer, int buffer); void drawBuffers(int framebuffer, IntBuffer buffers); int getTexParameteri(int texture, int target, int pname); int getTexLevelParameteri(int texture, int level, int pname); void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height); void bindTextureToUnit(int unit, int texture); int bufferStorage(int target, FloatBuffer data, int usage); void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter); void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels); int createFramebuffer(); int createTexture(int target); }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\dsa\DSAARB.java
package com.gtnewhorizons.angelica.glsm.dsa; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.lwjgl.opengl.ARBDirectStateAccess; import org.lwjgl.opengl.GL45; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; public class DSAARB extends DSAUnsupported { @Override public void generateMipmaps(int texture, int target) { ARBDirectStateAccess.glGenerateTextureMipmap(texture); } @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { // Note: DSA glTextureImage2D doesn't exist in ARB_direct_state_access // We need to use glTextureStorage2D + glTextureSubImage2D, or fall back to bind-based approach // For simplicity, use the fallback which binds, uploads, and restores super.textureImage2D(texture, target, level, internalformat, width, height, border, format, type, pixels); } @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { super.textureImage2D(texture, target, level, internalformat, width, height, border, format, type, pixels); } @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { ARBDirectStateAccess.glTextureSubImage2D(texture, level, xoffset, yoffset, width, height, format, type, pixels); } @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { ARBDirectStateAccess.glTextureSubImage2D(texture, level, xoffset, yoffset, width, height, format, type, pixels); } @Override public void texParameteri(int texture, int target, int pname, int param) { if(!GLStateManager.updateTexParameteriCache(target, texture, pname, param)) return; ARBDirectStateAccess.glTextureParameteri(texture, pname, param); } @Override public void texParameterf(int texture, int target, int pname, float param) { if(!GLStateManager.updateTexParameterfCache(target, texture, pname, param)) return; ARBDirectStateAccess.glTextureParameterf(texture, pname, param); } @Override public void texParameteriv(int texture, int target, int pname, IntBuffer params) { ARBDirectStateAccess.glTextureParameter(texture, pname, params); } @Override public void readBuffer(int framebuffer, int buffer) { ARBDirectStateAccess.glNamedFramebufferReadBuffer(framebuffer, buffer); } @Override public void drawBuffers(int framebuffer, IntBuffer buffers) { ARBDirectStateAccess.glNamedFramebufferDrawBuffers(framebuffer, buffers); } @Override public int getTexParameteri(int texture, int target, int pname) { return GLStateManager.getTexParameterOrDefault(texture, pname, () -> ARBDirectStateAccess.glGetTextureParameteri(texture, pname)); } @Override public int getTexLevelParameteri(int texture, int level, int pname) { return ARBDirectStateAccess.glGetTextureLevelParameteri(texture, level, pname); } @Override public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) { ARBDirectStateAccess.glCopyTextureSubImage2D(destTexture, i, i1, i2, i3, i4, width, height); } @Override public void bindTextureToUnit(int unit, int texture) { if(GLStateManager.getBoundTextureForServerState(unit) == texture) return; if (texture == 0) { super.bindTextureToUnit(unit, texture); } else { ARBDirectStateAccess.glBindTextureUnit(unit, texture); GLStateManager.getTextures().getTextureUnitBindings(unit).setBinding(texture); } } @Override public int bufferStorage(int target, FloatBuffer data, int usage) { final int buffer = GL45.glCreateBuffers(); GL45.glNamedBufferData(buffer, data, usage); return buffer; } @Override public void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) { ARBDirectStateAccess.glBlitNamedFramebuffer(source, dest, offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter); } @Override public void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels) { ARBDirectStateAccess.glNamedFramebufferTexture(fb, attachment, texture, levels); } @Override public int createFramebuffer() { return ARBDirectStateAccess.glCreateFramebuffers(); } @Override public int createTexture(int target) { return ARBDirectStateAccess.glCreateTextures(target); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\dsa\DSACore.java
package com.gtnewhorizons.angelica.glsm.dsa; public class DSACore extends DSAARB { }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\dsa\DSAUnsupported.java
package com.gtnewhorizons.angelica.glsm.dsa; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.minecraft.client.renderer.OpenGlHelper; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; public class DSAUnsupported implements DSAAccess { @Override public void generateMipmaps(int texture, int target) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GL30.glGenerateMipmap(target); } @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer pixels) { // Get what cache thinks is bound - we'll restore to this to keep cache/GL in sync final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); GL11.glBindTexture(target, cachedBinding); // Restore to cache value } @Override public void textureImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, IntBuffer pixels) { final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); GL11.glBindTexture(target, cachedBinding); } @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); GL11.glBindTexture(target, cachedBinding); } @Override public void textureSubImage2D(int texture, int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, IntBuffer pixels) { final int cachedBinding = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(target, texture); GL11.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); GL11.glBindTexture(target, cachedBinding); } @Override public void texParameteri(int texture, int target, int pname, int param) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GLStateManager.glTexParameteri(target, pname, param); } @Override public void texParameterf(int texture, int target, int pname, float param) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GLStateManager.glTexParameterf(target, pname, param); } @Override public void texParameteriv(int texture, int target, int pname, IntBuffer params) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); GLStateManager.glTexParameter(target, pname, params); } @Override public void readBuffer(int framebuffer, int buffer) { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer); GL11.glReadBuffer(buffer); } @Override public void drawBuffers(int framebuffer, IntBuffer buffers) { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer); GL20.glDrawBuffers(buffers); } @Override public int getTexParameteri(int texture, int target, int pname) { GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); return GLStateManager.glGetTexParameteri(target, pname); } @Override public int getTexLevelParameteri(int texture, int level, int pname) { final int previous = GLStateManager.getBoundTextureForServerState(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture); final int result = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, pname); GL11.glBindTexture(GL11.GL_TEXTURE_2D, previous); return result; } @Override public void copyTexSubImage2D(int destTexture, int target, int i, int i1, int i2, int i3, int i4, int width, int height) { final int previous = GLStateManager.getBoundTextureForServerState(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, destTexture); GL11.glCopyTexSubImage2D(target, i, i1, i2, i3, i4, width, height); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous); } @Override public void bindTextureToUnit(int unit, int texture) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); } @Override public int bufferStorage(int target, FloatBuffer data, int usage) { final int buffer = GL15.glGenBuffers(); GL15.glBindBuffer(target, buffer); RenderSystem.bufferData(target, data, usage); GL15.glBindBuffer(target, 0); return buffer; } @Override public void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, source); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_DRAW_FRAMEBUFFER, dest); GL30.glBlitFramebuffer(offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter); } @Override public void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels) { OpenGlHelper.func_153171_g/*glBindFramebuffer*/(fbtarget, fb); GL30.glFramebufferTexture2D(fbtarget, attachment, target, texture, levels); } @Override public int createFramebuffer() { final int framebuffer = OpenGlHelper.func_153165_e/*glGenFramebuffers*/(); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, framebuffer); return framebuffer; } @Override public int createTexture(int target) { final int texture = GL11.glGenTextures(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture); return texture; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\AccumulatedDraw.java
package com.gtnewhorizons.angelica.glsm.recording; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; import org.joml.Matrix4f; import java.util.List; /** * Represents an accumulated draw call during display list compilation. * Matrix-as-Data Architecture: Stores untransformed vertices + captured matrix. * The matrix will be applied at runtime, not baked into vertices. */ public class AccumulatedDraw { public final List<ModelQuadViewMutable> quads; public final Matrix4f transform; public final CapturingTessellator.Flags flags; public final int commandIndex; // Position in command list for state tracking public final int matrixGeneration; // For batching: same generation = same transform context public final int stateGeneration; // Same value = no state commands between draws, can merge /** * Last vertex restoration data for immediate mode draws. * Null for tessellator draws (no restoration needed). */ public final RestoreData restoreData; /** * Holds last vertex attribute values for GL state restoration after VBO draw. * Used to sync GLSM cache with actual GL state after VBO rendering. */ @Desugar public record RestoreData( float lastColorR, float lastColorG, float lastColorB, float lastColorA, float lastNormalX, float lastNormalY, float lastNormalZ, float lastTexCoordS, float lastTexCoordT) {} public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) { this(quads, transform, flags, commandIndex, matrixGeneration, 0, null); } public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) { this(quads, transform, flags, commandIndex, matrixGeneration, stateGeneration, null); } public AccumulatedDraw(List<ModelQuadViewMutable> quads, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration, RestoreData restoreData) { // Deep copy quads - pooled quads are reused after callback this.quads = ModelQuadUtil.deepCopyQuads(quads); this.transform = new Matrix4f(transform); // Snapshot for runtime application this.flags = flags; this.commandIndex = commandIndex; this.matrixGeneration = matrixGeneration; this.stateGeneration = stateGeneration; this.restoreData = restoreData; } @Override public String toString() { return String.format("AccumulatedDraw[quads=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, flags=C%dT%dL%dN%d, restore=%s]", quads.size(), commandIndex, matrixGeneration, stateGeneration, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0, restoreData != null ? "yes" : "no"); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\AccumulatedLineDraw.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import org.joml.Matrix4f; import java.util.ArrayList; import java.util.List; /** * Represents an accumulated line draw call during display list compilation. * Similar to AccumulatedDraw but for line primitives. * Stores untransformed line vertices + captured matrix. */ public class AccumulatedLineDraw { public final List<ImmediateModeRecorder.LineVertex> lines; public final Matrix4f transform; public final CapturingTessellator.Flags flags; public final int commandIndex; // Position in command list for state tracking public final int stateGeneration; // Same value = no state commands between draws, can merge public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex) { this(lines, transform, flags, commandIndex, 0); } public AccumulatedLineDraw(List<ImmediateModeRecorder.LineVertex> lines, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int stateGeneration) { // Copy lines - the source list may be cleared this.lines = new ArrayList<>(lines); this.transform = new Matrix4f(transform); // Snapshot for runtime application this.flags = flags; this.commandIndex = commandIndex; this.stateGeneration = stateGeneration; } @Override public String toString() { return String.format("AccumulatedLineDraw[lines=%d, cmdIdx=%d, flags=C%dT%dL%dN%d]", lines.size() / 2, commandIndex, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\AccumulatedPrimitiveDraw.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.line.ModelLine; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.primitive.ModelPrimitiveView; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.tri.ModelTriangle; import org.joml.Matrix4f; import java.util.ArrayList; import java.util.List; /** * Represents an accumulated primitive draw call during display list compilation. * Stores primitives (lines, triangles) from tessellator callback with their transform. * <p> * Unlike AccumulatedLineDraw which stores ImmediateModeRecorder.LineVertex (16-byte: pos+color), * this stores ModelPrimitiveView (32-byte: pos+color+tex+light+normal) from the tessellator. */ public class AccumulatedPrimitiveDraw { public final List<ModelPrimitiveView> primitives; public final Matrix4f transform; public final CapturingTessellator.Flags flags; public final int commandIndex; public final int matrixGeneration; // For batching: same generation = same transform context public final int stateGeneration; // Same value = no state commands between draws, can merge public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration) { this(primitives, transform, flags, commandIndex, matrixGeneration, 0); } public AccumulatedPrimitiveDraw(List<ModelPrimitiveView> primitives, Matrix4f transform, CapturingTessellator.Flags flags, int commandIndex, int matrixGeneration, int stateGeneration) { // Deep copy primitives - pooled primitives are reused after callback this.primitives = deepCopyPrimitives(primitives); this.transform = new Matrix4f(transform); this.flags = flags; this.commandIndex = commandIndex; this.matrixGeneration = matrixGeneration; this.stateGeneration = stateGeneration; } /** * Creates deep copies of all primitives in the list. * Required because CapturingTessellator pools and reuses primitive objects. */ private static List<ModelPrimitiveView> deepCopyPrimitives(List<ModelPrimitiveView> source) { final int size = source.size(); final List<ModelPrimitiveView> copies = new ArrayList<>(size); for (int i = 0; i < size; i++) { final ModelPrimitiveView prim = source.get(i); if (prim instanceof ModelLine ml) { copies.add(new ModelLine().copyFrom(ml)); } else if (prim instanceof ModelTriangle mt) { copies.add(new ModelTriangle().copyFrom(mt)); } } return copies; } @Override public String toString() { return String.format("AccumulatedPrimitiveDraw[primitives=%d, cmdIdx=%d, matrixGen=%d, stateGen=%d, mode=%d, flags=C%dT%dL%dN%d]", primitives.size(), commandIndex, matrixGeneration, stateGeneration, flags.drawMode, flags.hasColor ? 1 : 0, flags.hasTexture ? 1 : 0, flags.hasBrightness ? 1 : 0, flags.hasNormals ? 1 : 0); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\CommandBuffer.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import org.joml.Matrix4f; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; public final class CommandBuffer { private static final int DEFAULT_CAPACITY = 4096; // Guess at typical display list size // Flag bits for DRAW_RANGE_RESTORE command public static final int FLAG_HAS_BRIGHTNESS = 1 << 0; public static final int FLAG_HAS_COLOR = 1 << 1; public static final int FLAG_HAS_NORMALS = 1 << 2; public static final int FLAG_HAS_TEXTURE = 1 << 3; private ByteBuffer buffer; private long basePointer; private long writePointer; private final List<Object> complexObjects = new ArrayList<>(); public CommandBuffer() { this(DEFAULT_CAPACITY); } public CommandBuffer(int initialCapacity) { this.buffer = memAlloc(initialCapacity); this.basePointer = memAddress(buffer); this.writePointer = basePointer; } // === Low-level write operations === private void writeInt(int value) { memPutInt(writePointer, value); writePointer += 4; } private void writeFloat(float value) { memPutFloat(writePointer, value); writePointer += 4; } private void writeDouble(double value) { memPutDouble(writePointer, value); writePointer += 8; } private void ensureCapacity(int needed) { final int size = size(); final int remaining = buffer.capacity() - size; if (remaining < needed) { final int newCapacity = Math.max(buffer.capacity() * 2, buffer.capacity() + needed); buffer = memRealloc(buffer, newCapacity); basePointer = memAddress(buffer); writePointer = basePointer + size; } } // === Single int commands === public void writeEnable(int cap) { ensureCapacity(8); writeInt(GLCommand.ENABLE); writeInt(cap); } public void writeDisable(int cap) { ensureCapacity(8); writeInt(GLCommand.DISABLE); writeInt(cap); } public void writeClear(int mask) { ensureCapacity(8); writeInt(GLCommand.CLEAR); writeInt(mask); } public void writeClearStencil(int s) { ensureCapacity(8); writeInt(GLCommand.CLEAR_STENCIL); writeInt(s); } public void writeCullFace(int mode) { ensureCapacity(8); writeInt(GLCommand.CULL_FACE); writeInt(mode); } public void writeDepthFunc(int func) { ensureCapacity(8); writeInt(GLCommand.DEPTH_FUNC); writeInt(func); } public void writeShadeModel(int mode) { ensureCapacity(8); writeInt(GLCommand.SHADE_MODEL); writeInt(mode); } public void writeLogicOp(int opcode) { ensureCapacity(8); writeInt(GLCommand.LOGIC_OP); writeInt(opcode); } public void writeMatrixMode(int mode) { ensureCapacity(8); writeInt(GLCommand.MATRIX_MODE); writeInt(mode); } public void writeActiveTexture(int texture) { ensureCapacity(8); writeInt(GLCommand.ACTIVE_TEXTURE); writeInt(texture); } public void writeUseProgram(int program) { ensureCapacity(8); writeInt(GLCommand.USE_PROGRAM); writeInt(program); } public void writePushAttrib(int mask) { ensureCapacity(8); writeInt(GLCommand.PUSH_ATTRIB); writeInt(mask); } public void writePopAttrib() { ensureCapacity(8); writeInt(GLCommand.POP_ATTRIB); writeInt(0); // unused padding } public void writeLoadIdentity() { ensureCapacity(4); writeInt(GLCommand.LOAD_IDENTITY); } public void writePushMatrix() { ensureCapacity(4); writeInt(GLCommand.PUSH_MATRIX); } public void writePopMatrix() { ensureCapacity(4); writeInt(GLCommand.POP_MATRIX); } public void writeStencilMask(int mask) { ensureCapacity(8); writeInt(GLCommand.STENCIL_MASK); writeInt(mask); } public void writeDepthMask(boolean flag) { ensureCapacity(8); writeInt(GLCommand.DEPTH_MASK); writeInt(flag ? 1 : 0); } public void writeFrontFace(int mode) { ensureCapacity(8); writeInt(GLCommand.FRONT_FACE); writeInt(mode); } // === Two int commands === public void writeBindTexture(int target, int texture) { ensureCapacity(12); writeInt(GLCommand.BIND_TEXTURE); writeInt(target); writeInt(texture); } public void writePolygonMode(int face, int mode) { ensureCapacity(12); writeInt(GLCommand.POLYGON_MODE); writeInt(face); writeInt(mode); } public void writeColorMaterial(int face, int mode) { ensureCapacity(12); writeInt(GLCommand.COLOR_MATERIAL); writeInt(face); writeInt(mode); } public void writeLineStipple(int factor, int pattern) { ensureCapacity(12); writeInt(GLCommand.LINE_STIPPLE); writeInt(factor); writeInt(pattern); } public void writeStencilMaskSeparate(int face, int mask) { ensureCapacity(12); writeInt(GLCommand.STENCIL_MASK_SEPARATE); writeInt(face); writeInt(mask); } public void writeFogi(int pname, int param) { ensureCapacity(12); writeInt(GLCommand.FOGI); writeInt(pname); writeInt(param); } public void writeHint(int target, int mode) { ensureCapacity(12); writeInt(GLCommand.HINT); writeInt(target); writeInt(mode); } // === Three int commands === public void writeStencilFunc(int func, int ref, int mask) { ensureCapacity(16); writeInt(GLCommand.STENCIL_FUNC); writeInt(func); writeInt(ref); writeInt(mask); } public void writeStencilOp(int fail, int zfail, int zpass) { ensureCapacity(16); writeInt(GLCommand.STENCIL_OP); writeInt(fail); writeInt(zfail); writeInt(zpass); } public void writeTexParameteri(int target, int pname, int param) { ensureCapacity(16); writeInt(GLCommand.TEX_PARAMETERI); writeInt(target); writeInt(pname); writeInt(param); } // === Four int commands === public void writeViewport(int x, int y, int width, int height) { ensureCapacity(20); writeInt(GLCommand.VIEWPORT); writeInt(x); writeInt(y); writeInt(width); writeInt(height); } public void writeBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { ensureCapacity(20); writeInt(GLCommand.BLEND_FUNC); writeInt(srcRgb); writeInt(dstRgb); writeInt(srcAlpha); writeInt(dstAlpha); } public void writeColorMask(boolean red, boolean green, boolean blue, boolean alpha) { ensureCapacity(20); writeInt(GLCommand.COLOR_MASK); writeInt(red ? 1 : 0); writeInt(green ? 1 : 0); writeInt(blue ? 1 : 0); writeInt(alpha ? 1 : 0); } public void writeStencilFuncSeparate(int face, int func, int ref, int mask) { ensureCapacity(20); writeInt(GLCommand.STENCIL_FUNC_SEPARATE); writeInt(face); writeInt(func); writeInt(ref); writeInt(mask); } public void writeStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { ensureCapacity(20); writeInt(GLCommand.STENCIL_OP_SEPARATE); writeInt(face); writeInt(sfail); writeInt(dpfail); writeInt(dppass); } // === Float commands === public void writePointSize(float size) { ensureCapacity(8); writeInt(GLCommand.POINT_SIZE); writeFloat(size); } public void writeLineWidth(float width) { ensureCapacity(8); writeInt(GLCommand.LINE_WIDTH); writeFloat(width); } public void writePolygonOffset(float factor, float units) { ensureCapacity(12); writeInt(GLCommand.POLYGON_OFFSET); writeFloat(factor); writeFloat(units); } public void writeColor(float r, float g, float b, float a) { ensureCapacity(20); writeInt(GLCommand.COLOR); writeFloat(r); writeFloat(g); writeFloat(b); writeFloat(a); } public void writeClearColor(float r, float g, float b, float a) { ensureCapacity(20); writeInt(GLCommand.CLEAR_COLOR); writeFloat(r); writeFloat(g); writeFloat(b); writeFloat(a); } public void writeClearDepth(double depth) { ensureCapacity(12); writeInt(GLCommand.CLEAR_DEPTH); writeDouble(depth); } public void writeBlendColor(float r, float g, float b, float a) { ensureCapacity(20); writeInt(GLCommand.BLEND_COLOR); writeFloat(r); writeFloat(g); writeFloat(b); writeFloat(a); } // === Mixed int+float commands === public void writeAlphaFunc(int func, float ref) { ensureCapacity(12); writeInt(GLCommand.ALPHA_FUNC); writeInt(func); writeFloat(ref); } public void writeFogf(int pname, float param) { ensureCapacity(12); writeInt(GLCommand.FOGF); writeInt(pname); writeFloat(param); } public void writeLightf(int light, int pname, float param) { ensureCapacity(16); writeInt(GLCommand.LIGHTF); writeInt(light); writeInt(pname); writeFloat(param); } public void writeLightModelf(int pname, float param) { ensureCapacity(12); writeInt(GLCommand.LIGHT_MODELF); writeInt(pname); writeFloat(param); } public void writeLighti(int light, int pname, int param) { ensureCapacity(16); writeInt(GLCommand.LIGHTI); writeInt(light); writeInt(pname); writeInt(param); } public void writeLightModeli(int pname, int param) { ensureCapacity(12); writeInt(GLCommand.LIGHT_MODELI); writeInt(pname); writeInt(param); } public void writeMaterialf(int face, int pname, float param) { ensureCapacity(16); writeInt(GLCommand.MATERIALF); writeInt(face); writeInt(pname); writeFloat(param); } public void writeTexParameterf(int target, int pname, float param) { ensureCapacity(16); writeInt(GLCommand.TEX_PARAMETERF); writeInt(target); writeInt(pname); writeFloat(param); } // === Double commands === public void writeTranslate(double x, double y, double z) { ensureCapacity(28); writeInt(GLCommand.TRANSLATE); writeDouble(x); writeDouble(y); writeDouble(z); } public void writeRotate(double angle, double x, double y, double z) { ensureCapacity(36); writeInt(GLCommand.ROTATE); writeDouble(angle); writeDouble(x); writeDouble(y); writeDouble(z); } public void writeScale(double x, double y, double z) { ensureCapacity(28); writeInt(GLCommand.SCALE); writeDouble(x); writeDouble(y); writeDouble(z); } public void writeOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { ensureCapacity(52); writeInt(GLCommand.ORTHO); writeDouble(left); writeDouble(right); writeDouble(bottom); writeDouble(top); writeDouble(zNear); writeDouble(zFar); } public void writeFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { ensureCapacity(52); writeInt(GLCommand.FRUSTUM); writeDouble(left); writeDouble(right); writeDouble(bottom); writeDouble(top); writeDouble(zNear); writeDouble(zFar); } // === Matrix commands === public void writeMultMatrix(Matrix4f matrix) { ensureCapacity(68); writeInt(GLCommand.MULT_MATRIX); writeMatrix4f(matrix); } public void writeLoadMatrix(Matrix4f matrix) { ensureCapacity(68); writeInt(GLCommand.LOAD_MATRIX); writeMatrix4f(matrix); } /** * Write a Matrix4f to the buffer in column-major order (OpenGL convention). * Uses accessor methods instead of getToAddress() to avoid JOML MemUtil issues. */ private void writeMatrix4f(Matrix4f m) { // Column 0 writeFloat(m.m00()); writeFloat(m.m01()); writeFloat(m.m02()); writeFloat(m.m03()); // Column 1 writeFloat(m.m10()); writeFloat(m.m11()); writeFloat(m.m12()); writeFloat(m.m13()); // Column 2 writeFloat(m.m20()); writeFloat(m.m21()); writeFloat(m.m22()); writeFloat(m.m23()); // Column 3 writeFloat(m.m30()); writeFloat(m.m31()); writeFloat(m.m32()); writeFloat(m.m33()); } // === Buffer commands (inline 4 floats) === public void writeFog(int pname, FloatBuffer params) { final int count = Math.min(params.remaining(), 4); ensureCapacity(12 + count * 4); writeInt(GLCommand.FOG); writeInt(pname); writeInt(count); final int pos = params.position(); for (int i = 0; i < count; i++) { writeFloat(params.get(pos + i)); } } public void writeLight(int light, int pname, FloatBuffer params) { final int count = Math.min(params.remaining(), 4); ensureCapacity(16 + count * 4); writeInt(GLCommand.LIGHT); writeInt(light); writeInt(pname); writeInt(count); final int pos = params.position(); for (int i = 0; i < count; i++) { writeFloat(params.get(pos + i)); } } public void writeLightModel(int pname, FloatBuffer params) { final int count = Math.min(params.remaining(), 4); ensureCapacity(12 + count * 4); writeInt(GLCommand.LIGHT_MODEL); writeInt(pname); writeInt(count); final int pos = params.position(); for (int i = 0; i < count; i++) { writeFloat(params.get(pos + i)); } } public void writeMaterial(int face, int pname, FloatBuffer params) { final int count = Math.min(params.remaining(), 4); ensureCapacity(16 + count * 4); writeInt(GLCommand.MATERIAL); writeInt(face); writeInt(pname); writeInt(count); final int pos = params.position(); for (int i = 0; i < count; i++) { writeFloat(params.get(pos + i)); } } // === Draw commands === public void writeDrawRange(int vboIndex, int startVertex, int vertexCount, boolean hasBrightness) { ensureCapacity(20); writeInt(GLCommand.DRAW_RANGE); writeInt(vboIndex); writeInt(startVertex); writeInt(vertexCount); writeInt(hasBrightness ? 1 : 0); } /** * Write a DRAW_RANGE_RESTORE command that draws a VBO range and restores GL current state after. * Used for immediate mode VBOs to restore GL_CURRENT_COLOR, GL_CURRENT_NORMAL, GL_CURRENT_TEXTURE_COORDS. * * @param vboIndex Index into ownedVbos array * @param startVertex First vertex to draw * @param vertexCount Number of vertices to draw * @param hasBrightness True if VBO has brightness/lightmap data * @param hasColor True if color should be restored after draw * @param hasNormals True if normal should be restored after draw * @param hasTexture True if texcoord should be restored after draw * @param lastColorR Last vertex's red color component * @param lastColorG Last vertex's green color component * @param lastColorB Last vertex's blue color component * @param lastColorA Last vertex's alpha color component * @param lastNormalX Last vertex's normal X * @param lastNormalY Last vertex's normal Y * @param lastNormalZ Last vertex's normal Z * @param lastTexS Last vertex's texture S coordinate * @param lastTexT Last vertex's texture T coordinate */ public void writeDrawRangeRestore( int vboIndex, int startVertex, int vertexCount, boolean hasBrightness, boolean hasColor, boolean hasNormals, boolean hasTexture, float lastColorR, float lastColorG, float lastColorB, float lastColorA, float lastNormalX, float lastNormalY, float lastNormalZ, float lastTexS, float lastTexT ) { ensureCapacity(56); writeInt(GLCommand.DRAW_RANGE_RESTORE); writeInt(vboIndex); writeInt(startVertex); writeInt(vertexCount); int flags = (hasBrightness ? FLAG_HAS_BRIGHTNESS : 0) | (hasColor ? FLAG_HAS_COLOR : 0) | (hasNormals ? FLAG_HAS_NORMALS : 0) | (hasTexture ? FLAG_HAS_TEXTURE : 0); writeInt(flags); // Last color (4 floats = 16 bytes) writeFloat(lastColorR); writeFloat(lastColorG); writeFloat(lastColorB); writeFloat(lastColorA); // Last normal (3 floats = 12 bytes) writeFloat(lastNormalX); writeFloat(lastNormalY); writeFloat(lastNormalZ); // Last texcoord (2 floats = 8 bytes) writeFloat(lastTexS); writeFloat(lastTexT); } public void writeCallList(int listId) { ensureCapacity(8); writeInt(GLCommand.CALL_LIST); writeInt(listId); } public void writeDrawBuffer(int mode) { ensureCapacity(8); writeInt(GLCommand.DRAW_BUFFER); writeInt(mode); } private static final int MAX_DRAW_BUFFERS = 8; // cmd (4) + count (4) + buffers (4 * MAX_DRAW_BUFFERS) private static final int DRAW_BUFFERS_SIZE = 4 + 4 + 4 * MAX_DRAW_BUFFERS; public void writeDrawBuffers(int count, int buffer) { ensureCapacity(DRAW_BUFFERS_SIZE); writeInt(GLCommand.DRAW_BUFFERS); writeInt(count); writeInt(buffer); for (int i = 1; i < MAX_DRAW_BUFFERS; i++) { writeInt(0); } } public void writeDrawBuffers(int count, IntBuffer bufs) { ensureCapacity(DRAW_BUFFERS_SIZE); writeInt(GLCommand.DRAW_BUFFERS); writeInt(count); final int pos = bufs.position(); for (int i = 0; i < count && i < MAX_DRAW_BUFFERS; i++) { writeInt(bufs.get(pos + i)); } for (int i = count; i < MAX_DRAW_BUFFERS; i++) { writeInt(0); } } // === Complex object reference === public void writeComplexRef(DisplayListCommand cmd) { ensureCapacity(8); final int index = complexObjects.size(); complexObjects.add(cmd); writeInt(GLCommand.COMPLEX_REF); writeInt(index); } // === Reading methods for optimization pass === private long readPointer = 0; /** * Reset read position to the beginning of the buffer. */ public void resetRead() { readPointer = basePointer; } /** * Check if there's more data to read. */ public boolean hasRemaining() { return readPointer < writePointer; } /** * Read an int from the current position. */ public int readInt() { final int value = memGetInt(readPointer); readPointer += 4; return value; } /** * Read a float from the current position. */ public float readFloat() { final float value = memGetFloat(readPointer); readPointer += 4; return value; } /** * Read a double from the current position. */ public double readDouble() { final double value = memGetDouble(readPointer); readPointer += 8; return value; } /** * Read a Matrix4f from the current position (16 floats in column-major order). */ public Matrix4f readMatrix4f(Matrix4f dest) { dest.m00(readFloat()); dest.m01(readFloat()); dest.m02(readFloat()); dest.m03(readFloat()); dest.m10(readFloat()); dest.m11(readFloat()); dest.m12(readFloat()); dest.m13(readFloat()); dest.m20(readFloat()); dest.m21(readFloat()); dest.m22(readFloat()); dest.m23(readFloat()); dest.m30(readFloat()); dest.m31(readFloat()); dest.m32(readFloat()); dest.m33(readFloat()); return dest; } // === Lifecycle === public int size() { return (int) (writePointer - basePointer); } public long address() { return basePointer; } public ByteBuffer toBuffer() { buffer.limit(size()); buffer.position(0); return buffer; } public Object[] getComplexObjects() { return complexObjects.toArray(); } public Object getComplexObject(int index) { return complexObjects.get(index); } public boolean isEmpty() { return size() == 0 && complexObjects.isEmpty(); } /** * Clear the buffer for reuse. Does NOT free memory. */ public void clear() { writePointer = basePointer; complexObjects.clear(); } /** * Free the underlying buffer. Must be called when done. */ public void free() { if (buffer != null) { memFree(buffer); buffer = null; basePointer = 0; writePointer = 0; } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\CommandBufferExecutor.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import org.lwjgl.BufferUtils; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; import static com.gtnewhorizons.angelica.glsm.recording.CommandBuffer.*; /** * Executes commands from a CommandBuffer */ public final class CommandBufferExecutor { private CommandBufferExecutor() {} // Static reusable buffer for matrix ops (render thread only, LWJGL2/3 compatible) private static final FloatBuffer MATRIX_BUFFER = BufferUtils.createFloatBuffer(16); // Static reusable buffer for fog/light/material params private static final FloatBuffer PARAMS_BUFFER = BufferUtils.createFloatBuffer(4); // Static reusable buffer for draw buffers private static final int MAX_DRAW_BUFFERS = 8; private static final IntBuffer DRAW_BUFFERS_BUFFER = BufferUtils.createIntBuffer(MAX_DRAW_BUFFERS); /** * Execute all commands in the buffer. * * @param buffer The command buffer (position should be at 0, limit at size) * @param complexObjects Array of complex objects (TexImage2DCmd, etc.) * @param ownedVbos Array of VBOs owned by the display list (indexed by DrawRange commands) */ public static void execute(ByteBuffer buffer, Object[] complexObjects, VertexBuffer[] ownedVbos) { long ptr = memAddress(buffer); final long end = ptr + buffer.limit(); while (ptr < end) { final int cmd = memGetInt(ptr); ptr += 4; switch (cmd) { // === Single int commands === case GLCommand.ENABLE -> { GLStateManager.glEnable(memGetInt(ptr)); ptr += 4; } case GLCommand.DISABLE -> { GLStateManager.glDisable(memGetInt(ptr)); ptr += 4; } case GLCommand.CLEAR -> { GLStateManager.glClear(memGetInt(ptr)); ptr += 4; } case GLCommand.CLEAR_STENCIL -> { GLStateManager.glClearStencil(memGetInt(ptr)); ptr += 4; } case GLCommand.CULL_FACE -> { GLStateManager.glCullFace(memGetInt(ptr)); ptr += 4; } case GLCommand.DEPTH_FUNC -> { GLStateManager.glDepthFunc(memGetInt(ptr)); ptr += 4; } case GLCommand.SHADE_MODEL -> { GLStateManager.glShadeModel(memGetInt(ptr)); ptr += 4; } case GLCommand.LOGIC_OP -> { GLStateManager.glLogicOp(memGetInt(ptr)); ptr += 4; } case GLCommand.MATRIX_MODE -> { GLStateManager.glMatrixMode(memGetInt(ptr)); ptr += 4; } case GLCommand.ACTIVE_TEXTURE -> { GLStateManager.glActiveTexture(memGetInt(ptr)); ptr += 4; } case GLCommand.USE_PROGRAM -> { GLStateManager.glUseProgram(memGetInt(ptr)); ptr += 4; } case GLCommand.PUSH_ATTRIB -> { GLStateManager.glPushAttrib(memGetInt(ptr)); ptr += 4; } case GLCommand.POP_ATTRIB -> { GLStateManager.glPopAttrib(); ptr += 4; // Skip unused padding } case GLCommand.LOAD_IDENTITY -> { GLStateManager.glLoadIdentity(); } case GLCommand.PUSH_MATRIX -> { GLStateManager.glPushMatrix(); } case GLCommand.POP_MATRIX -> { GLStateManager.glPopMatrix(); } case GLCommand.STENCIL_MASK -> { GLStateManager.glStencilMask(memGetInt(ptr)); ptr += 4; } case GLCommand.DEPTH_MASK -> { GLStateManager.glDepthMask(memGetInt(ptr) != 0); ptr += 4; } case GLCommand.FRONT_FACE -> { GLStateManager.glFrontFace(memGetInt(ptr)); ptr += 4; } // === Two int commands === case GLCommand.BIND_TEXTURE -> { final int target = memGetInt(ptr); final int texture = memGetInt(ptr + 4); ptr += 8; GLStateManager.glBindTexture(target, texture); } case GLCommand.POLYGON_MODE -> { final int face = memGetInt(ptr); final int mode = memGetInt(ptr + 4); ptr += 8; GLStateManager.glPolygonMode(face, mode); } case GLCommand.COLOR_MATERIAL -> { final int face = memGetInt(ptr); final int mode = memGetInt(ptr + 4); ptr += 8; GLStateManager.glColorMaterial(face, mode); } case GLCommand.LINE_STIPPLE -> { final int factor = memGetInt(ptr); final int pattern = memGetInt(ptr + 4); ptr += 8; GLStateManager.glLineStipple(factor, (short) pattern); } case GLCommand.STENCIL_MASK_SEPARATE -> { final int face = memGetInt(ptr); final int mask = memGetInt(ptr + 4); ptr += 8; GLStateManager.glStencilMaskSeparate(face, mask); } case GLCommand.FOGI -> { final int pname = memGetInt(ptr); final int param = memGetInt(ptr + 4); ptr += 8; GLStateManager.glFogi(pname, param); } case GLCommand.HINT -> { final int target = memGetInt(ptr); final int mode = memGetInt(ptr + 4); ptr += 8; GLStateManager.glHint(target, mode); } // === Three int commands === case GLCommand.STENCIL_FUNC -> { final int func = memGetInt(ptr); final int ref = memGetInt(ptr + 4); final int mask = memGetInt(ptr + 8); ptr += 12; GLStateManager.glStencilFunc(func, ref, mask); } case GLCommand.STENCIL_OP -> { final int fail = memGetInt(ptr); final int zfail = memGetInt(ptr + 4); final int zpass = memGetInt(ptr + 8); ptr += 12; GLStateManager.glStencilOp(fail, zfail, zpass); } case GLCommand.TEX_PARAMETERI -> { final int target = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final int param = memGetInt(ptr + 8); ptr += 12; GLStateManager.glTexParameteri(target, pname, param); } // === Four int commands === case GLCommand.VIEWPORT -> { final int x = memGetInt(ptr); final int y = memGetInt(ptr + 4); final int width = memGetInt(ptr + 8); final int height = memGetInt(ptr + 12); ptr += 16; GLStateManager.glViewport(x, y, width, height); } case GLCommand.BLEND_FUNC -> { final int srcRgb = memGetInt(ptr); final int dstRgb = memGetInt(ptr + 4); final int srcAlpha = memGetInt(ptr + 8); final int dstAlpha = memGetInt(ptr + 12); ptr += 16; if (srcRgb == srcAlpha && dstRgb == dstAlpha) { GLStateManager.glBlendFunc(srcRgb, dstRgb); } else { GLStateManager.tryBlendFuncSeparate(srcRgb, dstRgb, srcAlpha, dstAlpha); } } case GLCommand.COLOR_MASK -> { final boolean r = memGetInt(ptr) != 0; final boolean g = memGetInt(ptr + 4) != 0; final boolean b = memGetInt(ptr + 8) != 0; final boolean a = memGetInt(ptr + 12) != 0; ptr += 16; GLStateManager.glColorMask(r, g, b, a); } case GLCommand.STENCIL_FUNC_SEPARATE -> { final int face = memGetInt(ptr); final int func = memGetInt(ptr + 4); final int ref = memGetInt(ptr + 8); final int mask = memGetInt(ptr + 12); ptr += 16; GLStateManager.glStencilFuncSeparate(face, func, ref, mask); } case GLCommand.STENCIL_OP_SEPARATE -> { final int face = memGetInt(ptr); final int sfail = memGetInt(ptr + 4); final int dpfail = memGetInt(ptr + 8); final int dppass = memGetInt(ptr + 12); ptr += 16; GLStateManager.glStencilOpSeparate(face, sfail, dpfail, dppass); } // === Float commands === case GLCommand.POINT_SIZE -> { GLStateManager.glPointSize(memGetFloat(ptr)); ptr += 4; } case GLCommand.LINE_WIDTH -> { GLStateManager.glLineWidth(memGetFloat(ptr)); ptr += 4; } case GLCommand.POLYGON_OFFSET -> { final float factor = memGetFloat(ptr); final float units = memGetFloat(ptr + 4); ptr += 8; GLStateManager.glPolygonOffset(factor, units); } case GLCommand.COLOR -> { final float r = memGetFloat(ptr); final float g = memGetFloat(ptr + 4); final float b = memGetFloat(ptr + 8); final float a = memGetFloat(ptr + 12); ptr += 16; GLStateManager.glColor4f(r, g, b, a); } case GLCommand.CLEAR_COLOR -> { final float r = memGetFloat(ptr); final float g = memGetFloat(ptr + 4); final float b = memGetFloat(ptr + 8); final float a = memGetFloat(ptr + 12); ptr += 16; GLStateManager.glClearColor(r, g, b, a); } case GLCommand.CLEAR_DEPTH -> { final double depth = memGetDouble(ptr); ptr += 8; GLStateManager.glClearDepth(depth); } case GLCommand.BLEND_COLOR -> { final float r = memGetFloat(ptr); final float g = memGetFloat(ptr + 4); final float b = memGetFloat(ptr + 8); final float a = memGetFloat(ptr + 12); ptr += 16; GLStateManager.glBlendColor(r, g, b, a); } // === Mixed int+float commands === case GLCommand.ALPHA_FUNC -> { final int func = memGetInt(ptr); final float ref = memGetFloat(ptr + 4); ptr += 8; GLStateManager.glAlphaFunc(func, ref); } case GLCommand.FOGF -> { final int pname = memGetInt(ptr); final float param = memGetFloat(ptr + 4); ptr += 8; GLStateManager.glFogf(pname, param); } case GLCommand.LIGHTF -> { final int light = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final float param = memGetFloat(ptr + 8); ptr += 12; GLStateManager.glLightf(light, pname, param); } case GLCommand.LIGHT_MODELF -> { final int pname = memGetInt(ptr); final float param = memGetFloat(ptr + 4); ptr += 8; GLStateManager.glLightModelf(pname, param); } case GLCommand.LIGHTI -> { final int light = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final int param = memGetInt(ptr + 8); ptr += 12; GLStateManager.glLighti(light, pname, param); } case GLCommand.LIGHT_MODELI -> { final int pname = memGetInt(ptr); final int param = memGetInt(ptr + 4); ptr += 8; GLStateManager.glLightModeli(pname, param); } case GLCommand.MATERIALF -> { final int face = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final float param = memGetFloat(ptr + 8); ptr += 12; GLStateManager.glMaterialf(face, pname, param); } case GLCommand.TEX_PARAMETERF -> { final int target = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final float param = memGetFloat(ptr + 8); ptr += 12; GLStateManager.glTexParameterf(target, pname, param); } // === Double commands === case GLCommand.TRANSLATE -> { final double x = memGetDouble(ptr); final double y = memGetDouble(ptr + 8); final double z = memGetDouble(ptr + 16); ptr += 24; GLStateManager.glTranslated(x, y, z); } case GLCommand.ROTATE -> { final double angle = memGetDouble(ptr); final double x = memGetDouble(ptr + 8); final double y = memGetDouble(ptr + 16); final double z = memGetDouble(ptr + 24); ptr += 32; GLStateManager.glRotated(angle, x, y, z); } case GLCommand.SCALE -> { final double x = memGetDouble(ptr); final double y = memGetDouble(ptr + 8); final double z = memGetDouble(ptr + 16); ptr += 24; GLStateManager.glScaled(x, y, z); } case GLCommand.ORTHO -> { final double left = memGetDouble(ptr); final double right = memGetDouble(ptr + 8); final double bottom = memGetDouble(ptr + 16); final double top = memGetDouble(ptr + 24); final double zNear = memGetDouble(ptr + 32); final double zFar = memGetDouble(ptr + 40); ptr += 48; GLStateManager.glOrtho(left, right, bottom, top, zNear, zFar); } case GLCommand.FRUSTUM -> { final double left = memGetDouble(ptr); final double right = memGetDouble(ptr + 8); final double bottom = memGetDouble(ptr + 16); final double top = memGetDouble(ptr + 24); final double zNear = memGetDouble(ptr + 32); final double zFar = memGetDouble(ptr + 40); ptr += 48; GLStateManager.glFrustum(left, right, bottom, top, zNear, zFar); } // === Matrix commands === case GLCommand.MULT_MATRIX -> { // Mode-agnostic: just multiply current matrix MATRIX_BUFFER.clear(); for (int i = 0; i < 16; i++) { MATRIX_BUFFER.put(memGetFloat(ptr)); ptr += 4; } MATRIX_BUFFER.flip(); GLStateManager.glMultMatrix(MATRIX_BUFFER); } case GLCommand.LOAD_MATRIX -> { MATRIX_BUFFER.clear(); for (int i = 0; i < 16; i++) { MATRIX_BUFFER.put(memGetFloat(ptr)); ptr += 4; } MATRIX_BUFFER.flip(); GLStateManager.glLoadMatrix(MATRIX_BUFFER); } // === Buffer commands === case GLCommand.FOG -> { final int pname = memGetInt(ptr); final int count = memGetInt(ptr + 4); ptr += 8; PARAMS_BUFFER.clear(); for (int i = 0; i < count; i++) { PARAMS_BUFFER.put(memGetFloat(ptr)); ptr += 4; } PARAMS_BUFFER.flip(); GLStateManager.glFog(pname, PARAMS_BUFFER); } case GLCommand.LIGHT -> { final int light = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final int count = memGetInt(ptr + 8); ptr += 12; PARAMS_BUFFER.clear(); for (int i = 0; i < count; i++) { PARAMS_BUFFER.put(memGetFloat(ptr)); ptr += 4; } PARAMS_BUFFER.flip(); GLStateManager.glLight(light, pname, PARAMS_BUFFER); } case GLCommand.LIGHT_MODEL -> { final int pname = memGetInt(ptr); final int count = memGetInt(ptr + 4); ptr += 8; PARAMS_BUFFER.clear(); for (int i = 0; i < count; i++) { PARAMS_BUFFER.put(memGetFloat(ptr)); ptr += 4; } PARAMS_BUFFER.flip(); GLStateManager.glLightModel(pname, PARAMS_BUFFER); } case GLCommand.MATERIAL -> { final int face = memGetInt(ptr); final int pname = memGetInt(ptr + 4); final int count = memGetInt(ptr + 8); ptr += 12; PARAMS_BUFFER.clear(); for (int i = 0; i < count; i++) { PARAMS_BUFFER.put(memGetFloat(ptr)); ptr += 4; } PARAMS_BUFFER.flip(); GLStateManager.glMaterial(face, pname, PARAMS_BUFFER); } // === Draw commands === case GLCommand.DRAW_RANGE -> { final int vboIndex = memGetInt(ptr); final int start = memGetInt(ptr + 4); final int count = memGetInt(ptr + 8); final boolean hasBrightness = memGetInt(ptr + 12) != 0; ptr += 16; final VertexBuffer vbo = ownedVbos[vboIndex]; vbo.setupState(); vbo.draw(start, count); vbo.cleanupState(); } case GLCommand.DRAW_RANGE_RESTORE -> { // Draw VBO range then restore GL current state from last vertex attributes final int vboIndex = memGetInt(ptr); final int start = memGetInt(ptr + 4); final int count = memGetInt(ptr + 8); final int flags = memGetInt(ptr + 12); // Draw the VBO final VertexBuffer vbo = ownedVbos[vboIndex]; vbo.setupState(); vbo.draw(start, count); vbo.cleanupState(); // Restore attributes based on flags if ((flags & FLAG_HAS_COLOR) != 0) { final float r = memGetFloat(ptr + 16); final float g = memGetFloat(ptr + 20); final float b = memGetFloat(ptr + 24); final float a = memGetFloat(ptr + 28); GLStateManager.glColor4f(r, g, b, a); } if ((flags & FLAG_HAS_NORMALS) != 0) { final float nx = memGetFloat(ptr + 32); final float ny = memGetFloat(ptr + 36); final float nz = memGetFloat(ptr + 40); GLStateManager.glNormal3f(nx, ny, nz); } if ((flags & FLAG_HAS_TEXTURE) != 0) { final float s = memGetFloat(ptr + 44); final float t = memGetFloat(ptr + 48); GLStateManager.glTexCoord2f(s, t); } ptr += 52; // Skip full command size (56 - 4 for cmd already read) } case GLCommand.CALL_LIST -> { final int listId = memGetInt(ptr); ptr += 4; DisplayListManager.glCallList(listId); } case GLCommand.DRAW_BUFFER -> { GLStateManager.glDrawBuffer(memGetInt(ptr)); ptr += 4; } case GLCommand.DRAW_BUFFERS -> { final int count = memGetInt(ptr); ptr += 4; DRAW_BUFFERS_BUFFER.clear(); for (int i = 0; i < count; i++) { DRAW_BUFFERS_BUFFER.put(memGetInt(ptr + i * 4)); } DRAW_BUFFERS_BUFFER.flip(); ptr += 4 * MAX_DRAW_BUFFERS; GLStateManager.glDrawBuffers(DRAW_BUFFERS_BUFFER); } // === Complex object reference === case GLCommand.COMPLEX_REF -> { final int index = memGetInt(ptr); ptr += 4; ((DisplayListCommand) complexObjects[index]).execute(); } default -> throw new IllegalStateException("Unknown command opcode: " + cmd); } } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\CommandBufferProcessor.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizons.angelica.glsm.DisplayListManager; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.Deque; public final class CommandBufferProcessor { private static final Logger LOGGER = LogManager.getLogger("CommandBufferProcessor"); private static final Matrix4f tempMatrix = new Matrix4f(); private CommandBufferProcessor() {} public static void processCommandForOptimization(int opcode, CommandBuffer raw, BufferTransformOptimizer opt, CommandBuffer out) { switch (opcode) { // === MultMatrix - already collapsed transforms from flushMatrix() === case GLCommand.MULT_MATRIX -> { raw.readMatrix4f(tempMatrix); opt.multMatrix(tempMatrix); // accumulated = accumulated * tempMatrix out.writeMultMatrix(tempMatrix); // Copy to output opt.markLastEmittedAsAccumulated(); // lastEmitted = accumulated (what GL now has) } // === Load commands - flush pending, emit, reset accumulator === case GLCommand.LOAD_IDENTITY -> { opt.emitPendingTransform(out); // Emit any pending transforms first out.writeLoadIdentity(); // Always emit LoadIdentity opt.loadIdentity(); // Reset accumulated to identity opt.resetLastEmitted(); // Reset lastEmitted to identity opt.checkAndClearAbsoluteMatrix(); // Clear the flag if set } case GLCommand.LOAD_MATRIX -> { raw.readMatrix4f(tempMatrix); opt.emitPendingTransform(out); out.writeLoadMatrix(tempMatrix); opt.loadIdentity(); opt.resetLastEmitted(); // Reset lastEmitted to identity opt.markAbsoluteMatrix(); } // === Stack operations - flush/update optimizer state and copy === case GLCommand.PUSH_MATRIX -> { opt.emitPendingTransform(out); opt.push(); // Reset accumulated/lastEmitted to identity after push. opt.loadIdentity(); opt.resetLastEmitted(); out.writePushMatrix(); } case GLCommand.POP_MATRIX -> { opt.pop(); out.writePopMatrix(); } // === Barriers - emit pending transform before copying === case GLCommand.MATRIX_MODE -> { final int mode = raw.readInt(); opt.emitPendingTransform(out); // Pending transforms apply to OLD mode out.writeMatrixMode(mode); opt.loadIdentity(); // Reset accumulated for new mode opt.resetLastEmitted(); // Reset lastEmitted for new mode } case GLCommand.CALL_LIST -> { final int listId = raw.readInt(); opt.emitPendingTransform(out); out.writeCallList(listId); } case GLCommand.PUSH_ATTRIB -> { final int mask = raw.readInt(); if ((mask & GL11.GL_TRANSFORM_BIT) != 0) { opt.emitPendingTransform(out); } out.writePushAttrib(mask); } // === All other commands - just copy === default -> copyCommandData(opcode, raw, out); } } /** * Copy a complete command (opcode already read) from raw to final buffer. */ public static void copyCommand(CommandBuffer raw, CommandBuffer out) { final int opcode = raw.readInt(); copyCommandData(opcode, raw, out); } /** * Copy command data based on opcode (opcode already consumed from raw). */ public static void copyCommandData(int opcode, CommandBuffer raw, CommandBuffer out) { switch (opcode) { // Single int commands case GLCommand.ENABLE -> out.writeEnable(raw.readInt()); case GLCommand.DISABLE -> out.writeDisable(raw.readInt()); case GLCommand.CLEAR -> out.writeClear(raw.readInt()); case GLCommand.CLEAR_STENCIL -> out.writeClearStencil(raw.readInt()); case GLCommand.CULL_FACE -> out.writeCullFace(raw.readInt()); case GLCommand.DEPTH_FUNC -> out.writeDepthFunc(raw.readInt()); case GLCommand.SHADE_MODEL -> out.writeShadeModel(raw.readInt()); case GLCommand.LOGIC_OP -> out.writeLogicOp(raw.readInt()); case GLCommand.MATRIX_MODE -> out.writeMatrixMode(raw.readInt()); case GLCommand.ACTIVE_TEXTURE -> out.writeActiveTexture(raw.readInt()); case GLCommand.USE_PROGRAM -> out.writeUseProgram(raw.readInt()); case GLCommand.PUSH_ATTRIB -> out.writePushAttrib(raw.readInt()); case GLCommand.POP_ATTRIB -> { raw.readInt(); out.writePopAttrib(); } case GLCommand.LOAD_IDENTITY -> out.writeLoadIdentity(); case GLCommand.PUSH_MATRIX -> out.writePushMatrix(); case GLCommand.POP_MATRIX -> out.writePopMatrix(); case GLCommand.STENCIL_MASK -> out.writeStencilMask(raw.readInt()); case GLCommand.DEPTH_MASK -> out.writeDepthMask(raw.readInt() != 0); case GLCommand.FRONT_FACE -> out.writeFrontFace(raw.readInt()); // Two int commands case GLCommand.BIND_TEXTURE -> out.writeBindTexture(raw.readInt(), raw.readInt()); case GLCommand.POLYGON_MODE -> out.writePolygonMode(raw.readInt(), raw.readInt()); case GLCommand.COLOR_MATERIAL -> out.writeColorMaterial(raw.readInt(), raw.readInt()); case GLCommand.LINE_STIPPLE -> out.writeLineStipple(raw.readInt(), raw.readInt()); case GLCommand.STENCIL_MASK_SEPARATE -> out.writeStencilMaskSeparate(raw.readInt(), raw.readInt()); case GLCommand.FOGI -> out.writeFogi(raw.readInt(), raw.readInt()); case GLCommand.HINT -> out.writeHint(raw.readInt(), raw.readInt()); // Three int commands case GLCommand.STENCIL_FUNC -> out.writeStencilFunc(raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.STENCIL_OP -> out.writeStencilOp(raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.TEX_PARAMETERI -> out.writeTexParameteri(raw.readInt(), raw.readInt(), raw.readInt()); // Four int commands case GLCommand.VIEWPORT -> out.writeViewport(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.BLEND_FUNC -> out.writeBlendFunc(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.COLOR_MASK -> out.writeColorMask(raw.readInt() != 0, raw.readInt() != 0, raw.readInt() != 0, raw.readInt() != 0); case GLCommand.STENCIL_FUNC_SEPARATE -> out.writeStencilFuncSeparate(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.STENCIL_OP_SEPARATE -> out.writeStencilOpSeparate(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt()); // Float commands case GLCommand.POINT_SIZE -> out.writePointSize(raw.readFloat()); case GLCommand.LINE_WIDTH -> out.writeLineWidth(raw.readFloat()); case GLCommand.POLYGON_OFFSET -> out.writePolygonOffset(raw.readFloat(), raw.readFloat()); case GLCommand.COLOR -> out.writeColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat()); case GLCommand.CLEAR_COLOR -> out.writeClearColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat()); // Single double commands case GLCommand.CLEAR_DEPTH -> out.writeClearDepth(raw.readDouble()); // Four float commands case GLCommand.BLEND_COLOR -> out.writeBlendColor(raw.readFloat(), raw.readFloat(), raw.readFloat(), raw.readFloat()); // Mixed int+float commands case GLCommand.ALPHA_FUNC -> out.writeAlphaFunc(raw.readInt(), raw.readFloat()); case GLCommand.FOGF -> out.writeFogf(raw.readInt(), raw.readFloat()); case GLCommand.LIGHTF -> out.writeLightf(raw.readInt(), raw.readInt(), raw.readFloat()); case GLCommand.LIGHT_MODELF -> out.writeLightModelf(raw.readInt(), raw.readFloat()); case GLCommand.LIGHTI -> out.writeLighti(raw.readInt(), raw.readInt(), raw.readInt()); case GLCommand.LIGHT_MODELI -> out.writeLightModeli(raw.readInt(), raw.readInt()); case GLCommand.MATERIALF -> out.writeMaterialf(raw.readInt(), raw.readInt(), raw.readFloat()); case GLCommand.TEX_PARAMETERF -> out.writeTexParameterf(raw.readInt(), raw.readInt(), raw.readFloat()); // Double commands case GLCommand.TRANSLATE -> out.writeTranslate(raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.ROTATE -> out.writeRotate(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.SCALE -> out.writeScale(raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.ORTHO -> out.writeOrtho(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); case GLCommand.FRUSTUM -> out.writeFrustum(raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble(), raw.readDouble()); // Matrix commands case GLCommand.MULT_MATRIX -> { out.writeMultMatrix(raw.readMatrix4f(tempMatrix)); } case GLCommand.LOAD_MATRIX -> { out.writeLoadMatrix(raw.readMatrix4f(tempMatrix)); } // FloatBuffer commands (inline 4 floats max) case GLCommand.FOG -> { final int pname = raw.readInt(); final int count = raw.readInt(); final FloatBuffer fb = FloatBuffer.allocate(count); for (int i = 0; i < count; i++) fb.put(raw.readFloat()); fb.flip(); out.writeFog(pname, fb); } case GLCommand.LIGHT -> { final int light = raw.readInt(); final int pname = raw.readInt(); final int count = raw.readInt(); final FloatBuffer fb = FloatBuffer.allocate(count); for (int i = 0; i < count; i++) fb.put(raw.readFloat()); fb.flip(); out.writeLight(light, pname, fb); } case GLCommand.LIGHT_MODEL -> { final int pname = raw.readInt(); final int count = raw.readInt(); final FloatBuffer fb = FloatBuffer.allocate(count); for (int i = 0; i < count; i++) fb.put(raw.readFloat()); fb.flip(); out.writeLightModel(pname, fb); } case GLCommand.MATERIAL -> { final int face = raw.readInt(); final int pname = raw.readInt(); final int count = raw.readInt(); final FloatBuffer fb = FloatBuffer.allocate(count); for (int i = 0; i < count; i++) fb.put(raw.readFloat()); fb.flip(); out.writeMaterial(face, pname, fb); } // Draw/call commands case GLCommand.DRAW_RANGE -> out.writeDrawRange(raw.readInt(), raw.readInt(), raw.readInt(), raw.readInt() != 0); case GLCommand.CALL_LIST -> out.writeCallList(raw.readInt()); // Complex object reference - transfer the object to output buffer case GLCommand.COMPLEX_REF -> { final int index = raw.readInt(); final Object obj = raw.getComplexObject(index); out.writeComplexRef((DisplayListCommand) obj); } default -> LOGGER.warn("[CommandBufferProcessor] Unknown opcode in buffer copy: {}", opcode); } } /** * Lightweight transform optimizer for buffer-to-buffer processing. * Tracks accumulated transform (mode-agnostic) and emits MultMatrix commands when needed. * * <p>This optimizer processes raw transform commands (TRANSLATE, ROTATE, SCALE) and * collapses them into single MultMatrix commands at barriers. It must stay synchronized * with the relativeTransform tracking in DisplayListManager - both systems must reset * at the same barriers (MatrixMode, LoadIdentity, LoadMatrix, Push/Pop).</p> */ public static class BufferTransformOptimizer { private final Matrix4f accumulated = new Matrix4f(); private final Matrix4f lastEmitted = new Matrix4f(); private final Matrix4f delta = new Matrix4f(); // Reused for delta computation private final Deque<Matrix4f> stack = new ArrayDeque<>(); private boolean absoluteMatrixFlag = false; public BufferTransformOptimizer() { accumulated.identity(); lastEmitted.identity(); } public void multMatrix(Matrix4f m) { accumulated.mul(m); } public void loadIdentity() { accumulated.identity(); } public void push() { stack.push(new Matrix4f(accumulated)); } public void pop() { if (!stack.isEmpty()) { accumulated.set(stack.pop()); lastEmitted.set(accumulated); } else { accumulated.identity(); lastEmitted.identity(); } } public boolean isIdentity() { return DisplayListManager.isIdentity(accumulated); } public void markAbsoluteMatrix() { absoluteMatrixFlag = true; } public boolean checkAndClearAbsoluteMatrix() { final boolean was = absoluteMatrixFlag; absoluteMatrixFlag = false; return was; } public void resetLastEmitted() { lastEmitted.identity(); } public void setLastEmitted(Matrix4f m) { lastEmitted.set(m); } public void markLastEmittedAsAccumulated() { lastEmitted.set(accumulated); } public void emitPendingTransform(CommandBuffer out) { if (!accumulated.equals(lastEmitted)) { emitTransformTo(out, accumulated); } } public void emitTransformTo(CommandBuffer out, Matrix4f target) { if (target.equals(lastEmitted)) { return; } if (DisplayListManager.isIdentity(lastEmitted)) { out.writeMultMatrix(target); } else { delta.set(lastEmitted).invert().mul(target); out.writeMultMatrix(delta); } lastEmitted.set(target); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\CommandRecorder.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import org.joml.Matrix4f; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Records GL commands to a CommandBuffer during display list compilation. */ public class CommandRecorder { private final CommandBuffer buffer; private int commandCount; public CommandRecorder() { this.buffer = new CommandBuffer(); this.commandCount = 0; } public CommandBuffer getBuffer() { return buffer; } public int getCommandCount() { return commandCount; } public void free() { buffer.free(); } // ==================== Recording Methods ==================== public void recordEnable(int cap) { buffer.writeEnable(cap); commandCount++; } public void recordDisable(int cap) { buffer.writeDisable(cap); commandCount++; } public void recordClear(int mask) { buffer.writeClear(mask); commandCount++; } public void recordClearColor(float r, float g, float b, float a) { buffer.writeClearColor(r, g, b, a); commandCount++; } public void recordClearDepth(double depth) { buffer.writeClearDepth(depth); commandCount++; } public void recordBlendColor(float r, float g, float b, float a) { buffer.writeBlendColor(r, g, b, a); commandCount++; } public void recordClearStencil(int s) { buffer.writeClearStencil(s); commandCount++; } public void recordColor(float r, float g, float b, float a) { buffer.writeColor(r, g, b, a); commandCount++; } public void recordColorMask(boolean r, boolean g, boolean b, boolean a) { buffer.writeColorMask(r, g, b, a); commandCount++; } public void recordDepthMask(boolean flag) { buffer.writeDepthMask(flag); commandCount++; } public void recordFrontFace(int mode) { buffer.writeFrontFace(mode); commandCount++; } public void recordDepthFunc(int func) { buffer.writeDepthFunc(func); commandCount++; } public void recordBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { buffer.writeBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); commandCount++; } public void recordAlphaFunc(int func, float ref) { buffer.writeAlphaFunc(func, ref); commandCount++; } public void recordCullFace(int mode) { buffer.writeCullFace(mode); commandCount++; } public void recordShadeModel(int mode) { buffer.writeShadeModel(mode); commandCount++; } public void recordBindTexture(int target, int texture) { buffer.writeBindTexture(target, texture); commandCount++; } public void recordTexParameteri(int target, int pname, int param) { buffer.writeTexParameteri(target, pname, param); commandCount++; } public void recordTexParameterf(int target, int pname, float param) { buffer.writeTexParameterf(target, pname, param); commandCount++; } public void recordMatrixMode(int mode) { buffer.writeMatrixMode(mode); commandCount++; } public void recordLoadIdentity() { buffer.writeLoadIdentity(); commandCount++; } public void recordPushMatrix() { buffer.writePushMatrix(); commandCount++; } public void recordPopMatrix() { buffer.writePopMatrix(); commandCount++; } public void recordMultMatrix(Matrix4f matrix) { buffer.writeMultMatrix(matrix); commandCount++; } public void recordLoadMatrix(Matrix4f matrix) { buffer.writeLoadMatrix(matrix); commandCount++; } public void recordOrtho(double left, double right, double bottom, double top, double zNear, double zFar) { buffer.writeOrtho(left, right, bottom, top, zNear, zFar); commandCount++; } public void recordFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { buffer.writeFrustum(left, right, bottom, top, zNear, zFar); commandCount++; } public void recordViewport(int x, int y, int width, int height) { buffer.writeViewport(x, y, width, height); commandCount++; } public void recordPointSize(float size) { buffer.writePointSize(size); commandCount++; } public void recordLineWidth(float width) { buffer.writeLineWidth(width); commandCount++; } public void recordLineStipple(int factor, int pattern) { buffer.writeLineStipple(factor, pattern); commandCount++; } public void recordPolygonOffset(float factor, float units) { buffer.writePolygonOffset(factor, units); commandCount++; } public void recordPolygonMode(int face, int mode) { buffer.writePolygonMode(face, mode); commandCount++; } public void recordColorMaterial(int face, int mode) { buffer.writeColorMaterial(face, mode); commandCount++; } public void recordLogicOp(int opcode) { buffer.writeLogicOp(opcode); commandCount++; } public void recordActiveTexture(int texture) { buffer.writeActiveTexture(texture); commandCount++; } public void recordUseProgram(int program) { buffer.writeUseProgram(program); commandCount++; } public void recordPushAttrib(int mask) { buffer.writePushAttrib(mask); commandCount++; } public void recordPopAttrib() { buffer.writePopAttrib(); commandCount++; } public void recordFogf(int pname, float param) { buffer.writeFogf(pname, param); commandCount++; } public void recordFogi(int pname, int param) { buffer.writeFogi(pname, param); commandCount++; } public void recordHint(int target, int mode) { buffer.writeHint(target, mode); commandCount++; } public void recordFog(int pname, FloatBuffer params) { buffer.writeFog(pname, params); commandCount++; } public void recordLightf(int light, int pname, float param) { buffer.writeLightf(light, pname, param); commandCount++; } public void recordLighti(int light, int pname, int param) { buffer.writeLighti(light, pname, param); commandCount++; } public void recordLight(int light, int pname, FloatBuffer params) { buffer.writeLight(light, pname, params); commandCount++; } public void recordLightModelf(int pname, float param) { buffer.writeLightModelf(pname, param); commandCount++; } public void recordLightModeli(int pname, int param) { buffer.writeLightModeli(pname, param); commandCount++; } public void recordLightModel(int pname, FloatBuffer params) { buffer.writeLightModel(pname, params); commandCount++; } public void recordMaterialf(int face, int pname, float val) { buffer.writeMaterialf(face, pname, val); commandCount++; } public void recordMaterial(int face, int pname, FloatBuffer params) { buffer.writeMaterial(face, pname, params); commandCount++; } public void recordStencilFunc(int func, int ref, int mask) { buffer.writeStencilFunc(func, ref, mask); commandCount++; } public void recordStencilFuncSeparate(int face, int func, int ref, int mask) { buffer.writeStencilFuncSeparate(face, func, ref, mask); commandCount++; } public void recordStencilOp(int fail, int zfail, int zpass) { buffer.writeStencilOp(fail, zfail, zpass); commandCount++; } public void recordStencilOpSeparate(int face, int sfail, int dpfail, int dppass) { buffer.writeStencilOpSeparate(face, sfail, dpfail, dppass); commandCount++; } public void recordStencilMask(int mask) { buffer.writeStencilMask(mask); commandCount++; } public void recordStencilMaskSeparate(int face, int mask) { buffer.writeStencilMaskSeparate(face, mask); commandCount++; } public void recordCallList(int listId) { buffer.writeCallList(listId); commandCount++; } public void recordDrawBuffer(int mode) { buffer.writeDrawBuffer(mode); commandCount++; } public void recordDrawBuffers(int count, int buf) { buffer.writeDrawBuffers(count, buf); commandCount++; } public void recordDrawBuffers(int count, IntBuffer bufs) { buffer.writeDrawBuffers(count, bufs); commandCount++; } public void recordComplexCommand(DisplayListCommand cmd) { buffer.writeComplexRef(cmd); commandCount++; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\CompiledDisplayList.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import java.nio.ByteBuffer; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; /** * Represents a compiled display list. * * <p>Contains commands serialized to a direct ByteBuffer for off-heap storage, * with complex objects (TexImage2DCmd, TexSubImage2DCmd) stored separately. * * <p>The ownedVbos array contains VBOs that are referenced by DrawRange commands. */ public final class CompiledDisplayList { /** * Empty display list singleton. Per OpenGL spec, an empty list is still valid. * This instance does nothing when rendered and is never deleted (shared singleton). */ public static final CompiledDisplayList EMPTY = new CompiledDisplayList(null, null, null); private final ByteBuffer commandBuffer; // Off-heap command storage, must be freed private final Object[] complexObjects; // Complex commands (TexImage2D, etc.) private final VertexBuffer[] ownedVbos; // GPU resources referenced by index public CompiledDisplayList(ByteBuffer commandBuffer, Object[] complexObjects, VertexBuffer[] ownedVbos) { this.commandBuffer = commandBuffer; this.complexObjects = complexObjects; this.ownedVbos = ownedVbos; } /** * Render this display list by executing all commands. */ public void render() { if (commandBuffer != null && commandBuffer.limit() > 0) { CommandBufferExecutor.execute(commandBuffer, complexObjects, ownedVbos); } } /** * Delete all resources held by this display list. */ public void delete() { // Delete complex objects that hold resources if (complexObjects != null) { for (Object obj : complexObjects) { if (obj instanceof DisplayListCommand cmd) { cmd.delete(); } } } // Close VBOs if (ownedVbos != null) { for (VertexBuffer vbo : ownedVbos) { if (vbo != null) { vbo.close(); } } } // Free the command buffer (off-heap memory) if (commandBuffer != null) { memFree(commandBuffer); } } /** * Get the command buffer for debugging/inspection. */ public ByteBuffer getCommandBuffer() { return commandBuffer; } /** * Get complex objects for inlining into another display list (nested lists). */ public Object[] getComplexObjects() { return complexObjects; } /** * Get owned VBOs for inlining into another display list. */ public VertexBuffer[] getOwnedVbos() { return ownedVbos; } // === Test inspection methods === /** * Get counts of each command type in the buffer. * Used for testing to verify optimization results. */ public Int2IntMap getCommandCounts() { final Int2IntMap counts = new Int2IntOpenHashMap(); if (commandBuffer == null || commandBuffer.limit() == 0) { return counts; } long ptr = memAddress(commandBuffer); final long end = ptr + commandBuffer.limit(); while (ptr < end) { final int cmd = memGetInt(ptr); counts.mergeInt(cmd, 1, Integer::sum); ptr += getCommandSize(cmd, ptr); } return counts; } /** * Get the sequence of command opcodes in order. * Used for testing to verify command ordering. */ public IntList getCommandOpcodes() { final IntList opcodes = new IntArrayList(); if (commandBuffer == null || commandBuffer.limit() == 0) { return opcodes; } long ptr = memAddress(commandBuffer); final long end = ptr + commandBuffer.limit(); while (ptr < end) { final int cmd = memGetInt(ptr); opcodes.add(cmd); ptr += getCommandSize(cmd, ptr); } return opcodes; } /** * Get size of a command in bytes (including the opcode). */ private static int getCommandSize(int cmd, long ptr) { return switch (cmd) { // Opcode-only commands (4 bytes) case GLCommand.LOAD_IDENTITY, GLCommand.PUSH_MATRIX, GLCommand.POP_MATRIX -> 4; // Single int commands (8 bytes) case GLCommand.ENABLE, GLCommand.DISABLE, GLCommand.CLEAR, GLCommand.CLEAR_STENCIL, GLCommand.CULL_FACE, GLCommand.DEPTH_FUNC, GLCommand.SHADE_MODEL, GLCommand.LOGIC_OP, GLCommand.MATRIX_MODE, GLCommand.ACTIVE_TEXTURE, GLCommand.USE_PROGRAM, GLCommand.PUSH_ATTRIB, GLCommand.POP_ATTRIB, GLCommand.STENCIL_MASK, GLCommand.DEPTH_MASK, GLCommand.FRONT_FACE, GLCommand.POINT_SIZE, GLCommand.LINE_WIDTH, GLCommand.CALL_LIST, GLCommand.COMPLEX_REF -> 8; // Two int commands (12 bytes) case GLCommand.BIND_TEXTURE, GLCommand.POLYGON_MODE, GLCommand.COLOR_MATERIAL, GLCommand.LINE_STIPPLE, GLCommand.STENCIL_MASK_SEPARATE, GLCommand.FOGI, GLCommand.HINT, GLCommand.POLYGON_OFFSET, GLCommand.ALPHA_FUNC, GLCommand.FOGF, GLCommand.LIGHT_MODELF, GLCommand.LIGHT_MODELI -> 12; // Three int commands (16 bytes) case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI, GLCommand.LIGHTF, GLCommand.LIGHTI, GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16; // Four int commands (20 bytes) case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK, GLCommand.STENCIL_FUNC_SEPARATE, GLCommand.STENCIL_OP_SEPARATE, GLCommand.COLOR, GLCommand.CLEAR_COLOR, GLCommand.BLEND_COLOR, GLCommand.DRAW_RANGE -> 20; // DRAW_RANGE_RESTORE: 56 bytes // [cmd:4][vboIndex:4][start:4][count:4][flags:4][color:16f][normal:12f][texcoord:8f] case GLCommand.DRAW_RANGE_RESTORE -> 56; // DRAW_BUFFER: 8 bytes [cmd:4][mode:4] case GLCommand.DRAW_BUFFER -> 8; // DRAW_BUFFERS: 40 bytes [cmd:4][count:4][bufs:4*8] case GLCommand.DRAW_BUFFERS -> 40; // Double commands case GLCommand.TRANSLATE, GLCommand.SCALE -> 28; // cmd + 3 doubles case GLCommand.CLEAR_DEPTH -> 12; // cmd + 1 double case GLCommand.ROTATE -> 36; // cmd + 4 doubles case GLCommand.ORTHO, GLCommand.FRUSTUM -> 52; // cmd + 6 doubles // Matrix commands case GLCommand.MULT_MATRIX, GLCommand.LOAD_MATRIX -> 68; // cmd + 16 floats // Buffer commands (variable, read count) case GLCommand.FOG, GLCommand.LIGHT_MODEL -> { final int count = memGetInt(ptr + 8); // pname at +4, count at +8 yield 12 + count * 4; } case GLCommand.LIGHT, GLCommand.MATERIAL -> { final int count = memGetInt(ptr + 12); // light/face at +4, pname at +8, count at +12 yield 16 + count * 4; } default -> throw new IllegalStateException("Unknown command: " + cmd); }; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\GLCommand.java
package com.gtnewhorizons.angelica.glsm.recording; /** * Command opcodes for ByteBuffer-based display list serialization. * Each command has a fixed layout described in comments. * All values are 4-byte aligned. */ public final class GLCommand { private GLCommand() {} // === Single int commands (8 bytes: opcode + param) === public static final int ENABLE = 1; // [cmd:4][cap:4] public static final int DISABLE = 2; // [cmd:4][cap:4] public static final int CLEAR = 3; // [cmd:4][mask:4] public static final int CLEAR_STENCIL = 4; // [cmd:4][s:4] public static final int CULL_FACE = 5; // [cmd:4][mode:4] public static final int DEPTH_FUNC = 6; // [cmd:4][func:4] public static final int SHADE_MODEL = 7; // [cmd:4][mode:4] public static final int LOGIC_OP = 8; // [cmd:4][opcode:4] public static final int MATRIX_MODE = 9; // [cmd:4][mode:4] public static final int ACTIVE_TEXTURE = 10; // [cmd:4][texture:4] public static final int USE_PROGRAM = 11; // [cmd:4][program:4] public static final int PUSH_ATTRIB = 12; // [cmd:4][mask:4] public static final int POP_ATTRIB = 13; // [cmd:4][unused:4] public static final int LOAD_IDENTITY = 14; // [cmd:4][matrixMode:4] public static final int PUSH_MATRIX = 15; // [cmd:4][matrixMode:4] public static final int POP_MATRIX = 16; // [cmd:4][matrixMode:4] public static final int STENCIL_MASK = 17; // [cmd:4][mask:4] public static final int DEPTH_MASK = 18; // [cmd:4][flag:4] (0 or 1) public static final int FRONT_FACE = 19; // [cmd:4][mode:4] // === Two int commands (12 bytes) === public static final int BIND_TEXTURE = 20; // [cmd:4][target:4][texture:4] public static final int POLYGON_MODE = 21; // [cmd:4][face:4][mode:4] public static final int COLOR_MATERIAL = 22; // [cmd:4][face:4][mode:4] public static final int LINE_STIPPLE = 23; // [cmd:4][factor:4][pattern:4] public static final int STENCIL_MASK_SEPARATE = 24; // [cmd:4][face:4][mask:4] public static final int FOGI = 25; // [cmd:4][pname:4][param:4] public static final int HINT = 26; // [cmd:4][target:4][mode:4] // === Three int commands (16 bytes) === public static final int STENCIL_FUNC = 30; // [cmd:4][func:4][ref:4][mask:4] public static final int STENCIL_OP = 31; // [cmd:4][fail:4][zfail:4][zpass:4] public static final int TEX_PARAMETERI = 32; // [cmd:4][target:4][pname:4][param:4] // === Four int commands (20 bytes) === public static final int VIEWPORT = 40; // [cmd:4][x:4][y:4][width:4][height:4] public static final int BLEND_FUNC = 41; // [cmd:4][srcRgb:4][dstRgb:4][srcAlpha:4][dstAlpha:4] public static final int COLOR_MASK = 42; // [cmd:4][r:4][g:4][b:4][a:4] (0 or 1 each) public static final int STENCIL_FUNC_SEPARATE = 43; // [cmd:4][face:4][func:4][ref:4][mask:4] public static final int STENCIL_OP_SEPARATE = 44; // [cmd:4][face:4][sfail:4][dpfail:4][dppass:4] // === Float commands === public static final int POINT_SIZE = 50; // [cmd:4][size:4f] public static final int LINE_WIDTH = 51; // [cmd:4][width:4f] public static final int POLYGON_OFFSET = 52; // [cmd:4][factor:4f][units:4f] public static final int NORMAL = 53; // [cmd:4][x:4f][y:4f][z:4f] public static final int COLOR = 54; // [cmd:4][r:4f][g:4f][b:4f][a:4f] public static final int CLEAR_COLOR = 55; // [cmd:4][r:4f][g:4f][b:4f][a:4f] public static final int BLEND_COLOR = 56; // [cmd:4][r:4f][g:4f][b:4f][a:4f] // === Mixed int+float commands === public static final int ALPHA_FUNC = 60; // [cmd:4][func:4][ref:4f] public static final int FOGF = 61; // [cmd:4][pname:4][param:4f] public static final int LIGHTF = 62; // [cmd:4][light:4][pname:4][param:4f] public static final int LIGHT_MODELF = 63; // [cmd:4][pname:4][param:4f] public static final int LIGHTI = 64; // [cmd:4][light:4][pname:4][param:4] public static final int LIGHT_MODELI = 65; // [cmd:4][pname:4][param:4] public static final int MATERIALF = 66; // [cmd:4][face:4][pname:4][param:4f] public static final int TEX_PARAMETERF = 67; // [cmd:4][target:4][pname:4][param:4f] // === Double commands === public static final int TRANSLATE = 70; // [cmd:4][mode:4][x:8d][y:8d][z:8d] = 32 bytes public static final int ROTATE = 71; // [cmd:4][mode:4][angle:8d][x:8d][y:8d][z:8d] = 40 bytes public static final int SCALE = 72; // [cmd:4][mode:4][x:8d][y:8d][z:8d] = 32 bytes public static final int ORTHO = 73; // [cmd:4][left:8d][right:8d][bottom:8d][top:8d][zNear:8d][zFar:8d] = 52 bytes public static final int FRUSTUM = 74; // [cmd:4][left:8d][right:8d][bottom:8d][top:8d][zNear:8d][zFar:8d] = 52 bytes public static final int CLEAR_DEPTH = 75; // [cmd:4][depth:8d] = 12 bytes // === Matrix commands (72 bytes) === public static final int MULT_MATRIX = 80; // [cmd:4][mode:4][m00-m33:64f] = 72 bytes public static final int LOAD_MATRIX = 81; // [cmd:4][mode:4][m00-m33:64f] = 72 bytes // === Buffer commands (inline 4 floats max) === public static final int FOG = 90; // [cmd:4][pname:4][count:4][params:16f] = 28 bytes public static final int LIGHT = 91; // [cmd:4][light:4][pname:4][count:4][params:16f] = 32 bytes public static final int LIGHT_MODEL = 92; // [cmd:4][pname:4][count:4][params:16f] = 28 bytes public static final int MATERIAL = 93; // [cmd:4][face:4][pname:4][count:4][params:16f] = 32 bytes // === Draw commands === public static final int DRAW_RANGE = 100; // [cmd:4][vboIndex:4][start:4][count:4][hasBrightness:4] = 20 bytes public static final int CALL_LIST = 101; // [cmd:4][listId:4] = 8 bytes public static final int DRAW_BUFFER = 102; // [cmd:4][mode:4] = 8 bytes public static final int DRAW_BUFFERS = 103; // [cmd:4][count:4][bufs:4*8] = 40 bytes (up to 8 buffers) /** * Draw VBO range with attribute restoration after draw. * Used for immediate mode VBOs to restore GL current state (color, normal, texcoord). */ public static final int DRAW_RANGE_RESTORE = 104; // [cmd:4][vboIndex:4][start:4][count:4][flags:4] // [lastColor:16f][lastNormal:12f][lastTexCoord:8f] = 56 bytes // === Complex object reference === public static final int COMPLEX_REF = 255; // [cmd:4][index:4] = 8 bytes /** * Get a human-readable name for an opcode (for debugging). */ public static String getName(int opcode) { return switch (opcode) { case ENABLE -> "ENABLE"; case DISABLE -> "DISABLE"; case CLEAR -> "CLEAR"; case CLEAR_STENCIL -> "CLEAR_STENCIL"; case CULL_FACE -> "CULL_FACE"; case DEPTH_FUNC -> "DEPTH_FUNC"; case SHADE_MODEL -> "SHADE_MODEL"; case LOGIC_OP -> "LOGIC_OP"; case MATRIX_MODE -> "MATRIX_MODE"; case ACTIVE_TEXTURE -> "ACTIVE_TEXTURE"; case USE_PROGRAM -> "USE_PROGRAM"; case PUSH_ATTRIB -> "PUSH_ATTRIB"; case POP_ATTRIB -> "POP_ATTRIB"; case LOAD_IDENTITY -> "LOAD_IDENTITY"; case PUSH_MATRIX -> "PUSH_MATRIX"; case POP_MATRIX -> "POP_MATRIX"; case STENCIL_MASK -> "STENCIL_MASK"; case DEPTH_MASK -> "DEPTH_MASK"; case FRONT_FACE -> "FRONT_FACE"; case BIND_TEXTURE -> "BIND_TEXTURE"; case POLYGON_MODE -> "POLYGON_MODE"; case COLOR_MATERIAL -> "COLOR_MATERIAL"; case LINE_STIPPLE -> "LINE_STIPPLE"; case STENCIL_MASK_SEPARATE -> "STENCIL_MASK_SEPARATE"; case FOGI -> "FOGI"; case HINT -> "HINT"; case STENCIL_FUNC -> "STENCIL_FUNC"; case STENCIL_OP -> "STENCIL_OP"; case TEX_PARAMETERI -> "TEX_PARAMETERI"; case VIEWPORT -> "VIEWPORT"; case BLEND_FUNC -> "BLEND_FUNC"; case COLOR_MASK -> "COLOR_MASK"; case STENCIL_FUNC_SEPARATE -> "STENCIL_FUNC_SEPARATE"; case STENCIL_OP_SEPARATE -> "STENCIL_OP_SEPARATE"; case POINT_SIZE -> "POINT_SIZE"; case LINE_WIDTH -> "LINE_WIDTH"; case POLYGON_OFFSET -> "POLYGON_OFFSET"; case COLOR -> "COLOR"; case CLEAR_COLOR -> "CLEAR_COLOR"; case BLEND_COLOR -> "BLEND_COLOR"; case ALPHA_FUNC -> "ALPHA_FUNC"; case FOGF -> "FOGF"; case LIGHTF -> "LIGHTF"; case LIGHT_MODELF -> "LIGHT_MODELF"; case LIGHTI -> "LIGHTI"; case LIGHT_MODELI -> "LIGHT_MODELI"; case MATERIALF -> "MATERIALF"; case TEX_PARAMETERF -> "TEX_PARAMETERF"; case TRANSLATE -> "TRANSLATE"; case ROTATE -> "ROTATE"; case SCALE -> "SCALE"; case ORTHO -> "ORTHO"; case FRUSTUM -> "FRUSTUM"; case CLEAR_DEPTH -> "CLEAR_DEPTH"; case MULT_MATRIX -> "MULT_MATRIX"; case LOAD_MATRIX -> "LOAD_MATRIX"; case FOG -> "FOG"; case LIGHT -> "LIGHT"; case LIGHT_MODEL -> "LIGHT_MODEL"; case MATERIAL -> "MATERIAL"; case DRAW_RANGE -> "DRAW_RANGE"; case CALL_LIST -> "CALL_LIST"; case DRAW_BUFFER -> "DRAW_BUFFER"; case DRAW_BUFFERS -> "DRAW_BUFFERS"; case DRAW_RANGE_RESTORE -> "DRAW_RANGE_RESTORE"; case COMPLEX_REF -> "COMPLEX_REF"; default -> "UNKNOWN(" + opcode + ")"; }; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\ImmediateModeRecorder.java
package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.NormI8; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuad; import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadViewMutable; import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.List; /** * Records immediate mode GL calls (glBegin/glEnd/glVertex) during display list compilation. * Converts immediate mode geometry to ModelQuad format for VBO compilation. * * <p>Tracks current immediate mode state: * <ul> * <li>TexCoord: Set by glTexCoord* calls</li> * <li>Normal: Set by glNormal* calls</li> * <li>Color: Read from GLStateManager.getColor() at vertex emission time</li> * </ul> * * <p>Supported primitive types: * <ul> * <li>GL_QUADS: 4 vertices per quad (native support)</li> * <li>GL_TRIANGLES: 3 vertices per triangle (converted to degenerate quad)</li> * <li>GL_TRIANGLE_FAN: Fan of triangles (converted to individual quads)</li> * <li>GL_TRIANGLE_STRIP: Strip of triangles (converted to individual quads)</li> * <li>GL_QUAD_STRIP: Strip of quads (converted to individual quads)</li> * <li>GL_POLYGON: Polygon (treated as triangle fan)</li> * </ul> * * <p>Unsupported primitive types (logged warning, geometry discarded): * <ul> * <li>GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP: Line primitives</li> * <li>GL_POINTS: Point primitives</li> * </ul> */ public class ImmediateModeRecorder { private static final Logger LOGGER = LogManager.getLogger("ImmediateModeRecorder"); // Accumulated quads from completed primitives private final List<ModelQuadViewMutable> quads = new ArrayList<>(); // Accumulated line vertices (pairs of vertices for GL_LINES) private final List<LineVertex> lineVertices = new ArrayList<>(); // Current primitive state private int currentPrimitiveType = -1; private boolean inPrimitive = false; // Vertices for current primitive (cleared on glEnd) private final List<ImmediateVertex> currentVertices = new ArrayList<>(); // Current immediate mode state (set by glTexCoord*, glNormal*) private float texCoordS = 0.0f; private float texCoordT = 0.0f; private float normalX = 0.0f; private float normalY = 0.0f; private float normalZ = 1.0f; // Default normal points +Z // Track which attributes have been set (for flags) private boolean hasTexCoord = false; private boolean hasNormal = false; private boolean hasColor = false; /** * Represents a single vertex captured during immediate mode. */ private static class ImmediateVertex { float x, y, z; // Position int color; // Packed ABGR color float texU, texV; // Texture coordinates int normal; // Packed normal ImmediateVertex(float x, float y, float z, int color, float texU, float texV, int normal) { this.x = x; this.y = y; this.z = z; this.color = color; this.texU = texU; this.texV = texV; this.normal = normal; } } /** * Represents a vertex for line primitives. * Simpler than ImmediateVertex - just position and color. */ public static class LineVertex { public final float x, y, z; public final int color; // Packed ABGR color public LineVertex(float x, float y, float z, int color) { this.x = x; this.y = y; this.z = z; this.color = color; } } public ImmediateModeRecorder() { // Recorder is ready to capture geometry } /** * Set the current texture coordinate. * Called by GLStateManager.glTexCoord*. */ public void setTexCoord(float s, float t) { this.texCoordS = s; this.texCoordT = t; this.hasTexCoord = true; } /** * Set the current normal vector. * Called by GLStateManager.glNormal*. */ public void setNormal(float x, float y, float z) { this.normalX = x; this.normalY = y; this.normalZ = z; this.hasNormal = true; } /** * Check if currently in a primitive (between glBegin and glEnd). */ public boolean isInPrimitive() { return inPrimitive; } /** * Start recording a new primitive. */ public void begin(int primitiveType) { if (inPrimitive) { throw new IllegalStateException("glBegin called while already in primitive"); } this.currentPrimitiveType = primitiveType; this.currentVertices.clear(); this.inPrimitive = true; } /** * End the current primitive, convert to quads/lines, and return them immediately. * This allows the caller to create AccumulatedDraw at the correct command position. * * @return Result containing quads, lines, and flags, or null if no geometry was produced */ public Result end() { if (!inPrimitive) { throw new IllegalStateException("glEnd called without glBegin"); } // Capture last vertex attributes BEFORE clearing currentVertices // These will be used to restore GL current state after VBO playback float lastColorR = 1.0f, lastColorG = 1.0f, lastColorB = 1.0f, lastColorA = 1.0f; float lastNormalX = 0.0f, lastNormalY = 0.0f, lastNormalZ = 1.0f; float lastTexS = 0.0f, lastTexT = 0.0f; if (!currentVertices.isEmpty()) { ImmediateVertex last = currentVertices.get(currentVertices.size() - 1); // Unpack color from ABGR format lastColorR = (last.color & 0xFF) / 255.0f; lastColorG = ((last.color >> 8) & 0xFF) / 255.0f; lastColorB = ((last.color >> 16) & 0xFF) / 255.0f; lastColorA = ((last.color >> 24) & 0xFF) / 255.0f; // Unpack normal from NormI8 format (signed bytes packed into int) lastNormalX = NormI8.unpackX(last.normal); lastNormalY = NormI8.unpackY(last.normal); lastNormalZ = NormI8.unpackZ(last.normal); // Texture coords are stored directly as floats lastTexS = last.texU; lastTexT = last.texV; } // Convert this primitive's vertices to quads or lines convertPrimitiveToQuads(); this.currentVertices.clear(); this.inPrimitive = false; // Return geometry from this primitive immediately (don't accumulate) if (quads.isEmpty() && lineVertices.isEmpty()) { return null; } // Copy geometry and create flags List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads); List<LineVertex> resultLines = new ArrayList<>(lineVertices); CapturingTessellator.Flags flags = new CapturingTessellator.Flags( hasTexCoord, // hasTexture false, // hasBrightness - immediate mode doesn't typically use lightmap hasColor, // hasColor hasNormal // hasNormals ); // Clear for next primitive (but keep attribute tracking state) quads.clear(); lineVertices.clear(); return new Result(resultQuads, resultLines, flags, lastColorR, lastColorG, lastColorB, lastColorA, lastNormalX, lastNormalY, lastNormalZ, lastTexS, lastTexT); } /** * Record a vertex with current attributes. * Color is read from GLStateManager at call time. */ public void vertex(float x, float y, float z) { if (!inPrimitive) { throw new IllegalStateException("glVertex called outside glBegin/glEnd"); } // Get current color from GLStateManager int packedColor = packColor( GLStateManager.getColor().getRed(), GLStateManager.getColor().getGreen(), GLStateManager.getColor().getBlue(), GLStateManager.getColor().getAlpha() ); if (packedColor != 0xFFFFFFFF) { hasColor = true; } // Pack normal int packedNormal = NormI8.pack(normalX, normalY, normalZ); currentVertices.add(new ImmediateVertex( x, y, z, packedColor, texCoordS, texCoordT, packedNormal )); } /** * Pack RGBA floats (0-1) into ABGR int format used by ModelQuad. */ private static int packColor(float r, float g, float b, float a) { int ri = (int) (r * 255.0f) & 0xFF; int gi = (int) (g * 255.0f) & 0xFF; int bi = (int) (b * 255.0f) & 0xFF; int ai = (int) (a * 255.0f) & 0xFF; // ABGR format (little-endian: stored as RGBA bytes) return (ai << 24) | (bi << 16) | (gi << 8) | ri; } /** * Convert the current primitive vertices to quads. * Handles different primitive types. */ private void convertPrimitiveToQuads() { int vertexCount = currentVertices.size(); if (vertexCount == 0) { return; } switch (currentPrimitiveType) { case GL11.GL_QUADS -> convertQuads(); case GL11.GL_TRIANGLES -> convertTriangles(); case GL11.GL_TRIANGLE_FAN, GL11.GL_POLYGON -> convertTriangleFan(); case GL11.GL_TRIANGLE_STRIP -> convertTriangleStrip(); case GL11.GL_QUAD_STRIP -> convertQuadStrip(); case GL11.GL_LINES -> convertLines(); case GL11.GL_LINE_STRIP -> convertLineStripToLines(); case GL11.GL_LINE_LOOP -> convertLineLoopToLines(); case GL11.GL_POINTS -> { LOGGER.warn("[ImmediateModeRecorder] Point primitives not supported, discarding {} vertices", vertexCount); } default -> { LOGGER.warn("[ImmediateModeRecorder] Unknown primitive type {}, discarding {} vertices", currentPrimitiveType, vertexCount); } } } /** * Convert GL_QUADS vertices to ModelQuads (4 vertices per quad). */ private void convertQuads() { int vertexCount = currentVertices.size(); int fullQuads = vertexCount / 4; for (int i = 0; i < fullQuads; i++) { int base = i * 4; addQuad( currentVertices.get(base), currentVertices.get(base + 1), currentVertices.get(base + 2), currentVertices.get(base + 3) ); } int remaining = vertexCount % 4; if (remaining > 0) { LOGGER.warn("[ImmediateModeRecorder] GL_QUADS: Incomplete quad, discarding {} vertices", remaining); } } /** * Convert GL_TRIANGLES vertices to degenerate quads (3 vertices per triangle, duplicate last). */ private void convertTriangles() { int vertexCount = currentVertices.size(); int fullTriangles = vertexCount / 3; for (int i = 0; i < fullTriangles; i++) { int base = i * 3; ImmediateVertex v0 = currentVertices.get(base); ImmediateVertex v1 = currentVertices.get(base + 1); ImmediateVertex v2 = currentVertices.get(base + 2); // Degenerate quad: duplicate third vertex addQuad(v0, v1, v2, v2); } int remaining = vertexCount % 3; if (remaining > 0) { LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLES: Incomplete triangle, discarding {} vertices", remaining); } } /** * Convert GL_TRIANGLE_FAN vertices to triangles then to degenerate quads. * First vertex is center, subsequent vertices form fan. */ private void convertTriangleFan() { int vertexCount = currentVertices.size(); if (vertexCount < 3) { LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_FAN: Need at least 3 vertices, got {}", vertexCount); return; } ImmediateVertex center = currentVertices.get(0); for (int i = 1; i < vertexCount - 1; i++) { ImmediateVertex v1 = currentVertices.get(i); ImmediateVertex v2 = currentVertices.get(i + 1); // Triangle: center, v1, v2 -> degenerate quad addQuad(center, v1, v2, v2); } } /** * Convert GL_TRIANGLE_STRIP vertices to triangles then to degenerate quads. */ private void convertTriangleStrip() { int vertexCount = currentVertices.size(); if (vertexCount < 3) { LOGGER.warn("[ImmediateModeRecorder] GL_TRIANGLE_STRIP: Need at least 3 vertices, got {}", vertexCount); return; } for (int i = 0; i < vertexCount - 2; i++) { ImmediateVertex v0, v1, v2; if ((i & 1) == 0) { // Even triangle: v[i], v[i+1], v[i+2] v0 = currentVertices.get(i); v1 = currentVertices.get(i + 1); v2 = currentVertices.get(i + 2); } else { // Odd triangle: v[i+1], v[i], v[i+2] (reverse winding) v0 = currentVertices.get(i + 1); v1 = currentVertices.get(i); v2 = currentVertices.get(i + 2); } addQuad(v0, v1, v2, v2); } } /** * Convert GL_QUAD_STRIP vertices to quads. * Vertices come in pairs: (v0,v1), (v2,v3), (v4,v5)... * Each quad uses 4 consecutive vertices in pattern: v[2i], v[2i+1], v[2i+3], v[2i+2] */ private void convertQuadStrip() { int vertexCount = currentVertices.size(); if (vertexCount < 4) { LOGGER.warn("[ImmediateModeRecorder] GL_QUAD_STRIP: Need at least 4 vertices, got {}", vertexCount); return; } int numQuads = (vertexCount - 2) / 2; for (int i = 0; i < numQuads; i++) { int base = i * 2; // Quad strip winding: v[0], v[1], v[3], v[2] addQuad( currentVertices.get(base), currentVertices.get(base + 1), currentVertices.get(base + 3), currentVertices.get(base + 2) ); } } /** * Convert GL_LINES vertices to line segments (pairs of vertices). */ private void convertLines() { int vertexCount = currentVertices.size(); int fullLines = vertexCount / 2; for (int i = 0; i < fullLines; i++) { int base = i * 2; ImmediateVertex v0 = currentVertices.get(base); ImmediateVertex v1 = currentVertices.get(base + 1); lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color)); lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color)); } int remaining = vertexCount % 2; if (remaining > 0) { LOGGER.warn("[ImmediateModeRecorder] GL_LINES: Incomplete line, discarding {} vertices", remaining); } } /** * Convert GL_LINE_STRIP to individual line segments. * Vertices 0-1-2-3 become lines: 0-1, 1-2, 2-3 */ private void convertLineStripToLines() { int vertexCount = currentVertices.size(); if (vertexCount < 2) { LOGGER.warn("[ImmediateModeRecorder] GL_LINE_STRIP: Need at least 2 vertices, got {}", vertexCount); return; } for (int i = 0; i < vertexCount - 1; i++) { ImmediateVertex v0 = currentVertices.get(i); ImmediateVertex v1 = currentVertices.get(i + 1); lineVertices.add(new LineVertex(v0.x, v0.y, v0.z, v0.color)); lineVertices.add(new LineVertex(v1.x, v1.y, v1.z, v1.color)); } } /** * Convert GL_LINE_LOOP to individual line segments. * Like LINE_STRIP but also closes the loop from last to first vertex. */ private void convertLineLoopToLines() { int vertexCount = currentVertices.size(); if (vertexCount < 2) { LOGGER.warn("[ImmediateModeRecorder] GL_LINE_LOOP: Need at least 2 vertices, got {}", vertexCount); return; } // Convert as strip first convertLineStripToLines(); // Close the loop: add last-to-first segment ImmediateVertex vLast = currentVertices.get(vertexCount - 1); ImmediateVertex vFirst = currentVertices.get(0); lineVertices.add(new LineVertex(vLast.x, vLast.y, vLast.z, vLast.color)); lineVertices.add(new LineVertex(vFirst.x, vFirst.y, vFirst.z, vFirst.color)); } /** * Create a ModelQuad from 4 ImmediateVertex objects. */ private void addQuad(ImmediateVertex v0, ImmediateVertex v1, ImmediateVertex v2, ImmediateVertex v3) { ModelQuad quad = new ModelQuad(); setVertex(quad, 0, v0); setVertex(quad, 1, v1); setVertex(quad, 2, v2); setVertex(quad, 3, v3); // Set light face based on computed normal quad.setLightFace(ModelQuadUtil.findLightFace(quad.getComputedFaceNormal())); quads.add(quad); } /** * Set a single vertex in a ModelQuad. */ private void setVertex(ModelQuad quad, int idx, ImmediateVertex v) { quad.setX(idx, v.x); quad.setY(idx, v.y); quad.setZ(idx, v.z); quad.setColor(idx, v.color); quad.setTexU(idx, v.texU); quad.setTexV(idx, v.texV); quad.setForgeNormal(idx, v.normal); // Light defaults to full brightness (no lightmap for immediate mode typically) quad.setLight(idx, ModelQuadUtil.DEFAULT_LIGHTMAP); } /** * Check if any immediate mode geometry has been captured. * * <p>Note: With immediate flush mode, this will typically return false as geometry * is returned from end() immediately. This method is kept for edge cases * where primitives might fail to convert (e.g., incomplete quads). */ public boolean hasGeometry() { return !quads.isEmpty() || !lineVertices.isEmpty(); } /** * Get any remaining accumulated geometry and clear the recorder. * * <p>Note: With immediate flush mode, this will typically return null as geometry * is returned from end() immediately. This method is kept for cleanup and * edge cases where geometry might remain (e.g., if end() was never called). * * @return Result containing remaining quads, lines, and flags, or null if no geometry */ public Result getQuadsAndClear() { if (inPrimitive) { throw new IllegalStateException("Cannot get geometry while in primitive (missing glEnd)"); } if (quads.isEmpty() && lineVertices.isEmpty()) { return null; } // Copy geometry and create flags List<ModelQuadViewMutable> resultQuads = new ArrayList<>(quads); List<LineVertex> resultLines = new ArrayList<>(lineVertices); CapturingTessellator.Flags flags = new CapturingTessellator.Flags( hasTexCoord, // hasTexture false, // hasBrightness - immediate mode doesn't typically use lightmap hasColor, // hasColor hasNormal // hasNormals ); // Clear state for reuse quads.clear(); lineVertices.clear(); hasColor = false; hasTexCoord = false; hasNormal = false; // Note: current texcoord/normal values are NOT reset - they persist per OpenGL spec // For getQuadsAndClear, we don't have last vertex data (it was cleared in end()) // Use default values - this method is for edge cases/cleanup anyway return new Result(resultQuads, resultLines, flags, 1.0f, 1.0f, 1.0f, 1.0f, // Default white color 0.0f, 0.0f, 1.0f, // Default +Z normal 0.0f, 0.0f); // Default (0,0) texcoord } /** * Result of immediate mode recording: quads, lines, attribute flags, and last vertex state. * The last vertex state is used to restore GL_CURRENT_COLOR etc. after VBO playback. */ @com.github.bsideup.jabel.Desugar public record Result( List<ModelQuadViewMutable> quads, List<LineVertex> lines, CapturingTessellator.Flags flags, // Last vertex attributes for restoration after VBO draw float lastColorR, float lastColorG, float lastColorB, float lastColorA, float lastNormalX, float lastNormalY, float lastNormalZ, float lastTexCoordS, float lastTexCoordT ) {} /** * Reset all state including current texcoord/normal. * Called when starting a new display list. */ public void reset() { quads.clear(); lineVertices.clear(); currentVertices.clear(); inPrimitive = false; currentPrimitiveType = -1; texCoordS = 0.0f; texCoordT = 0.0f; normalX = 0.0f; normalY = 0.0f; normalZ = 1.0f; hasColor = false; hasTexCoord = false; hasNormal = false; } /** * Process a glDrawArrays call during display list recording. * Reads vertex data from client arrays (tracked globally in GLStateManager) and converts to immediate mode geometry. * * @param mode Primitive type (GL_QUADS, GL_LINES, etc.) * @param first Starting index in arrays * @param count Number of vertices * @return Result containing converted geometry, or null if no geometry produced */ public Result processDrawArrays(int mode, int first, int count) { final var cas = GLStateManager.getClientArrayState(); final var vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null; final var colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null; return convertClientArrays( mode, first, count, vertexPointer, cas.getVertexPointerType(), cas.getVertexPointerSize(), cas.getVertexPointerStride(), colorPointer, cas.getColorPointerType(), cas.getColorPointerSize(), cas.getColorPointerStride() ); } /** * Convert client array data to immediate mode. * Called by glDrawArrays during display list recording. * Like Mesa's save_DrawArrays, reads vertex data from arrays and emits as immediate mode. * * @param mode Primitive type (GL_QUADS, GL_LINES, etc.) * @param first Starting index in arrays * @param count Number of vertices * @param vertexPointer Vertex position buffer (or null if not enabled) * @param vertexType GL type (GL_FLOAT, GL_DOUBLE, etc.) * @param vertexSize Size of vertex (2, 3, or 4) * @param vertexStride Stride in bytes (0 for tightly packed) * @param colorPointer Color buffer (or null if not enabled) * @param colorType GL type (GL_FLOAT, GL_UNSIGNED_BYTE, etc.) * @param colorSize Size of color (3 or 4) * @param colorStride Stride in bytes (0 for tightly packed) * @return Result containing converted geometry, or null if no geometry produced */ public Result convertClientArrays( int mode, int first, int count, java.nio.Buffer vertexPointer, int vertexType, int vertexSize, int vertexStride, java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride ) { begin(mode); // Hoist type checks and stride calculations outside the loop for performance. // Mesa's algorithm: offset_bytes = index * effective_stride // effective_stride = (stride == 0) ? (numComponents * sizeof(element)) : stride // Determine color reader (hoisted out of loop) final ColorReader colorReader; final int colorEffectiveStride; if (colorPointer == null) { colorReader = null; colorEffectiveStride = 0; } else if (colorType == GL11.GL_FLOAT && colorPointer instanceof FloatBuffer fb) { colorEffectiveStride = (colorStride == 0) ? colorSize * 4 : colorStride; final int strideInFloats = colorEffectiveStride / 4; colorReader = (idx) -> { final int offset = idx * strideInFloats; final float r = fb.get(offset); final float g = fb.get(offset + 1); final float b = fb.get(offset + 2); final float a = (colorSize == 4) ? fb.get(offset + 3) : 1.0f; GLStateManager.glColor4f(r, g, b, a); }; } else if ((colorType == GL11.GL_UNSIGNED_BYTE || colorType == GL11.GL_BYTE) && colorPointer instanceof ByteBuffer bb) { colorEffectiveStride = (colorStride == 0) ? colorSize : colorStride; colorReader = (idx) -> { final int offset = idx * colorEffectiveStride; final float r = (bb.get(offset) & 0xFF) / 255.0f; final float g = (bb.get(offset + 1) & 0xFF) / 255.0f; final float b = (bb.get(offset + 2) & 0xFF) / 255.0f; final float a = (colorSize == 4) ? (bb.get(offset + 3) & 0xFF) / 255.0f : 1.0f; GLStateManager.glColor4f(r, g, b, a); }; } else { // Unsupported color type - use white colorEffectiveStride = 0; colorReader = (idx) -> GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } // Determine vertex reader (hoisted out of loop) final VertexReader vertexReader; if (vertexPointer == null) { vertexReader = null; } else if (vertexType == GL11.GL_FLOAT && vertexPointer instanceof FloatBuffer fb) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 4 : vertexStride; final int strideInFloats = effectiveStride / 4; vertexReader = (idx) -> { final int offset = idx * strideInFloats; final float x = fb.get(offset); final float y = fb.get(offset + 1); final float z = (vertexSize >= 3) ? fb.get(offset + 2) : 0.0f; vertex(x, y, z); }; } else if (vertexType == GL11.GL_DOUBLE && vertexPointer instanceof DoubleBuffer db) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 8 : vertexStride; final int strideInDoubles = effectiveStride / 8; vertexReader = (idx) -> { final int offset = idx * strideInDoubles; final float x = (float) db.get(offset); final float y = (float) db.get(offset + 1); final float z = (vertexSize >= 3) ? (float) db.get(offset + 2) : 0.0f; vertex(x, y, z); }; } else if (vertexType == GL11.GL_INT && vertexPointer instanceof IntBuffer ib) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 4 : vertexStride; final int strideInInts = effectiveStride / 4; vertexReader = (idx) -> { final int offset = idx * strideInInts; final float x = ib.get(offset); final float y = ib.get(offset + 1); final float z = (vertexSize >= 3) ? ib.get(offset + 2) : 0.0f; vertex(x, y, z); }; } else if (vertexType == GL11.GL_SHORT && vertexPointer instanceof ShortBuffer sb) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 2 : vertexStride; final int strideInShorts = effectiveStride / 2; vertexReader = (idx) -> { final int offset = idx * strideInShorts; final float x = sb.get(offset); final float y = sb.get(offset + 1); final float z = (vertexSize >= 3) ? sb.get(offset + 2) : 0.0f; vertex(x, y, z); }; } else { // Unsupported vertex type vertexReader = null; } // Main loop - no type checks, just function calls for (int i = first; i < first + count; i++) { if (colorReader != null) { colorReader.read(i); } if (vertexReader != null) { vertexReader.read(i); } } return end(); } @FunctionalInterface private interface ColorReader { void read(int index); } @FunctionalInterface private interface VertexReader { void read(int index); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\RecordedGeometry.java
package com.gtnewhorizons.angelica.glsm.recording; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizons.angelica.glsm.recording.commands.DrawCommand; import me.jellysquid.mods.sodium.client.gl.attribute.BufferVertexFormat; import java.nio.ByteBuffer; import java.util.List; /** * Represents recorded geometry from a display list compilation. * Contains the vertex data buffer and metadata about draw commands. */ @Desugar public record RecordedGeometry(ByteBuffer buffer, BufferVertexFormat format, List<DrawCommand> drawCommands, int totalVertexCount) { public int getByteSize() { return buffer.remaining(); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\AlphaStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.AlphaState; public class AlphaStateStack extends AlphaState implements IStateStack<AlphaState> { protected final AlphaState[] stack; protected int pointer; public AlphaStateStack() { stack = new AlphaState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new AlphaState(); } } public AlphaStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public AlphaStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\BlendStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.BlendState; public class BlendStateStack extends BlendState implements IStateStack<BlendStateStack> { protected final BlendState[] stack; protected int pointer; public BlendStateStack() { stack = new BlendState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new BlendState(); } } public BlendStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public BlendStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\BooleanStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.BooleanState; /** * A stack for boolean GL state with lazy copy-on-write optimization. * <p> * When using the global attrib depth tracking (from glPushAttrib/glPopAttrib), state is only * saved when actually modified, dramatically reducing overhead when most states * don't change (e.g., GL_ENABLE_BIT saves ~270 states but typically only 3-4 change). */ public class BooleanStateStack extends BooleanState implements IStateStack<BooleanStateStack> { protected final boolean[] stack; /** * The depth at which state has been saved. Compared against GLStateManager.getAttribDepth() * to determine if we need to save before modification or restore on pop. */ protected int savedDepth; public BooleanStateStack(int glCap) { // Most booleans default to false this(glCap, false); } /** * Create a BooleanStateStack with a custom initial state. * Useful for GL states that default to true (e.g., GL_DITHER, GL_MULTISAMPLE). * * @param glCap GL capability constant * @param initialState initial enabled state */ public BooleanStateStack(int glCap, boolean initialState) { super(glCap); this.enabled = initialState; stack = new boolean[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; } // ==================== Traditional Stack Operations ==================== @Override public BooleanStateStack push() { if (savedDepth >= stack.length) { throw new IllegalStateException("Stack overflow size " + (savedDepth + 1) + " reached"); } stack[savedDepth++] = enabled; return this; } @Override public BooleanStateStack pop() { if (savedDepth == 0) { throw new IllegalStateException("Stack underflow"); } final boolean oldValue = stack[--savedDepth]; // Call setEnabledDirect to avoid triggering beforeModify during restore setEnabledDirect(oldValue); return this; } @Override public boolean isEmpty() { return savedDepth == 0; } // ==================== Lazy Copy-on-Write Operations ==================== @Override public int pushDepth() { // No-op: global depth is managed by GLStateManager return GLStateManager.getAttribDepth(); } /** * Restore state if it was modified at the current depth. * Only called by GLStateManager.popState() for states that registered as modified. */ @Override public BooleanStateStack popDepth() { // We're only called if we were modified, so savedDepth should match if (savedDepth > 0) { final boolean oldValue = stack[--savedDepth]; setEnabledDirect(oldValue); } return this; } /** * Called before modifying state. If we haven't saved at the current depth yet, * save the current value and register with GLStateManager for restoration. */ @Override public void beforeModify() { final int globalDepth = GLStateManager.getAttribDepth(); if (savedDepth < globalDepth) { stack[savedDepth++] = enabled; GLStateManager.registerModifiedState(this); } } @Override public int getDepth() { return GLStateManager.getAttribDepth(); } @Override public void setEnabled(boolean enabled) { beforeModify(); super.setEnabled(enabled); } private void setEnabledDirect(boolean enabled) { super.setEnabled(enabled); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\Color4Stack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.Color4; public class Color4Stack extends Color4 implements IStateStack<Color4Stack> { protected final Color4[] stack; protected int pointer; public Color4Stack() { stack = new Color4[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new Color4(); } } public Color4Stack(Color4 color4) { this(); set(color4); } public Color4Stack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public Color4Stack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\ColorMaskStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.ColorMask; public class ColorMaskStack extends ColorMask implements IStateStack<ColorMaskStack> { protected final ColorMask[] stack; protected int pointer; public ColorMaskStack() { stack = new ColorMask[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new ColorMask(); } } public ColorMaskStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public ColorMaskStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\DepthStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.DepthState; public class DepthStateStack extends DepthState implements IStateStack<DepthStateStack> { protected final DepthState[] stack; protected int pointer; public DepthStateStack() { stack = new DepthState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new DepthState(); } } public DepthStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public DepthStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\FogStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.FogState; public class FogStateStack extends FogState implements IStateStack<FogStateStack> { protected final FogState[] stack; protected int pointer; public FogStateStack() { stack = new FogState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new FogState(); } } public FogStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public FogStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\IntegerStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.IntegerState; public class IntegerStateStack extends IntegerState implements IStateStack<IntegerStateStack> { protected final IntegerState[] stack; protected int pointer; public IntegerStateStack(int val) { setValue(val); stack = new IntegerState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new IntegerState(); stack[i].setValue(val); } } public IntegerStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public IntegerStateStack push(int value) { push().setValue(value); return this; } public IntegerStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\LightModelStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.LightModelState; public class LightModelStateStack extends LightModelState implements IStateStack<LightModelStateStack> { protected final LightModelState[] stack; protected int pointer; public LightModelStateStack() { super(); stack = new LightModelState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new LightModelState(); } } public LightModelStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public LightModelStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\LightStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.LightState; public class LightStateStack extends LightState implements IStateStack<LightStateStack> { protected final LightState[] stack; protected int pointer; public LightStateStack(int light) { super(light); stack = new LightState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new LightState(light); } } public LightStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public LightStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\LineStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.LineState; /** * Stack for GL line state (width, stipple factor, stipple pattern). * Used by GL_LINE_BIT push/pop attrib. */ public class LineStateStack extends LineState implements IStateStack<LineStateStack> { protected final LineState[] stack; protected int pointer; public LineStateStack() { stack = new LineState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new LineState(); } } public LineStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public LineStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\MaterialStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.MaterialState; public class MaterialStateStack extends MaterialState implements IStateStack<MaterialStateStack> { protected final MaterialState[] stack; protected int pointer; public MaterialStateStack(int face) { super(face); stack = new MaterialState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new MaterialState(face); } } public MaterialStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public MaterialStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\MatrixModeStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.MatrixMode; public class MatrixModeStack extends MatrixMode implements IStateStack<MatrixModeStack> { protected final MatrixMode[] stack; protected int pointer; public MatrixModeStack() { stack = new MatrixMode[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new MatrixMode(); } } public MatrixModeStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public MatrixModeStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\PointStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.PointState; /** * Stack for GL point state (size). * Used by GL_POINT_BIT push/pop attrib. */ public class PointStateStack extends PointState implements IStateStack<PointStateStack> { protected final PointState[] stack; protected int pointer; public PointStateStack() { stack = new PointState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new PointState(); } } public PointStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public PointStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\PolygonStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.PolygonState; /** * Stack for GL polygon state (mode, offset, cull face mode, front face). * Used by GL_POLYGON_BIT push/pop attrib. */ public class PolygonStateStack extends PolygonState implements IStateStack<PolygonStateStack> { protected final PolygonState[] stack; protected int pointer; public PolygonStateStack() { stack = new PolygonState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new PolygonState(); } } public PolygonStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public PolygonStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\StencilStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.StencilState; /** * Stack for GL stencil buffer state. * Used by GL_STENCIL_BUFFER_BIT push/pop attrib. */ public class StencilStateStack extends StencilState implements IStateStack<StencilStateStack> { protected final StencilState[] stack; protected int pointer; public StencilStateStack() { stack = new StencilState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new StencilState(); } } public StencilStateStack push() { if (pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public StencilStateStack pop() { if (pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\TextureBindingStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.TextureBinding; public class TextureBindingStack extends TextureBinding implements IStateStack<TextureBindingStack> { protected final TextureBinding[] stack; protected int pointer; public TextureBindingStack() { stack = new TextureBinding[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new TextureBinding(); } } public TextureBindingStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public TextureBindingStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public TextureBinding peek() { return stack[pointer]; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\TextureUnitBooleanStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; /** * BooleanStateStack for per-texture-unit state. * Switches to correct unit (raw GL) before enable/disable calls. */ public class TextureUnitBooleanStateStack extends BooleanStateStack { private final int unitIndex; public TextureUnitBooleanStateStack(int glCap, int unitIndex) { super(glCap); this.unitIndex = unitIndex; } public TextureUnitBooleanStateStack(int glCap, int unitIndex, boolean initialState) { super(glCap, initialState); this.unitIndex = unitIndex; } @Override public void setEnabled(boolean enabled) { beforeModify(); setEnabledWithUnitSwitch(enabled); } @Override public TextureUnitBooleanStateStack popDepth() { if (savedDepth > 0) { final boolean oldValue = stack[--savedDepth]; setEnabledWithUnitSwitch(oldValue); } return this; } private void setEnabledWithUnitSwitch(boolean enabled) { final boolean bypass = GLStateManager.shouldBypassCache(); if (bypass || enabled != this.enabled) { if (!bypass) this.enabled = enabled; int currentUnit = GLStateManager.getActiveTextureUnit(); boolean needsSwitch = currentUnit != unitIndex; if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + unitIndex); if (enabled) GL11.glEnable(glCap); else GL11.glDisable(glCap); if (needsSwitch) GL13.glActiveTexture(GL13.GL_TEXTURE0 + currentUnit); } } public int getUnitIndex() { return unitIndex; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\stacks\ViewPortStateStack.java
package com.gtnewhorizons.angelica.glsm.stacks; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.ViewportState; public class ViewPortStateStack extends ViewportState implements IStateStack<ViewPortStateStack> { protected final ViewportState[] stack; protected int pointer; public ViewPortStateStack() { stack = new ViewportState[GLStateManager.MAX_ATTRIB_STACK_DEPTH]; for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) { stack[i] = new ViewportState(); } } public ViewPortStateStack push() { if(pointer == stack.length) { throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); } stack[pointer++].set(this); return this; } public ViewPortStateStack pop() { if(pointer == 0) { throw new IllegalStateException("Stack underflow"); } set(stack[--pointer]); return this; } public boolean isEmpty() { return pointer == 0; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\AlphaState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; @Getter public class AlphaState implements ISettableState<AlphaState> { @Setter protected int function = GL11.GL_ALWAYS; @Setter protected float reference = -1.0F; @Override public AlphaState set(AlphaState state) { this.function = state.function; this.reference = state.reference; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof AlphaState alphaState)) return false; return function == alphaState.function && Float.compare(alphaState.reference, reference) == 0; } @Override public AlphaState copy() { return new AlphaState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\BlendState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; @Getter @Setter public class BlendState implements ISettableState<BlendState> { protected int srcRgb = GL11.GL_ONE; protected int dstRgb = GL11.GL_ZERO; protected int srcAlpha = GL11.GL_ONE; protected int dstAlpha = GL11.GL_ZERO; public BlendState() {} public BlendState(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { this.srcRgb = srcRgb; this.dstRgb = dstRgb; this.srcAlpha = srcAlpha; this.dstAlpha = dstAlpha; } public void setAll(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { this.srcRgb = srcRgb; this.dstRgb = dstRgb; this.srcAlpha = srcAlpha; this.dstAlpha = dstAlpha; } public void setSrcDstRgb(int srcRgb, int dstRgb) { this.srcRgb = srcRgb; this.dstRgb = dstRgb; } @Override public BlendState set(BlendState state) { this.srcRgb = state.srcRgb; this.dstRgb = state.dstRgb; this.srcAlpha = state.srcAlpha; this.dstAlpha = state.dstAlpha; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof BlendState blendState)) return false; return srcRgb == blendState.srcRgb && dstRgb == blendState.dstRgb && srcAlpha == blendState.srcAlpha && dstAlpha == blendState.dstAlpha; } @Override public BlendState copy() { return new BlendState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\BooleanState.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import lombok.Getter; import org.lwjgl.opengl.GL11; public class BooleanState implements ISettableState<BooleanState> { protected final int glCap; @Getter protected boolean enabled; public BooleanState(int glCap) { this.glCap = glCap; } public void disable() { this.setEnabled(false); } public void enable() { this.setEnabled(true); } public void setEnabled(boolean enabled) { final boolean bypass = GLStateManager.shouldBypassCache(); if (bypass || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.vendorIsAMD() && GLStateManager.isPoppingAttributes())) { if (!bypass) { this.enabled = enabled; } // Always call GL - the calling method controls whether we reach here based on recording mode if (enabled) { GL11.glEnable(this.glCap); } else { GL11.glDisable(this.glCap); } } } @Override public BooleanState set(BooleanState state) { this.enabled = state.enabled; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof BooleanState booleanState)) return false; return enabled == booleanState.enabled; } @Override public BooleanState copy() { return new BooleanState(this.glCap).set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\ClientArrayState.java
package com.gtnewhorizons.angelica.glsm.states; import java.nio.Buffer; import org.lwjgl.opengl.GL11; /** * Tracks OpenGL client array state (glVertexPointer, glColorPointer, etc.) * This state is NOT part of the server attribute stack (push/pop attrib), * but is needed for display list compilation to capture glDrawArrays calls. * * When a display list is compiled, glDrawArrays reads from the current * vertex/color arrays at compile time (not playback time). We need to track * this state globally so ImmediateModeRecorder can access it. */ public class ClientArrayState { // Vertex array state private boolean vertexArrayEnabled = false; private Buffer vertexPointer = null; private int vertexPointerSize = 4; private int vertexPointerType = GL11.GL_FLOAT; private int vertexPointerStride = 0; // Color array state private boolean colorArrayEnabled = false; private Buffer colorPointer = null; private int colorPointerSize = 4; private int colorPointerType = GL11.GL_FLOAT; private int colorPointerStride = 0; // Vertex array methods public void setVertexPointer(int size, int type, int stride, Buffer pointer) { this.vertexPointerSize = size; this.vertexPointerType = type; this.vertexPointerStride = stride; this.vertexPointer = pointer; } public boolean isVertexArrayEnabled() { return vertexArrayEnabled; } public void setVertexArrayEnabled(boolean enabled) { this.vertexArrayEnabled = enabled; } public Buffer getVertexPointer() { return vertexPointer; } public int getVertexPointerSize() { return vertexPointerSize; } public int getVertexPointerType() { return vertexPointerType; } public int getVertexPointerStride() { return vertexPointerStride; } // Color array methods public void setColorPointer(int size, int type, int stride, Buffer pointer) { this.colorPointerSize = size; this.colorPointerType = type; this.colorPointerStride = stride; this.colorPointer = pointer; } public boolean isColorArrayEnabled() { return colorArrayEnabled; } public void setColorArrayEnabled(boolean enabled) { this.colorArrayEnabled = enabled; } public Buffer getColorPointer() { return colorPointer; } public int getColorPointerSize() { return colorPointerSize; } public int getColorPointerType() { return colorPointerType; } public int getColorPointerStride() { return colorPointerStride; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\Color4.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import java.nio.FloatBuffer; @Getter @Setter public class Color4 implements ISettableState<Color4> { protected float red = 1.0F; protected float green = 1.0F; protected float blue = 1.0F; protected float alpha = 1.0F; public Color4() { } public Color4(float red, float green, float blue, float alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } @Override public Color4 set(Color4 state) { this.red = state.red; this.green = state.green; this.blue = state.blue; this.alpha = state.alpha; return this; } public void get(FloatBuffer params) { params.put(0, red); params.put(1, green); params.put(2, blue); params.put(3, alpha); } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof Color4 color4)) return false; return Float.compare(color4.red, red) == 0 && Float.compare(color4.green, green) == 0 && Float.compare(color4.blue, blue) == 0 && Float.compare(color4.alpha, alpha) == 0; } @Override public Color4 copy() { return new Color4().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\ColorMask.java
package com.gtnewhorizons.angelica.glsm.states; public class ColorMask implements ISettableState<ColorMask> { public boolean red = true; public boolean green = true; public boolean blue = true; public boolean alpha = true; public void setAll(boolean red, boolean green, boolean blue, boolean alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } @Override public ColorMask set(ColorMask state) { this.red = state.red; this.green = state.green; this.blue = state.blue; this.alpha = state.alpha; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof ColorMask colorMask)) return false; return red == colorMask.red && green == colorMask.green && blue == colorMask.blue && alpha == colorMask.alpha; } @Override public ColorMask copy() { return new ColorMask().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\DepthState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; @Getter @Setter public class DepthState implements ISettableState<DepthState> { protected boolean enabled = true; protected int func = GL11.GL_LESS; @Override public DepthState set(DepthState state) { this.enabled = state.enabled; this.func = state.func; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof DepthState depthState)) return false; return enabled == depthState.enabled && func == depthState.func; } @Override public DepthState copy() { return new DepthState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\FogState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.joml.Vector3d; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; @Getter @Setter public class FogState implements ISettableState<FogState> { protected int fogMode = GL11.GL_EXP; protected final Vector3d fogColor = new Vector3d(0.0F, 0.0F, 0.0F); protected float fogAlpha = 1.0F; protected final FloatBuffer fogColorBuffer = FloatBuffer.allocate(4); protected float density = 1.0F; protected float start; protected float end = 1.0F; @Override public FogState set(FogState state) { this.fogMode = state.fogMode; this.fogColor.set(state.fogColor); this.fogAlpha = state.fogAlpha; this.fogColorBuffer.put(0, state.fogColorBuffer.get(0)); this.density = state.density; this.start = state.start; this.end = state.end; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof FogState fogState)) return false; return fogMode == fogState.fogMode && Float.compare(fogState.fogAlpha, fogAlpha) == 0 && Float.compare(fogState.density, density) == 0 && Float.compare(fogState.start, start) == 0 && Float.compare(fogState.end, end) == 0 && fogColor.equals(fogState.fogColor); } @Override public FogState copy() { return new FogState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\IntegerState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; public class IntegerState implements ISettableState<IntegerState> { @Getter @Setter private int value; @Override public IntegerState set(IntegerState state) { this.value = state.value; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof IntegerState integerState)) return false; return value == integerState.value; } @Override public IntegerState copy() { return new IntegerState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\ISettableState.java
package com.gtnewhorizons.angelica.glsm.states; public interface ISettableState<T> extends Cloneable { T set(T state); @SuppressWarnings("unchecked") default void set(ISettableState<?> value) { set((T) value); } boolean sameAs(Object state); T copy(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\LightModelState.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.joml.Vector4f; import org.joml.Vector4i; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f; public class LightModelState implements ISettableState<LightModelState> { private static final Vector4f vector4f = new Vector4f(); private static final Vector4i vector4i = new Vector4i(); public final Vector4f ambient; public int colorControl; public float localViewer; public float twoSide; public LightModelState() { ambient = new Vector4f(0.2F, 0.2F, 0.2F, 1.0F); colorControl = GL12.GL_SINGLE_COLOR; localViewer = 0.0F; twoSide = 0.0F; } public void setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer); } } public void setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer); } } public void setColorControl(int val) { if (GLStateManager.shouldBypassCache() || this.colorControl != val) { this.colorControl = val; GL11.glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, val); } } public void setColorControl(IntBuffer newBuffer) { setColorControl(newBuffer.get()); } public void setLocalViewer(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.localViewer, val) != 0) { this.localViewer = val; GL11.glLightModelf(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, val); } } public void setLocalViewer(FloatBuffer newBuffer) { setLocalViewer(newBuffer.get()); } public void setLocalViewer(IntBuffer newBuffer) { setLocalViewer((float) newBuffer.get()); } public void setLocalViewer(int val) { setLocalViewer((float) val); } public void setTwoSide(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.twoSide, val) != 0) { this.twoSide = val; GL11.glLightModelf(GL11.GL_LIGHT_MODEL_TWO_SIDE, val); } } public void setTwoSide(FloatBuffer newBuffer) { setTwoSide(newBuffer.get()); } public void setTwoSide(IntBuffer newBuffer) { setTwoSide((float) newBuffer.get()); } public void setTwoSide(int val) { setTwoSide((float) val); } @Override public LightModelState set(LightModelState state) { this.ambient.set(state.ambient); this.colorControl = state.colorControl; this.localViewer = state.localViewer; this.twoSide = state.twoSide; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof LightModelState lightModelState)) return false; return this.ambient.equals(lightModelState.ambient) && this.colorControl == lightModelState.colorControl && Float.compare(lightModelState.localViewer, this.localViewer) == 0 && Float.compare(lightModelState.twoSide, this.twoSide) == 0; } @Override public LightModelState copy() { return new LightModelState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\LightState.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.joml.Matrix3f; import org.joml.Vector3f; import org.joml.Vector3i; import org.joml.Vector4f; import org.joml.Vector4i; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f; public class LightState implements ISettableState<LightState> { private static final Vector4i vector4i = new Vector4i(); private static final Vector4f vector4f = new Vector4f(); private static final Vector3i vector3i = new Vector3i(); private static final Matrix3f matrix3f = new Matrix3f(); public int light; public final Vector4f ambient; public final Vector4f diffuse; public final Vector4f specular; public final Vector4f position; public final Vector3f spotDirection; public float spotExponent; public float spotCutoff; public float constantAttenuation; public float linearAttenuation; public float quadraticAttenuation; public LightState(int light) { this( light, new Vector4f(0F, 0F, 0F, 1F), new Vector4f(0F, 0F, 0F, 1F), new Vector4f(0F, 0F, 0F, 1F), new Vector4f(0F, 0F, 1F, 0F), new Vector3f(0F, 0F, -1F), 0F, 180F, 1.0F, 0.0F, 0.0F ); if (light == GL11.GL_LIGHT0) { this.diffuse.set(1F, 1F, 1F, 1F); this.specular.set(1F, 1F, 1F, 1F); } } public LightState(int light, Vector4f ambient, Vector4f diffuse, Vector4f specular, Vector4f position, Vector3f spotDirection, float spotExponent, float spotCutoff, float constantAttenuation, float linearAttenuation, float quadraticAttenuation) { this.light = light; this.ambient = ambient; this.diffuse = diffuse; this.specular = specular; this.spotExponent = spotExponent; this.spotCutoff = spotCutoff; this.constantAttenuation = constantAttenuation; this.linearAttenuation = linearAttenuation; this.quadraticAttenuation = quadraticAttenuation; this.position = position; this.position.mul(GLStateManager.getModelViewMatrix()); this.spotDirection = spotDirection; GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.mul(matrix3f); } public void setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer); } } public void setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer); } } public void setDiffuse(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer); } } public void setDiffuse(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer); } } public void setSpecular(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer); } } public void setSpecular(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer); } } public void setPosition(FloatBuffer newBuffer) { // We are bypassing cache everytime for position, because the necessary components to enable tracking the cache // are big and probably more than just bypassing. We would need to track the modelview matrix it was transformed // with and the untransformed coordinates in addition to the final transformation. this.position.set(newBuffer); this.position.mul(GLStateManager.getModelViewMatrix()); GL11.glLight(this.light, GL11.GL_POSITION, newBuffer); } public void setPosition(IntBuffer newBuffer) { vector4i.set(newBuffer); this.position.set((float) vector4i.x, (float) vector4i.y, (float) vector4i.z, (float) vector4i.w); this.position.mul(GLStateManager.getModelViewMatrix()); GL11.glLight(this.light, GL11.GL_POSITION, newBuffer); } public void setSpotDirection(FloatBuffer newBuffer) { // We are bypassing cache everytime for spot direction, because the necessary components to enable tracking the cache // are big and probably more than just bypassing. We would need to track the modelview matrix it was transformed // with and the untransformed coordinates in addition to the final transformation. GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.set(newBuffer); this.spotDirection.mul(matrix3f); GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer); } public void setSpotDirection(IntBuffer newBuffer) { vector3i.set(newBuffer); GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z); this.spotDirection.mul(matrix3f); GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer); } public void setSpotExponent(FloatBuffer newBuffer) { setSpotExponent(newBuffer.get()); } public void setSpotExponent(IntBuffer newBuffer) { setSpotExponent((float) newBuffer.get()); } public void setSpotExponent(int i) { setSpotExponent((float) i); } public void setSpotExponent(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotExponent) != 0) { this.spotExponent = f; GL11.glLightf(this.light, GL11.GL_SPOT_EXPONENT, f); } } public void setSpotCutoff(FloatBuffer newBuffer) { setSpotCutoff(newBuffer.get()); } public void setSpotCutoff(IntBuffer newBuffer) { setSpotCutoff((float) newBuffer.get()); } public void setSpotCutoff(int i) { setSpotCutoff((float) i); } public void setSpotCutoff(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotCutoff) != 0) { this.spotCutoff = f; GL11.glLightf(this.light, GL11.GL_SPOT_CUTOFF, f); } } public void setConstantAttenuation(FloatBuffer newBuffer) { setConstantAttenuation(newBuffer.get()); } public void setConstantAttenuation(IntBuffer newBuffer) { setConstantAttenuation((float) newBuffer.get()); } public void setConstantAttenuation(int i) { setConstantAttenuation((float) i); } public void setConstantAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.constantAttenuation) != 0) { this.constantAttenuation = f; GL11.glLightf(this.light, GL11.GL_CONSTANT_ATTENUATION, f); } } public void setLinearAttenuation(FloatBuffer newBuffer) { setLinearAttenuation(newBuffer.get()); } public void setLinearAttenuation(IntBuffer newBuffer) { setLinearAttenuation((float) newBuffer.get()); } public void setLinearAttenuation(int i) { setLinearAttenuation((float) i); } public void setLinearAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.linearAttenuation) != 0) { this.linearAttenuation = f; GL11.glLightf(this.light, GL11.GL_LINEAR_ATTENUATION, f); } } public void setQuadraticAttenuation(FloatBuffer newBuffer) { setQuadraticAttenuation(newBuffer.get()); } public void setQuadraticAttenuation(IntBuffer newBuffer) { setQuadraticAttenuation((float) newBuffer.get()); } public void setQuadraticAttenuation(int i) { setQuadraticAttenuation((float) i); } public void setQuadraticAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.quadraticAttenuation) != 0) { this.quadraticAttenuation = f; GL11.glLightf(this.light, GL11.GL_QUADRATIC_ATTENUATION, f); } } @Override public LightState set(LightState state) { this.ambient.set(state.ambient); this.diffuse.set(state.diffuse); this.specular.set(state.specular); this.position.set(state.position); this.spotDirection.set(state.spotDirection); this.spotExponent = state.spotExponent; this.spotCutoff = state.spotCutoff; this.constantAttenuation = state.constantAttenuation; this.linearAttenuation = state.linearAttenuation; this.quadraticAttenuation = state.quadraticAttenuation; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof LightState lightState)) return false; return this.ambient.equals(lightState.ambient) && this.diffuse.equals(lightState.diffuse) && this.specular.equals(lightState.specular) && this.position.equals(lightState.position) && this.spotDirection.equals(lightState.spotDirection) && Float.compare(this.spotCutoff, lightState.spotCutoff) == 0 && Float.compare(this.spotExponent, lightState.spotExponent) == 0 && Float.compare(this.linearAttenuation, lightState.linearAttenuation) == 0 && Float.compare(this.constantAttenuation, lightState.constantAttenuation) == 0 && Float.compare(this.quadraticAttenuation, lightState.quadraticAttenuation) == 0; } @Override public LightState copy() { return new LightState(this.light).set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\LineState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; /** * Tracks GL line state: width, stipple factor, and stipple pattern. * Corresponds to GL_LINE_BIT attributes. */ @Getter @Setter public class LineState implements ISettableState<LineState> { private float width = 1.0f; private int stippleFactor = 1; private short stipplePattern = (short) 0xFFFF; @Override public LineState set(LineState state) { this.width = state.width; this.stippleFactor = state.stippleFactor; this.stipplePattern = state.stipplePattern; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof LineState lineState)) return false; return Float.compare(width, lineState.width) == 0 && stippleFactor == lineState.stippleFactor && stipplePattern == lineState.stipplePattern; } @Override public LineState copy() { return new LineState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\MaterialState.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.joml.Vector3f; import org.joml.Vector3i; import org.joml.Vector4f; import org.joml.Vector4i; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.gtnewhorizons.angelica.glsm.GLStateManager.i2f; public class MaterialState implements ISettableState<MaterialState> { private static final Vector4f vector4f = new Vector4f(); private static final Vector4i vector4i = new Vector4i(); private static final Vector3f vector3f = new Vector3f(); private static final Vector3i vector3i = new Vector3i(); public int face; public final Vector4f ambient; public final Vector4f diffuse; public final Vector4f specular; public final Vector4f emission; public float shininess; public final Vector3f colorIndexes; public MaterialState(int face) { this.face = face; ambient = new Vector4f(0.2F, 0.2F, 0.2F, 1.0F); diffuse = new Vector4f(0.8F, 0.8F, 0.8F, 1.0F); specular = new Vector4f(0.0F, 0.0F, 0.0F, 1.0F); emission = new Vector4f(0.0F, 0.0F, 0.0F, 1.0F); shininess = 0.0F; colorIndexes = new Vector3f(0.0F, 1.0F, 1.0F); } public void setAmbient(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer); } } public void setAmbient(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer); } } public void setDiffuse(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer); } } public void setDiffuse(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer); } } public void setSpecular(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer); } } public void setSpecular(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer); } } public void setEmission(FloatBuffer newBuffer) { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer); } } public void setEmission(IntBuffer newBuffer) { vector4i.set(newBuffer); vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer); } } public void setShininess(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.shininess, val) != 0) { this.shininess = val; GL11.glMaterialf(face, GL11.GL_SHININESS, val); } } public void setShininess(FloatBuffer newBuffer) { setShininess(newBuffer.get()); } public void setShininess(IntBuffer newBuffer) { setShininess((float) newBuffer.get());} public void setShininess(int val) { setShininess((float) val);} public void setColorIndexes(FloatBuffer newBuffer) { // You are reading this correctly, nvidia drivers flip the y and z values in // glMaterial specifically for GL_COLOR_INDEXES. Other drivers do not do this. // This probably breaks things but who knows, GLSM is setup to track to what the // driver is doing for it right now. if (GLStateManager.vendorIsNVIDIA()) { vector3f.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1)); } else { vector3f.set(newBuffer); } if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer); } } public void setColorIndexes(IntBuffer newBuffer) { vector3i.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1)); vector3f.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z); if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer); } } @Override public MaterialState set(MaterialState state) { this.ambient.set(state.ambient); this.diffuse.set(state.diffuse); this.specular.set(state.specular); this.emission.set(state.emission); this.shininess = state.shininess; this.colorIndexes.set(state.colorIndexes); return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof MaterialState materialState)) return false; return this.ambient.equals(materialState.ambient) && this.diffuse.equals(materialState.diffuse) && this.specular.equals(materialState.specular) && this.emission.equals(materialState.emission) && Float.compare(materialState.shininess, this.shininess) == 0 && this.colorIndexes.equals(materialState.colorIndexes); } @Override public MaterialState copy() { return new MaterialState(this.face).set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\MatrixMode.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import lombok.Getter; import org.lwjgl.opengl.GL11; @Getter public class MatrixMode implements ISettableState<MatrixMode> { protected int mode = GL11.GL_MODELVIEW; public void setMode(int mode) { if(mode != GL11.GL_MODELVIEW && mode != GL11.GL_PROJECTION && mode != GL11.GL_TEXTURE && mode != GL11.GL_COLOR) { // Invalid mode, do nothing on the cache, but pass it along to OGL GL11.glMatrixMode(mode); return; } final boolean bypass = GLStateManager.shouldBypassCache(); if (bypass || this.mode != mode) { if (!bypass) { this.mode = mode; } GL11.glMatrixMode(mode); } } public int getMatrix() { return switch(mode) { case GL11.GL_MODELVIEW -> GL11.GL_MODELVIEW_MATRIX; case GL11.GL_PROJECTION -> GL11.GL_PROJECTION_MATRIX; case GL11.GL_TEXTURE -> GL11.GL_TEXTURE_MATRIX; default -> throw new IllegalStateException("Unexpected value: " + mode); }; } @Override public MatrixMode set(MatrixMode state) { this.mode = state.mode; return this; } @Override public boolean sameAs(Object state) { if(this == state) return true; if(!(state instanceof MatrixMode matrixMode)) return false; return mode == matrixMode.mode; } @Override public MatrixMode copy() { return new MatrixMode().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\PointState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; /** * Tracks GL point state: size. * Corresponds to GL_POINT_BIT attributes. */ @Getter @Setter public class PointState implements ISettableState<PointState> { private float size = 1.0f; @Override public PointState set(PointState state) { this.size = state.size; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof PointState pointState)) return false; return Float.compare(size, pointState.size) == 0; } @Override public PointState copy() { return new PointState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\PolygonState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; /** * Tracks GL polygon state: polygon mode (front/back) and polygon offset. * Corresponds to GL_POLYGON_BIT attributes (excluding enable bits which are BooleanStateStack). */ @Getter @Setter public class PolygonState implements ISettableState<PolygonState> { private int frontMode = GL11.GL_FILL; private int backMode = GL11.GL_FILL; private float offsetFactor = 0.0f; private float offsetUnits = 0.0f; private int cullFaceMode = GL11.GL_BACK; private int frontFace = GL11.GL_CCW; @Override public PolygonState set(PolygonState state) { this.frontMode = state.frontMode; this.backMode = state.backMode; this.offsetFactor = state.offsetFactor; this.offsetUnits = state.offsetUnits; this.cullFaceMode = state.cullFaceMode; this.frontFace = state.frontFace; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof PolygonState polygonState)) return false; return frontMode == polygonState.frontMode && backMode == polygonState.backMode && Float.compare(offsetFactor, polygonState.offsetFactor) == 0 && Float.compare(offsetUnits, polygonState.offsetUnits) == 0 && cullFaceMode == polygonState.cullFaceMode && frontFace == polygonState.frontFace; } @Override public PolygonState copy() { return new PolygonState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\StencilState.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; /** * Tracks GL stencil buffer state. * Corresponds to GL_STENCIL_BUFFER_BIT attributes. * Supports separate front/back state (GL 2.0 glStencilFuncSeparate, glStencilOpSeparate, glStencilMaskSeparate). */ @Getter @Setter public class StencilState implements ISettableState<StencilState> { // Front face state private int funcFront = GL11.GL_ALWAYS; private int refFront = 0; private int valueMaskFront = 0xFFFFFFFF; private int failOpFront = GL11.GL_KEEP; private int zFailOpFront = GL11.GL_KEEP; private int zPassOpFront = GL11.GL_KEEP; private int writeMaskFront = 0xFFFFFFFF; // Back face state (GL 2.0) private int funcBack = GL11.GL_ALWAYS; private int refBack = 0; private int valueMaskBack = 0xFFFFFFFF; private int failOpBack = GL11.GL_KEEP; private int zFailOpBack = GL11.GL_KEEP; private int zPassOpBack = GL11.GL_KEEP; private int writeMaskBack = 0xFFFFFFFF; // Clear value (shared) private int clearValue = 0; @Override public StencilState set(StencilState state) { this.funcFront = state.funcFront; this.refFront = state.refFront; this.valueMaskFront = state.valueMaskFront; this.failOpFront = state.failOpFront; this.zFailOpFront = state.zFailOpFront; this.zPassOpFront = state.zPassOpFront; this.writeMaskFront = state.writeMaskFront; this.funcBack = state.funcBack; this.refBack = state.refBack; this.valueMaskBack = state.valueMaskBack; this.failOpBack = state.failOpBack; this.zFailOpBack = state.zFailOpBack; this.zPassOpBack = state.zPassOpBack; this.writeMaskBack = state.writeMaskBack; this.clearValue = state.clearValue; return this; } /** * Set both front and back state at once (non-separate calls). */ public void setFunc(int func, int ref, int mask) { this.funcFront = func; this.refFront = ref; this.valueMaskFront = mask; this.funcBack = func; this.refBack = ref; this.valueMaskBack = mask; } /** * Set both front and back operations at once (non-separate calls). */ public void setOp(int fail, int zFail, int zPass) { this.failOpFront = fail; this.zFailOpFront = zFail; this.zPassOpFront = zPass; this.failOpBack = fail; this.zFailOpBack = zFail; this.zPassOpBack = zPass; } /** * Set both front and back write mask at once (non-separate calls). */ public void setWriteMask(int mask) { this.writeMaskFront = mask; this.writeMaskBack = mask; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof StencilState stencilState)) return false; return funcFront == stencilState.funcFront && refFront == stencilState.refFront && valueMaskFront == stencilState.valueMaskFront && failOpFront == stencilState.failOpFront && zFailOpFront == stencilState.zFailOpFront && zPassOpFront == stencilState.zPassOpFront && writeMaskFront == stencilState.writeMaskFront && funcBack == stencilState.funcBack && refBack == stencilState.refBack && valueMaskBack == stencilState.valueMaskBack && failOpBack == stencilState.failOpBack && zFailOpBack == stencilState.zFailOpBack && zPassOpBack == stencilState.zPassOpBack && writeMaskBack == stencilState.writeMaskBack && clearValue == stencilState.clearValue; } @Override public StencilState copy() { return new StencilState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\TextureBinding.java
package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; @Getter public class TextureBinding implements ISettableState<TextureBinding> { @Setter protected int binding; @Override public TextureBinding set(TextureBinding state) { this.binding = state.binding; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof TextureBinding textureBinding)) return false; return binding == textureBinding.binding; } @Override public TextureBinding copy() { return new TextureBinding().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\TextureUnitArray.java
package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.stacks.TextureUnitBooleanStateStack; import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack; import lombok.Getter; import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class TextureUnitArray { private final TextureBindingStack[] bindings; private final TextureUnitBooleanStateStack[] states; private final TextureUnitBooleanStateStack[] texture1DStates; private final TextureUnitBooleanStateStack[] texture3DStates; private final TextureUnitBooleanStateStack[] texGenSStates; private final TextureUnitBooleanStateStack[] texGenTStates; private final TextureUnitBooleanStateStack[] texGenRStates; private final TextureUnitBooleanStateStack[] texGenQStates; @Getter public final Matrix4fStack[] textureMatricies; public TextureUnitArray() { bindings = new TextureBindingStack[GLStateManager.MAX_TEXTURE_UNITS]; states = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texture1DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texture3DStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texGenSStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texGenTStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texGenRStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; texGenQStates = new TextureUnitBooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS]; textureMatricies = new Matrix4fStack[GLStateManager.MAX_TEXTURE_UNITS]; for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { bindings[i] = new TextureBindingStack(); states[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_2D, i); texture1DStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_1D, i); texture3DStates[i] = new TextureUnitBooleanStateStack(GL12.GL_TEXTURE_3D, i); texGenSStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_S, i); texGenTStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_T, i); texGenRStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_R, i); texGenQStates[i] = new TextureUnitBooleanStateStack(GL11.GL_TEXTURE_GEN_Q, i); textureMatricies[i] = new Matrix4fStack(GLStateManager.MAX_TEXTURE_STACK_DEPTH); } } public TextureBindingStack getTextureUnitBindings(int index) { return bindings[index]; } public TextureUnitBooleanStateStack getTextureUnitStates(int index) { return states[index]; } public TextureUnitBooleanStateStack getTexture1DStates(int index) { return texture1DStates[index]; } public TextureUnitBooleanStateStack getTexture3DStates(int index) { return texture3DStates[index]; } public TextureUnitBooleanStateStack getTexGenSStates(int index) { return texGenSStates[index]; } public TextureUnitBooleanStateStack getTexGenTStates(int index) { return texGenTStates[index]; } public TextureUnitBooleanStateStack getTexGenRStates(int index) { return texGenRStates[index]; } public TextureUnitBooleanStateStack getTexGenQStates(int index) { return texGenQStates[index]; } public Matrix4fStack getTextureUnitMatrix(int index) { return textureMatricies[index]; } @Override public boolean equals(Object state) { if (this == state) return true; if (!(state instanceof TextureUnitArray textureUnitArray)) return false; for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { if (!bindings[i].sameAs(textureUnitArray.bindings[i])) return false; if (!states[i].sameAs(textureUnitArray.states[i])) return false; if (!texture1DStates[i].sameAs(textureUnitArray.texture1DStates[i])) return false; if (!texture3DStates[i].sameAs(textureUnitArray.texture3DStates[i])) return false; if (!texGenSStates[i].sameAs(textureUnitArray.texGenSStates[i])) return false; if (!texGenTStates[i].sameAs(textureUnitArray.texGenTStates[i])) return false; if (!texGenRStates[i].sameAs(textureUnitArray.texGenRStates[i])) return false; if (!texGenQStates[i].sameAs(textureUnitArray.texGenQStates[i])) return false; } return true; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\states\ViewportState.java
package com.gtnewhorizons.angelica.glsm.states; import java.nio.IntBuffer; public class ViewportState implements ISettableState<ViewportState> { public int x; public int y; public int width; public int height; public void setViewPort(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void get(IntBuffer params) { params.put(0, x); params.put(1, y); params.put(2, width); params.put(3, height); } @Override public ViewportState set(ViewportState state) { this.x = state.x; this.y = state.y; this.width = state.width; this.height = state.height; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof ViewportState viewportState)) return false; return x == viewportState.x && y == viewportState.y && width == viewportState.width && height == viewportState.height; } @Override public ViewportState copy() { return new ViewportState().set(this); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\texture\TextureInfo.java
package com.gtnewhorizons.angelica.glsm.texture; import com.gtnewhorizons.angelica.glsm.RenderSystem; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; public class TextureInfo { @Getter protected final int id; protected int internalFormat = -1; protected int width = -1; protected int height = -1; @Getter @Setter protected int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR; @Getter @Setter protected int magFilter = GL11.GL_LINEAR; @Getter @Setter protected int wrapS = GL11.GL_REPEAT; @Getter @Setter protected int wrapT = GL11.GL_REPEAT; @Getter @Setter protected int maxLevel = 1000; @Getter @Setter protected int minLod = -1000; @Getter @Setter protected int maxLod = 1000; @Getter @Setter protected float lodBias = 0.0f; @Getter @Setter protected float maxAnisotropy = 1.0f; protected TextureInfo(int id) { this.id = id; } public int getInternalFormat() { if (internalFormat == -1) { internalFormat = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); } return internalFormat; } public int getWidth() { if (width == -1) { width = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_WIDTH); } return width; } public int getHeight() { if (height == -1) { height = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_HEIGHT); } return height; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\texture\TextureInfoCache.java
package com.gtnewhorizons.angelica.glsm.texture; import com.gtnewhorizons.angelica.glsm.GLStateManager; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import java.nio.Buffer; import java.util.concurrent.locks.ReentrantLock; public class TextureInfoCache { /** * Adapted from Iris for use in GLSM. * * This cache stores server-side texture state (parameters, dimensions) that is shared across GL contexts. * Locking is only used during splash when multiple contexts exist. */ public static final TextureInfoCache INSTANCE = new TextureInfoCache(); private final Int2ObjectMap<TextureInfo> cache = new Int2ObjectOpenHashMap<>(); private final ReentrantLock lock = new ReentrantLock(); private TextureInfoCache() { } public TextureInfo getInfo(int id) { if (id < 0) return null; if (GLStateManager.isSplashComplete()) { return cache.computeIfAbsent(id, TextureInfo::new); } lock.lock(); try { return cache.computeIfAbsent(id, TextureInfo::new); } finally { lock.unlock(); } } public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable Buffer pixels) { if (target == GL11.GL_TEXTURE_2D && level == 0) { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; info.internalFormat = internalformat; info.width = width; info.height = height; } } public void onTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, long pixels_buffer_offset) { if (target == GL11.GL_TEXTURE_2D && level == 0) { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; info.internalFormat = internalformat; info.width = width; info.height = height; } } public void onDeleteTexture(int id) { if (id < 0) return; if (GLStateManager.isSplashComplete()) { cache.remove(id); return; } // During splash: lock for thread safety lock.lock(); try { cache.remove(id); } finally { lock.unlock(); } } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\texture\TextureTracker.java
package com.gtnewhorizons.angelica.glsm.texture; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.renderer.texture.AbstractTexture; import org.jetbrains.annotations.Nullable; public class TextureTracker { /** * Adapted from Iris for use in GLSM */ public static final TextureTracker INSTANCE = new TextureTracker(); private static Runnable bindTextureListener; static { StateUpdateNotifiers.bindTextureNotifier = listener -> bindTextureListener = listener; } private final Int2ObjectMap<AbstractTexture> textures = new Int2ObjectOpenHashMap<>(); private boolean lockBindCallback; private TextureTracker() { } public void trackTexture(int id, AbstractTexture texture) { textures.put(id, texture); } @Nullable public AbstractTexture getTexture(int id) { return textures.get(id); } public void onBindTexture(int id) { if (lockBindCallback) { return; } if (GLStateManager.getActiveTextureUnit() == 0) { lockBindCallback = true; if (bindTextureListener != null) { bindTextureListener.run(); } if(Iris.enabled) { final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline != null) { pipeline.onBindTexture(id); } } // Reset texture state RenderSystem.bindTextureToUnit(0, id); lockBindCallback = false; } } public void onDeleteTexture(int id) { textures.remove(id); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\DisplayListCommand.java
package com.gtnewhorizons.angelica.glsm.recording.commands; /** * A single command recorded during display list compilation. * Commands are executed in sequence during glCallList() to replay the display list. */ public interface DisplayListCommand { /** * Execute this command by calling the appropriate GL function. */ void execute(); /** * Release any resources held by this command (e.g., VBOs). * Called when the display list is deleted. */ default void delete() { // Most commands don't hold resources } /** * Handle this command during display list optimization. * * <p>Commands override this to implement their optimization behavior: * <ul> * <li>Matrix transforms: accumulate into the optimizer, return false</li> * <li>Push/Pop: update stack, return true to emit</li> * <li>Barriers: emit pending transforms, return true to emit</li> * <li>State changes: return true to emit</li> * </ul> * * @param ctx The optimization context providing access to transform state * @return true if this command should be added to output, false if handled internally */ default boolean handleOptimization(OptimizationContext ctx) { return true; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\DrawCommand.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import com.github.bsideup.jabel.Desugar; /** * Represents a single draw call within a compiled display list. * Each DrawCommand corresponds to one glBegin/glEnd block. */ @Desugar public record DrawCommand( int firstVertex, int vertexCount, int primitiveType ) {}
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\DrawRangeCmd.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import org.jetbrains.annotations.NotNull; /** * Command: Draw a range of vertices from a shared VBO. * <p> * DrawRangeCmd references a shared VBO owned by CompiledDisplayList.ownedVbos. * Multiple DrawRangeCmds can reference different ranges within the same VBO, * enabling format-based batching where all draws with the same vertex format * share a single VBO. * <p> * Transform is NOT stored here - handled by TransformOptimizer emitting * MultMatrixCmd before this command during optimization. */ @Desugar public record DrawRangeCmd( VertexBuffer sharedVbo, int startVertex, int vertexCount, boolean hasBrightness ) implements DisplayListCommand { @Override public void execute() { sharedVbo.setupState(); sharedVbo.draw(startVertex, vertexCount); sharedVbo.cleanupState(); } @Override public void delete() { // No-op: VBO lifetime is managed by CompiledDisplayList.ownedVbos } @Override public @NotNull String toString() { return "DrawRange(start=" + startVertex + ", count=" + vertexCount + ", hasBrightness=" + hasBrightness + ")"; } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\MultMatrixCmd.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.jetbrains.annotations.NotNull; import org.joml.Matrix4f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; /** * Command: glMultMatrix(matrix) * Multiplies the current matrix by the specified matrix. */ @Desugar public record MultMatrixCmd(Matrix4f matrix, FloatBuffer buffer) implements DisplayListCommand { /** * Create a MultMatrixCmd with pre-allocated buffer. */ public static MultMatrixCmd create(Matrix4f matrix) { final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); matrix.get(buffer); buffer.rewind(); return new MultMatrixCmd(new Matrix4f(matrix), buffer); } @Override public void execute() { buffer.rewind(); GLStateManager.glMultMatrix(buffer); } @Override public @NotNull String toString() { return String.format("MultMatrix(%s)", matrix); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\OptimizationContext.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import org.joml.Matrix4f; /** * Context provided to commands during display list optimization. * Allows commands to interact with the transform optimizer and draw batcher. */ public interface OptimizationContext { /** Get the accumulated MODELVIEW transform matrix. */ Matrix4f getAccumulatedTransform(); /** Reset accumulated transform to identity. */ void loadIdentity(); /** Push current accumulated transform onto stack. */ void pushTransform(); /** Pop transform from stack, restoring previous accumulated value. */ void popTransform(); /** Emit a MultMatrix command if accumulated differs from last emitted. */ void emitPendingTransform(); /** Emit a MultMatrix command to reach the target transform. */ void emitTransformTo(Matrix4f target); /** Add a command to the output list. */ void emit(DisplayListCommand cmd); /** * Mark that the GL matrix is at an absolute value (after LoadMatrix). * Subsequent LoadIdentity commands must be emitted to reset to identity. */ void markAbsoluteMatrix(); /** * Check if the GL matrix is at an absolute value and clear the flag. * @return true if LoadMatrix was called and not yet reset by LoadIdentity */ boolean checkAndClearAbsoluteMatrix(); }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\TexImage2DCmd.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Command: glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels) * Specifies a two-dimensional texture image during display list playback. */ @Desugar public record TexImage2DCmd( int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable byte[] pixelData ) implements DisplayListCommand { /** * Create command from IntBuffer */ public static TexImage2DCmd fromIntBuffer(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable IntBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 4; // 4 bytes per int data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asIntBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexImage2DCmd(target, level, internalformat, width, height, border, format, type, data); } /** * Create command from FloatBuffer */ public static TexImage2DCmd fromFloatBuffer(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable FloatBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 4; // 4 bytes per float data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asFloatBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexImage2DCmd(target, level, internalformat, width, height, border, format, type, data); } /** * Create command from DoubleBuffer */ public static TexImage2DCmd fromDoubleBuffer(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable DoubleBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 8; // 8 bytes per double data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asDoubleBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexImage2DCmd(target, level, internalformat, width, height, border, format, type, data); } /** * Create command from ByteBuffer */ public static TexImage2DCmd fromByteBuffer(int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = limit - pos; data = new byte[size]; pixels.get(data); pixels.position(pos); // Restore position } return new TexImage2DCmd(target, level, internalformat, width, height, border, format, type, data); } @Override public void execute() { ByteBuffer buffer = null; if (pixelData != null) { buffer = ByteBuffer.allocateDirect(pixelData.length).order(ByteOrder.nativeOrder()); buffer.put(pixelData); buffer.flip(); } GLStateManager.glTexImage2D(target, level, internalformat, width, height, border, format, type, buffer); } @Override public @NotNull String toString() { String dataStr = pixelData != null ? (pixelData.length + " bytes") : "null"; return String.format("TexImage2D(target=%s, level=%d, internalformat=%s, %dx%d, border=%d, format=%s, type=%s, data=%s)", GLDebug.getTextureTargetName(target), level, GLDebug.getTextureFormatName(internalformat), width, height, border, GLDebug.getTextureFormatName(format), GLDebug.getDataTypeName(type), dataStr); } }
Angelica
src\main\java\com\gtnewhorizons\angelica\glsm\recording\commands\TexSubImage2DCmd.java
package com.gtnewhorizons.angelica.glsm.recording.commands; import com.github.bsideup.jabel.Desugar; import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Command: glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels) * Updates a portion of an existing two-dimensional texture image during display list playback. */ @Desugar public record TexSubImage2DCmd( int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, @Nullable byte[] pixelData ) implements DisplayListCommand { /** * Create command from IntBuffer */ public static TexSubImage2DCmd fromIntBuffer(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, @Nullable IntBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 4; // 4 bytes per int data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asIntBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexSubImage2DCmd(target, level, xoffset, yoffset, width, height, format, type, data); } /** * Create command from FloatBuffer */ public static TexSubImage2DCmd fromFloatBuffer(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, @Nullable FloatBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 4; // 4 bytes per float data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asFloatBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexSubImage2DCmd(target, level, xoffset, yoffset, width, height, format, type, data); } /** * Create command from DoubleBuffer */ public static TexSubImage2DCmd fromDoubleBuffer(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, @Nullable DoubleBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = (limit - pos) * 8; // 8 bytes per double data = new byte[size]; ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder()); bb.asDoubleBuffer().put(pixels); pixels.position(pos); // Restore position } return new TexSubImage2DCmd(target, level, xoffset, yoffset, width, height, format, type, data); } /** * Create command from ByteBuffer */ public static TexSubImage2DCmd fromByteBuffer(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, @Nullable ByteBuffer pixels) { byte[] data = null; if (pixels != null) { int pos = pixels.position(); int limit = pixels.limit(); int size = limit - pos; data = new byte[size]; pixels.get(data); pixels.position(pos); // Restore position } return new TexSubImage2DCmd(target, level, xoffset, yoffset, width, height, format, type, data); } @Override public void execute() { ByteBuffer buffer = null; if (pixelData != null) { buffer = ByteBuffer.allocateDirect(pixelData.length).order(ByteOrder.nativeOrder()); buffer.put(pixelData); buffer.flip(); } GLStateManager.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, buffer); } @Override public @NotNull String toString() { String dataStr = pixelData != null ? (pixelData.length + " bytes") : "null"; return String.format("TexSubImage2D(target=%s, level=%d, offset=(%d,%d), %dx%d, format=%s, type=%s, data=%s)", GLDebug.getTextureTargetName(target), level, xoffset, yoffset, width, height, GLDebug.getTextureFormatName(format), GLDebug.getDataTypeName(type), dataStr); } }