[vintage] Fix animated sprites not being tracked if fast block renderer is used #23

Merged
embeddedt merged 14 commits from karnatour/celeritas:stonecutter into stonecutter 2026-02-13 19:19:26 -05:00
489 changed files with 9311 additions and 10968 deletions
Showing only changes of commit 3ac83a6646 - Show all commits

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
# Used when a commit is pushed to the repository
# This makes use of caching for faster builds and uploads the resulting artifacts
name: ci
on: push
env:
CELERITAS_DISABLE_DECOMP: true
jobs:
build:
runs-on: ubuntu-large
steps:
- name: Checkout sources
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Set up JDK
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: |
8
17
21
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4.4.4
- name: Initialize Unimined caches
uses: actions/cache@v4
with:
path: |
**/.gradle/unimined
key: unimined-v4-${{ runner.os }}-build-snapshot-${{ hashFiles('settings.gradle.kts') }}
restore-keys: |
unimined-v4-${{ runner.os }}-build-snapshot-
- name: Build all packaged jars
run: ./gradlew packageJar --info --stacktrace
- name: Show checksums
run: find build/libs -name \*.jar | sort | xargs sha256sum
+7 -17
View File
@@ -19,10 +19,11 @@ env:
MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
MAVEN_SECRET: ${{ secrets.MAVEN_SECRET }} MAVEN_SECRET: ${{ secrets.MAVEN_SECRET }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
CELERITAS_DISABLE_DECOMP: true
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-large
steps: steps:
- name: Verify that release channel is available - name: Verify that release channel is available
@@ -40,27 +41,16 @@ jobs:
8 8
17 17
21 21
- name: Initialize caches - name: Setup Gradle
uses: actions/cache@v4 uses: gradle/actions/setup-gradle@v4.4.4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: release-${{ runner.os }}-build-snapshot-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('settings.gradle') }}
restore-keys: |
release-${{ runner.os }}-build-snapshot-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties') }}-
- name: Initialize Unimined caches - name: Initialize Unimined caches
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: | path: |
modern/versions/**/.gradle/unimined **/.gradle/unimined
forge1710/.gradle/unimined key: unimined-v4-${{ runner.os }}-build-snapshot-${{ hashFiles('settings.gradle.kts') }}
forge122/.gradle/unimined
babric/.gradle/unimined
key: unimined-v2-${{ runner.os }}-build-snapshot-${{ hashFiles('modern/build.gradle') }}-${{ hashFiles('settings.gradle.kts') }}
restore-keys: | restore-keys: |
unimined-v2-${{ runner.os }}-build-snapshot-${{ hashFiles('modern/build.gradle') }}- unimined-v4-${{ runner.os }}-build-snapshot-
unimined-v2-${{ runner.os }}-build-snapshot-
- name: Publish artifacts - name: Publish artifacts
if: ${{ inputs.release_type != 'DRY_RUN' }} if: ${{ inputs.release_type != 'DRY_RUN' }}
run: ./gradlew :taugradle_publish -Prelease_channel=${{ inputs.release_type }} --stacktrace run: ./gradlew :taugradle_publish -Prelease_channel=${{ inputs.release_type }} --stacktrace
-93
View File
@@ -1,93 +0,0 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.embeddedt.embeddium.gradle.build.conventions.LWJGLHelper
import org.embeddedt.embeddium.gradle.unimined.ProductionJarHelper
import xyz.wagyourtail.unimined.api.minecraft.EnvType
import xyz.wagyourtail.unimined.api.minecraft.task.AbstractRemapJarTask
import java.net.URI
plugins {
id("celeritas.platform-conventions")
id("celeritas-unimined-plugin")
id("xyz.wagyourtail.unimined") version "1.3.15-SNAPSHOT"
}
repositories {
maven("https://maven.fabricmc.net")
}
group = "org.embeddedt"
version = rootProject.version
evaluationDependsOn(":common")
data class VersionData(val uniminedVersion: String, val metadataURL: URI? = null)
val versionDataMap = mapOf(
"1.0.0-beta.7.3" to VersionData("b1.7.3"),
"1.0.0-beta.8.1" to VersionData( "b1.8.1"),
"1.2-alpha.125a" to VersionData("12w05a-1442", file("12w05a.json").toURI())
)
val isClientServerSplit = stonecutter.eval(project.name, "<1.3")
val featherVersion = if(isClientServerSplit) 23 else 28
val versionData = versionDataMap.getOrDefault(project.name, VersionData(project.name))
base.archivesName = "celeritas-fabriclike-mc${versionData.uniminedVersion.replace(Regex("^1\\."), "")}"
unimined.minecraft {
combineWith(project(":common"), project(":common").sourceSets.getByName("main"))
version = versionData.uniminedVersion
side = if(isClientServerSplit) EnvType.CLIENT else EnvType.COMBINED
if (versionData.metadataURL != null) {
minecraftData.metadataURL = versionData.metadataURL
}
mappings {
calamus()
feather(featherVersion)
}
fabric {
loader("0.16.14")
}
minecraftRemapper.config {
ignoreConflicts(true)
}
runs.config("client") {
javaVersion = JavaVersion.VERSION_21
}
if (!isClientServerSplit) {
runs.config("server") {
enabled = false
}
}
}
dependencies {
implementation("org.joml:joml:1.10.5")
shadow("org.joml:joml:1.10.5")
implementation("it.unimi.dsi:fastutil:8.5.15")
implementation("org.apache.logging.log4j:log4j-api:2.0-beta9")
}
val remapJar = tasks.named<AbstractRemapJarTask>("remapJar") {
manifest {
attributes(mapOf("Calamus-Generation" to "1"))
}
}
ProductionJarHelper.createShadowRemapJar(project)
LWJGLHelper.convertLwjgl2To3(project)
ProductionJarHelper.configureProcessedResources(project)
tasks.register("packageJar", Copy::class) {
from(tasks.named<ShadowJar>("shadowRemapJar").get().archiveFile)
into("${rootProject.layout.buildDirectory.get()}/libs/${project.version}")
}
+1 -1
View File
@@ -74,7 +74,7 @@ val publishTask = tau.publishing.publish {
minecraftVersionRange = bs.ModLoader.getMinecraftVersion(name) minecraftVersionRange = bs.ModLoader.getMinecraftVersion(name)
javaVersions.add(JavaVersion.VERSION_21) javaVersions.add(JavaVersion.VERSION_21)
environment = ModEnvironment.CLIENT_ONLY environment.set(ModEnvironment.CLIENT_ONLY)
modLoaders.add(when(ourLoader) { modLoaders.add(when(ourLoader) {
bs.ModLoader.FABRIC -> ModLoader.FABRIC bs.ModLoader.FABRIC -> ModLoader.FABRIC
+14 -5
View File
@@ -11,15 +11,24 @@ dependencies {
implementation("org.ow2.asm:asm-commons:9.6") implementation("org.ow2.asm:asm-commons:9.6")
implementation("com.google.code.gson:gson:2.10.1") implementation("com.google.code.gson:gson:2.10.1")
implementation("org.apache.commons:commons-compress:1.26.0") implementation("org.apache.commons:commons-compress:1.26.0")
implementation("com.gradleup.shadow:shadow-gradle-plugin:8.3.0") implementation("com.gradleup.shadow:shadow-gradle-plugin:9.3.0")
implementation("dev.kikugie:stonecutter:0.7-beta.2") implementation("dev.kikugie:stonecutter:0.7.11")
} }
repositories { repositories {
mavenCentral() mavenCentral()
maven("https://maven.fabricmc.net/") exclusiveContent {
maven("https://maven.kikugie.dev/releases") forRepository { maven("https://maven.fabricmc.net/") }
maven("https://maven.kikugie.dev/snapshots") filter {
includeGroupAndSubgroups("net.fabricmc")
}
}
exclusiveContent {
forRepository { maven("https://maven.kikugie.dev/releases") }
filter {
includeGroup("dev.kikugie")
}
}
} }
gradlePlugin { gradlePlugin {
@@ -16,9 +16,14 @@ public class LWJGLHelper {
); );
public static void convertLwjgl2To3(Project project) { public static void convertLwjgl2To3(Project project) {
project.getConfigurations().getByName("minecraftLibraries").getDependencies().removeIf(dep -> Objects.equals(dep.getGroup(), "org.lwjgl.lwjgl")); convertLwjgl2To3(project, "minecraftLibraries");
project.getDependencies().add("minecraftLibraries", "org.taumc:legacy-lwjgl3:1.2-tau"); }
addLwjgl3(project, "minecraftLibraries");
public static void convertLwjgl2To3(Project project, String minecraftLibsConfigurationName) {
project.getConfigurations().getByName(minecraftLibsConfigurationName).getDependencies().removeIf(dep -> Objects.equals(dep.getGroup(), "org.lwjgl.lwjgl"));
String legacyLwjgl3Version = Objects.requireNonNull(project.getProperties().get("legacy_lwjgl3_version"), "legacy_lwjgl3_version not specified").toString();
project.getDependencies().add(minecraftLibsConfigurationName, "org.taumc:legacy-lwjgl3:" + legacyLwjgl3Version);
addLwjgl3(project, minecraftLibsConfigurationName);
} }
public static void addLwjgl3(Project project) { public static void addLwjgl3(Project project) {
@@ -31,6 +36,7 @@ public class LWJGLHelper {
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION); deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION);
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "linux"); deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "linux");
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "windows"); deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "windows");
deps.add(configurationName, "org.lwjgl:" + component + ":" + LWJGL3_VERSION + ":natives-" + "macos-arm64");
} }
} }
} }
@@ -0,0 +1,19 @@
package org.embeddedt.embeddium.gradle.build.conventions;
/**
* Taken from GTNHGradle
*/
public class RFBArgs {
public static final String[] JAVA_17_ARGS = new String[] { "-Dfile.encoding=UTF-8",
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader",
"-Djava.security.manager=allow", "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", "--add-opens",
"java.base/java.net=ALL-UNNAMED", "--add-opens", "java.base/java.nio=ALL-UNNAMED", "--add-opens",
"java.base/java.io=ALL-UNNAMED", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens",
"java.base/java.lang.reflect=ALL-UNNAMED", "--add-opens", "java.base/java.text=ALL-UNNAMED", "--add-opens",
"java.base/java.util=ALL-UNNAMED", "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED", "--add-opens",
"java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming",
"--add-opens", "java.desktop/sun.awt=ALL-UNNAMED", "--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED",
"--add-opens", "java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED", "--add-opens",
"jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED", "--add-opens",
"java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED", };
}
@@ -0,0 +1,31 @@
package org.embeddedt.embeddium.gradle.build.conventions;
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar;
import org.gradle.api.Project;
import org.gradle.jvm.tasks.Jar;
import java.util.List;
public class ShadowHelper {
public static void createShadowRemapJar(Project project) {
createShadowRemapJar(project, "remapJar");
}
public static void createShadowRemapJar(Project project, String remapJarTaskName) {
project.getTasks().named("shadowJar").configure(task -> {
if (task instanceof ShadowJar shadowJar) {
shadowJar.getConfigurations().set(List.of());
}
});
project.getTasks().register("shadowRemapJar", ShadowJar.class).configure(shadowJar -> {
shadowJar.getArchiveClassifier().set("");
shadowJar.getConfigurations().set(List.of(project.getConfigurations().getByName("shadow")));
shadowJar.from(project.zipTree(((Jar)project.getTasks().named(remapJarTaskName).get()).getArchiveFile()));
shadowJar.getManifest().inheritFrom(((Jar)project.getTasks().getByName("jar")).getManifest());
shadowJar.relocate("org.joml", "org.embeddedt.embeddium.impl.shadow.joml");
shadowJar.mergeServiceFiles();
shadowJar.from("COPYING", "COPYING.LESSER", "README.md");
});
}
}
@@ -115,8 +115,9 @@ repositories {
} }
dependencies { dependencies {
compileOnly("org.projectlombok:lombok:1.18.30") val lombokVersion = rootProject.properties["lombok_version"].toString()
annotationProcessor("org.projectlombok:lombok:1.18.30") compileOnly("org.projectlombok:lombok:${lombokVersion}")
annotationProcessor("org.projectlombok:lombok:${lombokVersion}")
compileOnly("com.google.code.findbugs:jsr305:3.0.2") compileOnly("com.google.code.findbugs:jsr305:3.0.2")
} }
@@ -125,16 +126,16 @@ tasks.withType<AbstractArchiveTask>().configureEach {
isReproducibleFileOrder = true isReproducibleFileOrder = true
} }
val modLoader = ModLoader.fromProject(project) val modLoader: ModLoader? = ModLoader.fromProject(project)
val minecraftVersion = ModLoader.getMinecraftVersion(project) val minecraftVersion = ModLoader.getMinecraftVersion(project)
val stonecutterExt = project.extensions.getByType<StonecutterBuildExtension>() val stonecutterExt = project.extensions.findByType<StonecutterBuildExtension>()
val modMixinConfigs = mutableListOf("embeddium.mixins.json") val modMixinConfigs = mutableListOf("embeddium.mixins.json")
project.extra.set("celeritasMixinConfigs", modMixinConfigs) project.extra.set("celeritasMixinConfigs", modMixinConfigs)
if (generateSequence(project) { it.parent }.any { it.name == "modern" }) { if (generateSequence(project) { it.parent }.any { it.name == "modern" }) {
if (stonecutterExt.constants.getOrDefault("settings_gui", false)) { if (stonecutterExt?.constants?.getOrDefault("settings_gui", false) ?: false) {
sourceSets { sourceSets {
main { main {
java.srcDir("src/main/gui_java") java.srcDir("src/main/gui_java")
@@ -144,18 +145,10 @@ if (generateSequence(project) { it.parent }.any { it.name == "modern" }) {
} }
tasks.named<ProcessResources>("processResources") { tasks.named<ProcessResources>("processResources") {
val mixinCompatLevel = if (stonecutterExt.eval(minecraftVersion, "<1.17")) { val inputProps = mutableMapOf(
"JAVA_8"
} else if (stonecutterExt.eval(minecraftVersion, "<1.18")) {
"JAVA_16"
} else {
"JAVA_17"
}
val inputProps = mapOf(
"forgeid" to if (modLoader == ModLoader.NEOFORGE) "neoforge" else "forge", "forgeid" to if (modLoader == ModLoader.NEOFORGE) "neoforge" else "forge",
"minecraft" to (versionedProperty("minecraft_dependency") ?: ""), "minecraft" to (versionedProperty("minecraft_dependency") ?: ""),
"mod_version" to version, "mod_version" to version,
"mixinCompatLevel" to mixinCompatLevel,
"mod_id" to rootProject.property("mod_id"), "mod_id" to rootProject.property("mod_id"),
"mod_display_name" to rootProject.property("mod_display_name"), "mod_display_name" to rootProject.property("mod_display_name"),
"mod_description" to rootProject.property("mod_description"), "mod_description" to rootProject.property("mod_description"),
@@ -169,11 +162,22 @@ tasks.named<ProcessResources>("processResources") {
"fabric_api_modules" to rootProject.property("fabric_api_modules") "fabric_api_modules" to rootProject.property("fabric_api_modules")
) )
stonecutterExt?.let {
val mixinCompatLevel = if (it.eval(minecraftVersion, "<1.17")) {
"JAVA_8"
} else if (it.eval(minecraftVersion, "<1.18")) {
"JAVA_16"
} else {
"JAVA_17"
}
inputProps.put("mixinCompatLevel", mixinCompatLevel)
}
inputProps.forEach { (key, value) -> inputProps.forEach { (key, value) ->
inputs.property(key, value) inputs.property(key, value)
} }
filesMatching(listOf("fabric.mod.json", "META-INF/mods.toml", "quilt.mod.json", "embeddium.mixins.json")) { filesMatching(listOf("fabric.mod.json", "META-INF/mods.toml", "META-INF/neoforge.mods.toml", "quilt.mod.json", "embeddium.mixins.json")) {
expand(inputProps) expand(inputProps)
} }
@@ -0,0 +1,382 @@
package org.embeddedt.embeddium.gradle.task
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.tasks.*
import org.objectweb.asm.ClassReader
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
import java.io.File
import java.util.jar.JarFile
const val LWJGL_ABSTRACTION_PACKAGE = "org.taumc.celeritas.lwjgl"
enum class LWJGLVersion(val version: Int) {
TWO(2),
THREE(3);
}
abstract class GenerateLWJGLAbstraction : DefaultTask() {
@get:InputFiles
@get:Classpath
abstract val lwjgl2Classpath: ConfigurableFileCollection
@get:InputFiles
@get:Classpath
abstract val lwjgl3Classpath: ConfigurableFileCollection
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
data class GLMethod(
val returnType: String,
val name: String,
val params: List<Pair<String, String>>
) {
fun signature(): String = "$name(${params.joinToString(",") { it.first }})$returnType"
}
data class GLConstant(
val name: String,
val type: String,
val value: Any
)
class GLClassData {
val methods = mutableSetOf<GLMethod>();
val constants = mutableSetOf<GLConstant>();
}
@TaskAction
fun generate() {
val outputDir = outputDirectory.get().asFile
outputDir.mkdirs()
// GL version classes to process
val glVersions = mapOf(
"11" to "org/lwjgl/opengl/GL11",
"12" to "org/lwjgl/opengl/GL12",
"13" to "org/lwjgl/opengl/GL13",
"14" to "org/lwjgl/opengl/GL14",
"15" to "org/lwjgl/opengl/GL15",
"20" to "org/lwjgl/opengl/GL20",
"21" to "org/lwjgl/opengl/GL21",
"30" to "org/lwjgl/opengl/GL30",
"31" to "org/lwjgl/opengl/GL31",
"32" to "org/lwjgl/opengl/GL32",
"33" to "org/lwjgl/opengl/GL33",
"40" to "org/lwjgl/opengl/GL40",
"41" to "org/lwjgl/opengl/GL41",
"42" to "org/lwjgl/opengl/GL42",
"43" to "org/lwjgl/opengl/GL43",
"44" to "org/lwjgl/opengl/GL44",
"45" to "org/lwjgl/opengl/GL45",
"46" to "org/lwjgl/opengl/GL46"
)
val allMethods = mutableMapOf<String, GLClassData>()
glVersions.forEach { (version, classPath) ->
val methods = extractGLMethods(classPath, lwjgl3Classpath.files)
allMethods[version] = methods
logger.info("Extracted ${methods.methods.size} methods from GL$version")
}
filterValidGLMethods(allMethods, glVersions, lwjgl2Classpath.files)
// Generate LWJGLService interface
generateLWJGLServiceInterface(outputDir, allMethods)
// Generate LWJGLService implementations
for (version in LWJGLVersion.entries) {
generateLWJGLBackingService(outputDir, version, allMethods, glVersions)
}
// Generate GLXY wrapper classes
glVersions.keys.forEach { version ->
val methods = allMethods[version] ?: GLClassData()
generateGLWrapper(outputDir, version, methods)
}
logger.lifecycle("Generated LWJGL abstraction layer in ${outputDir.absolutePath}")
}
private fun isGLMethod(method: MethodNode): Boolean {
val isStatic = (method.access and Opcodes.ACC_STATIC) != 0
val isPublic = (method.access and Opcodes.ACC_PUBLIC) != 0
return (isStatic && isPublic && method.name.startsWith("gl"))
}
private fun extractGLMethods(classPath: String, classpathFiles: Set<File>): GLClassData {
val data = GLClassData()
for (file in classpathFiles) {
if (!file.exists() || !file.name.endsWith(".jar")) continue
try {
JarFile(file).use { jar ->
val entry = jar.getJarEntry("$classPath.class") ?: continue
jar.getInputStream(entry).use { stream ->
val classReader = ClassReader(stream)
val classNode = ClassNode()
classReader.accept(classNode, 0)
classNode.fields.forEach { field ->
val isStatic = (field.access and Opcodes.ACC_STATIC) != 0
val isFinal = (field.access and Opcodes.ACC_FINAL) != 0
val isPublic = (field.access and Opcodes.ACC_PUBLIC) != 0
if (isStatic && isFinal && isPublic && field.value != null) {
val type = Type.getType(field.desc)
val javaType = asmTypeToJavaType(type)
data.constants.add(GLConstant(
name = field.name,
type = javaType,
value = field.value
))
}
}
classNode.methods.filter { isGLMethod(it) }.forEach { method ->
val methodType = Type.getMethodType(method.desc)
val paramTypes = methodType.argumentTypes.map { asmTypeToJavaType(it) }
if (paramTypes.any { it.startsWith("org.lwjgl.") }) {
// Do not emit overloads that require LWJGL class references
return@forEach
}
val returnType = asmTypeToJavaType(methodType.returnType)
// Try to get parameter names from bytecode
val paramNames = mutableListOf<String>()
// First try MethodParameters attribute (Java 8+ with -parameters flag)
if (method.parameters != null && method.parameters.isNotEmpty()) {
method.parameters.forEach { param ->
paramNames.add(param.name)
}
}
// Fall back to LocalVariableTable if available
else if (method.localVariables != null && method.localVariables.isNotEmpty()) {
// For static methods, local variables start at index 0
// Sort by index and skip synthetic/internal variables
method.localVariables
.filter { it.index < paramTypes.size }
.sortedBy { it.index }
.forEach { localVar ->
if (paramNames.size < paramTypes.size) {
paramNames.add(localVar.name)
}
}
}
// Ensure we have enough parameter names
while (paramNames.size < paramTypes.size) {
paramNames.add("param${paramNames.size}")
}
val params = paramTypes.mapIndexed { idx, type ->
type to paramNames[idx]
}
data.methods.add(GLMethod(
returnType = returnType,
name = method.name,
params = params
))
}
}
if (data.methods.isNotEmpty()) break
}
} catch (e: Exception) {
logger.warn("Could not read class $classPath from ${file.name}: ${e.message}")
}
}
return data
}
private fun filterValidGLMethods(allMethods: MutableMap<String, GLClassData>, glVersions: Map<String, String>, classpathFiles: Set<File>) {
val lwjgl2Signatures = mutableSetOf<String>()
for (file in classpathFiles) {
if (!file.exists() || !file.name.endsWith(".jar")) continue
JarFile(file).use { jar ->
allMethods.forEach { (version, _) ->
val classBinaryName = glVersions[version]
val entry = jar.getJarEntry("$classBinaryName.class") ?: return@forEach
jar.getInputStream(entry).use { stream ->
val classReader = ClassReader(stream)
val classNode = ClassNode()
classReader.accept(classNode, 0)
classNode.methods.filter { isGLMethod(it) }.forEach { method ->
val methodType = Type.getMethodType(method.desc)
val paramTypes = methodType.argumentTypes.map { asmTypeToJavaType(it) }
val paramNames = mutableListOf<String>()
while (paramNames.size < paramTypes.size) {
paramNames.add("param${paramNames.size}")
}
val returnType = asmTypeToJavaType(methodType.returnType)
val params = paramTypes.mapIndexed { idx, type ->
type to paramNames[idx]
}
lwjgl2Signatures.add(GLMethod(name = method.name, returnType = returnType, params = params).signature())
}
}
}
}
}
allMethods.forEach { (version, methodSet) ->
val oldSize = methodSet.methods.size
methodSet.methods.removeIf { !lwjgl2Signatures.contains(it.signature()) }
val newSize = methodSet.methods.size
if (newSize < oldSize) {
logger.info("Removed {} methods from GL{} that don't exist in LWJGL2", oldSize - newSize, version)
}
}
}
private fun asmTypeToJavaType(type: Type): String {
return when (type.sort) {
Type.VOID -> "void"
Type.BOOLEAN -> "boolean"
Type.CHAR -> "char"
Type.BYTE -> "byte"
Type.SHORT -> "short"
Type.INT -> "int"
Type.FLOAT -> "float"
Type.LONG -> "long"
Type.DOUBLE -> "double"
Type.ARRAY -> asmTypeToJavaType(type.elementType) + "[]".repeat(type.dimensions)
Type.OBJECT -> type.className
else -> type.className
}
}
private fun getOutputDir(outputDir: File, group: String): File {
return File(outputDir, group + File.separatorChar + LWJGL_ABSTRACTION_PACKAGE.replace('.', File.separatorChar))
}
private fun generateLWJGLServiceInterface(outputDir: File, allMethods: Map<String, GLClassData>) {
val packageDir = getOutputDir(outputDir, "main")
packageDir.mkdirs()
val serviceFile = File(packageDir, "LWJGLService.java")
val allUniqueMethods = allMethods.values.map { it.methods }.flatten().distinctBy { it.signature() }
serviceFile.writeText("""
package ${LWJGL_ABSTRACTION_PACKAGE};
public interface LWJGLService {
LWJGLService INSTANCE = createInstance();
static LWJGLService constructInstance(String className) {
try {
var clz = Class.forName(className);
return (LWJGLService)clz.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
static LWJGLService createInstance() {
try {
Class.forName("org.lwjgl.opengl.GL11");
return constructInstance("${LWJGL_ABSTRACTION_PACKAGE}.LWJGL2Service");
} catch (ClassNotFoundException e) {
return constructInstance("${LWJGL_ABSTRACTION_PACKAGE}.LWJGL3Service");
}
}
${allUniqueMethods.joinToString("\n\n") { method ->
val params = method.params.joinToString(", ") { "${it.first} ${it.second}" }
" ${method.returnType} ${method.name}($params);"
}}
}
""".trimIndent())
}
private fun generateLWJGLBackingService(outputDir: File, version: LWJGLVersion, allMethods: Map<String, GLClassData>, glVersions: Map<String, String>) {
val packageDir = getOutputDir(outputDir, "lwjgl" + version.version)
packageDir.mkdirs()
val serviceFile = File(packageDir, "LWJGL${version.version}Service.java")
// Create a map of methods to their GL class
val methodToClass = mutableMapOf<String, String>()
glVersions.forEach { (version, _) ->
allMethods[version]?.methods?.forEach { method ->
if (!methodToClass.containsKey(method.signature())) {
methodToClass[method.signature()] = version
}
}
}
val allUniqueMethods = allMethods.values.map { it.methods }.flatten().distinctBy { it.signature() }
serviceFile.writeText("""
package ${LWJGL_ABSTRACTION_PACKAGE};
class LWJGL${version.version}Service implements LWJGLService {
${allUniqueMethods.joinToString("\n\n") { method ->
val params = method.params.joinToString(", ") { "${it.first} ${it.second}" }
val paramNames = method.params.joinToString(", ") { it.second }
val returnStmt = if (method.returnType == "void") "" else "return "
val glVersion = methodToClass[method.signature()] ?: "11"
""" @Override
public ${method.returnType} ${method.name}($params) {
${returnStmt}org.lwjgl.opengl.GL${glVersion}.${method.name}($paramNames);
}"""
}}
}
""".trimIndent())
}
private fun generateGLWrapper(outputDir: File, version: String, classData: GLClassData) {
val packageDir = getOutputDir(outputDir, "main")
packageDir.mkdirs()
val className = "GL$version"
val wrapperFile = File(packageDir, "$className.java")
wrapperFile.writeText("""
package ${LWJGL_ABSTRACTION_PACKAGE};
public class $className {
private static final LWJGLService service = LWJGLService.INSTANCE;
${classData.constants.joinToString("\n\n") { constant ->
" public static final ${constant.type} ${constant.name} = ${constant.value};"
}}
${classData.methods.joinToString("\n\n") { method ->
val params = method.params.joinToString(", ") { "${it.first} ${it.second}" }
val paramNames = method.params.joinToString(", ") { it.second }
val returnStmt = if (method.returnType == "void") "" else "return "
""" public static ${method.returnType} ${method.name}($params) {
${returnStmt}service.${method.name}($paramNames);
}"""
}}
}
""".trimIndent())
}
}
+64 -3
View File
@@ -1,3 +1,5 @@
import org.embeddedt.embeddium.gradle.task.GenerateLWJGLAbstraction
plugins { plugins {
id 'java-library' id 'java-library'
id 'maven-publish' id 'maven-publish'
@@ -16,15 +18,56 @@ repositories {
mavenCentral() mavenCentral()
} }
def generatedSourcesDir = layout.buildDirectory.dir("generated/sources/lwjgl-abstraction/java")
sourceSets {
lwjglCommon {
java.srcDir(generatedSourcesDir.map { it.dir("main") })
}
lwjgl2 {
java.srcDir(generatedSourcesDir.map { it.dir("lwjgl2") })
compileClasspath += main.compileClasspath
compileClasspath += lwjglCommon.output
}
lwjgl3 {
java.srcDir(generatedSourcesDir.map { it.dir("lwjgl3") })
compileClasspath += main.compileClasspath
compileClasspath += lwjglCommon.output
}
main {
compileClasspath += lwjglCommon.output
}
}
def generateAbstractionLayer = tasks.register("generateLWJGLAbstraction", GenerateLWJGLAbstraction) {
lwjgl2Classpath.from(configurations.named("lwjgl2CompileClasspath"))
lwjgl3Classpath.from(configurations.named("lwjgl3CompileClasspath"))
outputDirectory.set(generatedSourcesDir)
}
tasks.named("compileLwjglCommonJava") {
dependsOn(generateAbstractionLayer)
}
def compileAgainstLwjgl = true
dependencies { dependencies {
def lwjglVersion = "3.3.1" def lwjglVersion = "3.3.1"
def lwjglNatives = "natives-linux" def lwjgl2Version = "2.9.3"
lwjgl3CompileOnly(platform("org.lwjgl:lwjgl-bom:$lwjglVersion"))
lwjgl3CompileOnly "org.lwjgl:lwjgl"
lwjgl3CompileOnly "org.lwjgl:lwjgl-opengl"
lwjgl2CompileOnly("org.lwjgl.lwjgl:lwjgl:$lwjgl2Version")
if (compileAgainstLwjgl) {
// TODO Completely remove direct dependency on LWJGL3
implementation(platform("org.lwjgl:lwjgl-bom:$lwjglVersion")) implementation(platform("org.lwjgl:lwjgl-bom:$lwjglVersion"))
implementation "org.lwjgl:lwjgl" implementation "org.lwjgl:lwjgl"
implementation "org.lwjgl:lwjgl-opengl" implementation "org.lwjgl:lwjgl-opengl"
runtimeOnly(group: "org.lwjgl", name: "lwjgl", classifier: lwjglNatives) }
runtimeOnly(group: "org.lwjgl", name: "lwjgl-opengl", classifier: lwjglNatives)
implementation "org.joml:joml:1.10.5" implementation "org.joml:joml:1.10.5"
implementation "it.unimi.dsi:fastutil:7.1.0" implementation "it.unimi.dsi:fastutil:7.1.0"
implementation "org.apache.logging.log4j:log4j-api:2.0-beta9" implementation "org.apache.logging.log4j:log4j-api:2.0-beta9"
@@ -35,6 +78,8 @@ dependencies {
implementation("org.ow2.asm:asm-tree:9.6") implementation("org.ow2.asm:asm-tree:9.6")
implementation("org.ow2.asm:asm-util:9.6") implementation("org.ow2.asm:asm-util:9.6")
implementation "com.google.code.gson:gson:2.10.1"
testImplementation 'org.junit.jupiter:junit-jupiter:5.13.0' testImplementation 'org.junit.jupiter:junit-jupiter:5.13.0'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
} }
@@ -77,9 +122,25 @@ tasks.withType(Jar).configureEach {
} }
jar { jar {
from(sourceSets.lwjglCommon.output)
from(sourceSets.lwjgl2.output)
from(sourceSets.lwjgl3.output)
manifest { manifest {
attributes([ attributes([
"Lwjgl3ify-Aware": "true" "Lwjgl3ify-Aware": "true"
]) ])
} }
} }
// make RFG stop complaining
def obfAttr = Attribute.of("com.gtnewhorizons.retrofuturagradle.obfuscation", String)
def transformedAttr = Attribute.of("rfgDeobfuscatorTransformed", Boolean)
configurations {
runtimeElements {
attributes {
attribute(obfAttr, "mcp")
attribute(transformedAttr, true)
}
}
}
@@ -52,7 +52,7 @@ public class NormI8 {
*/ */
private static int encode(float comp) { private static int encode(float comp) {
// TODO: is the clamp necessary here? our inputs should always be normalized vector components // TODO: is the clamp necessary here? our inputs should always be normalized vector components
return ((int) (Math.clamp(comp, -1.0F, 1.0F) * COMPONENT_RANGE) & 255); return ((int) (Math.clamp(-1.0F, 1.0F, comp) * COMPONENT_RANGE) & 255);
} }
/** /**
@@ -33,4 +33,8 @@ public class MathUtil {
public static int clamp(int value, int min, int max) { public static int clamp(int value, int min, int max) {
return Math.min(Math.max(value, min), max); return Math.min(Math.max(value, min), max);
} }
public static boolean roughlyEqual(float a, float b) {
return Math.abs(b - a) < 0.00001f;
}
} }
@@ -1,15 +1,23 @@
package org.embeddedt.embeddium.impl.gl.arena; package org.embeddedt.embeddium.impl.gl.arena;
import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.common.util.NativeBuffer;
import org.jetbrains.annotations.Nullable;
public class PendingUpload { public class PendingUpload {
private final NativeBuffer data; private final NativeBuffer data;
private GlBufferSegment result; private GlBufferSegment result;
public PendingUpload(NativeBuffer data) { private PendingUpload(NativeBuffer data) {
this.data = data; this.data = data;
} }
public static @Nullable PendingUpload of(@Nullable NativeBuffer data) {
if (data == null) {
return null;
}
return new PendingUpload(data);
}
public NativeBuffer getDataBuffer() { public NativeBuffer getDataBuffer() {
return this.data; return this.data;
} }
@@ -5,6 +5,8 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayFIFOQueue;
import org.embeddedt.embeddium.impl.gl.buffer.*; import org.embeddedt.embeddium.impl.gl.buffer.*;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.functions.BufferCopyFunctions;
import org.embeddedt.embeddium.impl.gl.functions.BufferMapRangeFunctions;
import org.embeddedt.embeddium.impl.gl.functions.BufferStorageFunctions; import org.embeddedt.embeddium.impl.gl.functions.BufferStorageFunctions;
import org.embeddedt.embeddium.impl.gl.sync.GlFence; import org.embeddedt.embeddium.impl.gl.sync.GlFence;
import org.embeddedt.embeddium.impl.gl.util.EnumBitField; import org.embeddedt.embeddium.impl.gl.util.EnumBitField;
@@ -48,7 +50,10 @@ public class MappedStagingBuffer implements StagingBuffer {
} }
public static boolean isSupported(RenderDevice instance) { public static boolean isSupported(RenderDevice instance) {
return instance.getDeviceFunctions().getBufferStorageFunctions() != BufferStorageFunctions.NONE; var functions = instance.getDeviceFunctions();
return functions.bufferStorageFunctions() != BufferStorageFunctions.NONE
&& functions.bufferCopyFunctions() != BufferCopyFunctions.PIXEL_PACK
&& functions.bufferMapRangeFunctions() == BufferMapRangeFunctions.CORE;
} }
@Override @Override
@@ -0,0 +1,82 @@
package org.embeddedt.embeddium.impl.gl.array;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.JNI;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.NativeType;
import java.nio.IntBuffer;
import static org.lwjgl.system.MemoryStack.stackGet;
import static org.lwjgl.system.MemoryUtil.memAddress;
/**
* Native bindings to the <a href="https://registry.khronos.org/OpenGL/extensions/APPLE/APPLE_vertex_array_object.txt">APPLE_vertex_array_object</a> extension.
* <p>This extension introduces named vertex array objects which encapsulate vertex array state on the client side.
* The main purpose of these objects is to keep pointers to static vertex data and provide a name for different sets of static vertex data.</p>
*
* <p>By extending vertex array range functionality this extension allows multiple vertex array ranges to exist at one time,
* including their complete sets of state, in manner analogous to texture objects.</p>
*
* <p>GenVertexArraysAPPLE creates a list of n number of vertex array object names. After creating a name,
* BindVertexArrayAPPLE associates the name with a vertex array object and selects this vertex array and its associated state as current.
* To get back to the default vertex array and its associated state the client should bind to vertex array named 0.</p>
*
* <p>Once a client is done using a vertex array object it can be deleted with DeleteVertexArraysAPPLE.
* The client is responsible for allocating and deallocating the memory used by the vertex array data,
* while the DeleteVertexArraysAPPLE command deletes vertex array object names and associated state only.</p>
*/
public class APPLEVertexArrayObject {
private static final long bindVertexArray = GL.getFunctionProvider().getFunctionAddress("glBindVertexArrayAPPLE");
private static final long deleteVertexArrays = GL.getFunctionProvider().getFunctionAddress("glDeleteVertexArraysAPPLE");
private static final long genVertexArrays = GL.getFunctionProvider().getFunctionAddress("glGenVertexArraysAPPLE");
private static final long isVertexArray = GL.getFunctionProvider().getFunctionAddress("glIsVertexArrayAPPLE");
public static final boolean supported = bindVertexArray != 0;
public static void glBindVertexArrayAPPLE(@NativeType("GLuint") int array) {
JNI.callV(array, bindVertexArray);
}
public static void nglDeleteVertexArraysAPPLE(int n, long arrays) {
JNI.callPV(n, arrays, deleteVertexArrays);
}
public static void glDeleteVertexArraysAPPLE(@NativeType("GLuint const *") IntBuffer arrays) {
nglDeleteVertexArraysAPPLE(arrays.remaining(), memAddress(arrays));
}
public static void glDeleteVertexArraysAPPLE(@NativeType("GLuint const *") int array) {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
IntBuffer arrays = stack.callocInt(1);
arrays.put(0, array);
nglDeleteVertexArraysAPPLE(1, memAddress(arrays));
} finally {
stack.setPointer(stackPointer);
}
}
public static void nglGenVertexArraysAPPLE(int n, long arrays) {
JNI.callPV(n, arrays, genVertexArrays);
}
public static void glGenVertexArraysAPPLE(@NativeType("GLuint *") IntBuffer arrays) {
nglGenVertexArraysAPPLE(arrays.remaining(), memAddress(arrays));
}
public static int glGenVertexArraysAPPLE() {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
IntBuffer arrays = stack.callocInt(1);
nglGenVertexArraysAPPLE(1, memAddress(arrays));
return arrays.get(0);
} finally {
stack.setPointer(stackPointer);
}
}
public static boolean glIsVertexArrayAPPLE(@NativeType("GLuint") int array) {
return JNI.callZ(array, isVertexArray);
}
}
@@ -1,7 +1,7 @@
package org.embeddedt.embeddium.impl.gl.array; package org.embeddedt.embeddium.impl.gl.array;
import org.embeddedt.embeddium.impl.gl.GlObject; import org.embeddedt.embeddium.impl.gl.GlObject;
import org.lwjgl.opengl.GL30C; import org.embeddedt.embeddium.impl.gl.util.VAOUtil;
/** /**
* Provides Vertex Array functionality on supported platforms. * Provides Vertex Array functionality on supported platforms.
@@ -10,11 +10,11 @@ public class GlVertexArray extends GlObject {
public static final int NULL_ARRAY_ID = 0; public static final int NULL_ARRAY_ID = 0;
public GlVertexArray() { public GlVertexArray() {
this.setHandle(GL30C.glGenVertexArrays()); this.setHandle(VAOUtil.glGenVertexArrays());
} }
@Override @Override
protected void destroyInternal() { protected void destroyInternal() {
GL30C.glDeleteVertexArrays(this.handle()); VAOUtil.glDeleteVertexArrays(this.handle());
} }
} }
@@ -1,13 +1,18 @@
package org.embeddedt.embeddium.impl.gl.buffer; package org.embeddedt.embeddium.impl.gl.buffer;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL21C;
import org.lwjgl.opengl.GL31C; import org.lwjgl.opengl.GL31C;
import org.lwjgl.opengl.GL43C;
public enum GlBufferTarget { public enum GlBufferTarget {
ARRAY_BUFFER(GL20C.GL_ARRAY_BUFFER, GL20C.GL_ARRAY_BUFFER_BINDING), ARRAY_BUFFER(GL20C.GL_ARRAY_BUFFER, GL20C.GL_ARRAY_BUFFER_BINDING),
ELEMENT_BUFFER(GL20C.GL_ELEMENT_ARRAY_BUFFER, GL20C.GL_ELEMENT_ARRAY_BUFFER_BINDING), ELEMENT_BUFFER(GL20C.GL_ELEMENT_ARRAY_BUFFER, GL20C.GL_ELEMENT_ARRAY_BUFFER_BINDING),
COPY_READ_BUFFER(GL31C.GL_COPY_READ_BUFFER, GL31C.GL_COPY_READ_BUFFER), COPY_READ_BUFFER(GL31C.GL_COPY_READ_BUFFER, GL31C.GL_COPY_READ_BUFFER),
COPY_WRITE_BUFFER(GL31C.GL_COPY_WRITE_BUFFER, GL31C.GL_COPY_WRITE_BUFFER); COPY_WRITE_BUFFER(GL31C.GL_COPY_WRITE_BUFFER, GL31C.GL_COPY_WRITE_BUFFER),
DRAW_INDIRECT_BUFFER(GL43C.GL_DRAW_INDIRECT_BUFFER, GL43C.GL_DRAW_INDIRECT_BUFFER_BINDING),
PIXEL_PACK_BUFFER(GL21C.GL_PIXEL_PACK_BUFFER, GL21C.GL_PIXEL_PACK_BUFFER_BINDING),
PIXEL_UNPACK_BUFFER(GL21C.GL_PIXEL_UNPACK_BUFFER, GL21C.GL_PIXEL_UNPACK_BUFFER_BINDING);
public static final GlBufferTarget[] VALUES = GlBufferTarget.values(); public static final GlBufferTarget[] VALUES = GlBufferTarget.values();
public static final int COUNT = VALUES.length; public static final int COUNT = VALUES.length;
@@ -19,6 +19,8 @@ public interface CommandList extends AutoCloseable {
void uploadData(GlMutableBuffer glBuffer, ByteBuffer byteBuffer, GlBufferUsage usage); void uploadData(GlMutableBuffer glBuffer, ByteBuffer byteBuffer, GlBufferUsage usage);
void uploadData(GlMutableBuffer glBuffer, long ptr, long bytes, GlBufferUsage usage);
void copyBufferSubData(GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes); void copyBufferSubData(GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes);
void bindBuffer(GlBufferTarget target, GlBuffer buffer); void bindBuffer(GlBufferTarget target, GlBuffer buffer);
@@ -1,11 +1,14 @@
package org.embeddedt.embeddium.impl.gl.device; package org.embeddedt.embeddium.impl.gl.device;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType; import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
public interface DrawCommandList extends AutoCloseable { public interface DrawCommandList extends AutoCloseable {
void multiDrawElementsBaseVertex(MultiDrawBatch batch, GlPrimitiveType primitiveType, GlIndexType indexType); void multiDrawElementsBaseVertex(MultiDrawBatch batch, GlPrimitiveType primitiveType, GlIndexType indexType);
void multiDrawElementsIndirect(GlBuffer indirectBuffer, int count, GlPrimitiveType primitiveType, GlIndexType indexType);
void endTessellating(); void endTessellating();
void flush(); void flush();
@@ -7,6 +7,8 @@ import org.embeddedt.embeddium.impl.gl.state.GlStateTracker;
import org.embeddedt.embeddium.impl.gl.sync.GlFence; import org.embeddedt.embeddium.impl.gl.sync.GlFence;
import org.embeddedt.embeddium.impl.gl.tessellation.*; import org.embeddedt.embeddium.impl.gl.tessellation.*;
import org.embeddedt.embeddium.impl.gl.util.EnumBitField; import org.embeddedt.embeddium.impl.gl.util.EnumBitField;
import org.embeddedt.embeddium.impl.gl.util.VAOUtil;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.*; import org.lwjgl.opengl.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@@ -85,7 +87,7 @@ public class GLRenderDevice implements RenderDevice {
@Override @Override
public void bindVertexArray(GlVertexArray array) { public void bindVertexArray(GlVertexArray array) {
if (this.stateTracker.makeVertexArrayActive(array)) { if (this.stateTracker.makeVertexArrayActive(array)) {
GL30C.glBindVertexArray(array.handle()); VAOUtil.glBindVertexArray(array.handle());
} }
} }
@@ -98,24 +100,29 @@ public class GLRenderDevice implements RenderDevice {
} }
@Override @Override
public void copyBufferSubData(GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes) { public void uploadData(GlMutableBuffer glBuffer, long ptr, long bytes, GlBufferUsage usage) {
this.bindBuffer(GlBufferTarget.COPY_READ_BUFFER, src); this.bindBuffer(GlBufferTarget.ARRAY_BUFFER, glBuffer);
this.bindBuffer(GlBufferTarget.COPY_WRITE_BUFFER, dst);
GL31C.glCopyBufferSubData(GL31C.GL_COPY_READ_BUFFER, GL31C.GL_COPY_WRITE_BUFFER, readOffset, writeOffset, bytes); GL20C.nglBufferData(GlBufferTarget.ARRAY_BUFFER.getTargetParameter(), bytes, ptr, usage.getId());
glBuffer.setSize(bytes);
} }
@Override @Override
public void bindBuffer(GlBufferTarget target, GlBuffer buffer) { public void copyBufferSubData(GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes) {
GLRenderDevice.this.functions.bufferCopyFunctions().copyBufferSubData(this, src, dst, readOffset, writeOffset, bytes);
}
@Override
public void bindBuffer(GlBufferTarget target, @Nullable GlBuffer buffer) {
if (this.stateTracker.makeBufferActive(target, buffer)) { if (this.stateTracker.makeBufferActive(target, buffer)) {
GL20C.glBindBuffer(target.getTargetParameter(), buffer.handle()); GL20C.glBindBuffer(target.getTargetParameter(), buffer != null ? buffer.handle() : 0);
} }
} }
@Override @Override
public void unbindVertexArray() { public void unbindVertexArray() {
if (this.stateTracker.makeVertexArrayActive(null)) { if (this.stateTracker.makeVertexArrayActive(null)) {
GL30C.glBindVertexArray(GlVertexArray.NULL_ARRAY_ID); VAOUtil.glBindVertexArray(GlVertexArray.NULL_ARRAY_ID);
} }
} }
@@ -192,7 +199,8 @@ public class GLRenderDevice implements RenderDevice {
this.bindBuffer(GlBufferTarget.ARRAY_BUFFER, buffer); this.bindBuffer(GlBufferTarget.ARRAY_BUFFER, buffer);
ByteBuffer buf = GL32C.glMapBufferRange(GlBufferTarget.ARRAY_BUFFER.getTargetParameter(), offset, length, flags.getBitField()); ByteBuffer buf = GLRenderDevice.this.functions.bufferMapRangeFunctions()
.mapBufferRange(buffer, offset, length, flags);
if (buf == null) { if (buf == null) {
throw new RuntimeException("Failed to map buffer"); throw new RuntimeException("Failed to map buffer");
@@ -249,7 +257,7 @@ public class GLRenderDevice implements RenderDevice {
GlImmutableBuffer buffer = new GlImmutableBuffer(flags); GlImmutableBuffer buffer = new GlImmutableBuffer(flags);
this.bindBuffer(GlBufferTarget.ARRAY_BUFFER, buffer); this.bindBuffer(GlBufferTarget.ARRAY_BUFFER, buffer);
GLRenderDevice.this.functions.getBufferStorageFunctions() GLRenderDevice.this.functions.bufferStorageFunctions()
.createBufferStorage(GlBufferTarget.ARRAY_BUFFER, bufferSize, flags); .createBufferStorage(GlBufferTarget.ARRAY_BUFFER, bufferSize, flags);
return buffer; return buffer;
@@ -263,7 +271,7 @@ public class GLRenderDevice implements RenderDevice {
@Override @Override
public void multiDrawElementsBaseVertex(MultiDrawBatch batch, GlPrimitiveType primitiveType, GlIndexType indexType) { public void multiDrawElementsBaseVertex(MultiDrawBatch batch, GlPrimitiveType primitiveType, GlIndexType indexType) {
GL32C.nglMultiDrawElementsBaseVertex(primitiveType.getId(), GLRenderDevice.this.functions.multidrawFunctions().multiDrawElementsBaseVertex(primitiveType.getId(),
batch.pElementCount, batch.pElementCount,
indexType.getFormatId(), indexType.getFormatId(),
batch.pElementPointer, batch.pElementPointer,
@@ -271,6 +279,11 @@ public class GLRenderDevice implements RenderDevice {
batch.pBaseVertex); batch.pBaseVertex);
} }
@Override
public void multiDrawElementsIndirect(GlBuffer indirectBuffer, int count, GlPrimitiveType primitiveType, GlIndexType indexType) {
GL43C.glMultiDrawElementsIndirect(primitiveType.getId(), indexType.getFormatId(), 0, count, 0);
}
@Override @Override
public void endTessellating() { public void endTessellating() {
GLRenderDevice.this.activeTessellation.unbind(GLRenderDevice.this.commandList); GLRenderDevice.this.activeTessellation.unbind(GLRenderDevice.this.commandList);
@@ -0,0 +1,54 @@
package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL31C;
import org.lwjgl.system.MemoryUtil;
public enum BufferCopyFunctions {
CORE {
@Override
public void copyBufferSubData(CommandList commandList, GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes) {
commandList.bindBuffer(GlBufferTarget.COPY_READ_BUFFER, src);
commandList.bindBuffer(GlBufferTarget.COPY_WRITE_BUFFER, dst);
GL31C.glCopyBufferSubData(GL31C.GL_COPY_READ_BUFFER, GL31C.GL_COPY_WRITE_BUFFER, readOffset, writeOffset, bytes);
}
},
PIXEL_PACK {
@Override
public void copyBufferSubData(CommandList commandList, GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes) {
if (src.getActiveMapping() != null || dst.getActiveMapping() != null) {
throw new IllegalStateException("Cannot use PIXEL_PACK copy strategy on mapped buffers");
}
commandList.bindBuffer(GlBufferTarget.PIXEL_PACK_BUFFER, src);
commandList.bindBuffer(GlBufferTarget.PIXEL_UNPACK_BUFFER, dst);
long srcBufPtr = GL15.nglMapBuffer(GlBufferTarget.PIXEL_PACK_BUFFER.getTargetParameter(), GL15.GL_READ_ONLY);
if (srcBufPtr == 0L) {
throw new IllegalStateException("Source buffer could not be mapped");
}
long dstBufPtr = GL15.nglMapBuffer(GlBufferTarget.PIXEL_UNPACK_BUFFER.getTargetParameter(), GL15.GL_WRITE_ONLY);
if (dstBufPtr == 0L) {
throw new IllegalStateException("Destination buffer could not be mapped");
}
MemoryUtil.memCopy(srcBufPtr + readOffset, dstBufPtr + writeOffset, bytes);
GL15.glUnmapBuffer(GlBufferTarget.PIXEL_PACK_BUFFER.getTargetParameter());
GL15.glUnmapBuffer(GlBufferTarget.PIXEL_UNPACK_BUFFER.getTargetParameter());
commandList.bindBuffer(GlBufferTarget.PIXEL_PACK_BUFFER, null);
commandList.bindBuffer(GlBufferTarget.PIXEL_UNPACK_BUFFER, null);
}
};
public abstract void copyBufferSubData(CommandList commandList, GlBuffer src, GlBuffer dst, long readOffset, long writeOffset, long bytes);
public static BufferCopyFunctions pickBest(RenderDevice device) {
var caps = device.getCapabilities();
if (caps.OpenGL31 || caps.GL_ARB_copy_buffer) {
return CORE;
} else {
return PIXEL_PACK;
}
}
}
@@ -0,0 +1,56 @@
package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferMapFlags;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.util.EnumBitField;
import org.lwjgl.opengl.GL15C;
import org.lwjgl.opengl.GL30C;
import java.nio.ByteBuffer;
public enum BufferMapRangeFunctions {
CORE {
@Override
public ByteBuffer mapBufferRange(GlBuffer buffer, long offset, long length, EnumBitField<GlBufferMapFlags> flags) {
return GL30C.glMapBufferRange(GlBufferTarget.ARRAY_BUFFER.getTargetParameter(), offset, length, flags.getBitField());
}
},
MAP_FULL_AND_SLICE {
@Override
public ByteBuffer mapBufferRange(GlBuffer buffer, long offset, long length, EnumBitField<GlBufferMapFlags> flags) {
if (flags.contains(GlBufferMapFlags.EXPLICIT_FLUSH)) {
throw new UnsupportedOperationException("Explicit flush not supported for MAP_FULL_AND_SLICE strategy");
}
int access;
if (flags.contains(GlBufferMapFlags.WRITE) && flags.contains(GlBufferMapFlags.READ)) {
access = GL15C.GL_READ_WRITE;
} else if (flags.contains(GlBufferMapFlags.WRITE)) {
access = GL15C.GL_WRITE_ONLY;
} else {
access = GL15C.GL_READ_ONLY;
}
ByteBuffer buf = GL15C.glMapBuffer(GlBufferTarget.ARRAY_BUFFER.getTargetParameter(), access, null);
// Avoid slicing the buffer if we can prove that the full buffer is being mapped
if (buffer instanceof GlMutableBuffer mutBuffer && mutBuffer.getSize() == length && offset == 0) {
return buf;
}
return buf.position(Math.toIntExact(offset))
.limit(Math.toIntExact(offset) + Math.toIntExact(length))
.slice();
}
};
public abstract ByteBuffer mapBufferRange(GlBuffer buffer, long offset, long length, EnumBitField<GlBufferMapFlags> flags);
public static BufferMapRangeFunctions pickBest(RenderDevice device) {
var caps = device.getCapabilities();
if (caps.OpenGL30 || caps.GL_ARB_map_buffer_range) {
return CORE;
} else {
return MAP_FULL_AND_SLICE;
}
}
}
@@ -2,14 +2,16 @@ package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
public class DeviceFunctions { public record DeviceFunctions(BufferStorageFunctions bufferStorageFunctions,
private final BufferStorageFunctions bufferStorageFunctions; MultidrawFunctions multidrawFunctions,
BufferCopyFunctions bufferCopyFunctions,
BufferMapRangeFunctions bufferMapRangeFunctions) {
public DeviceFunctions(RenderDevice device) { public DeviceFunctions(RenderDevice device) {
this.bufferStorageFunctions = BufferStorageFunctions.pickBest(device); this(
} BufferStorageFunctions.pickBest(device),
MultidrawFunctions.pickBest(device),
public BufferStorageFunctions getBufferStorageFunctions() { BufferCopyFunctions.pickBest(device),
return this.bufferStorageFunctions; BufferMapRangeFunctions.pickBest(device)
);
} }
} }
@@ -0,0 +1,51 @@
package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.lwjgl.opengl.ARBDrawElementsBaseVertex;
import org.lwjgl.opengl.GL32C;
import org.lwjgl.opengl.GLCapabilities;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.system.Pointer;
public enum MultidrawFunctions {
NONE {
@Override
public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int size, long pBaseVertex) {
throw new UnsupportedOperationException("Platform does not support DrawElementsBaseVertex");
}
},
FALLBACK {
@Override
public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int size, long pBaseVertex) {
for (int i = 0; i < size; i++) {
long off = i * 4L;
int count = MemoryUtil.memGetInt(pCount + off);
if (count > 0) {
ARBDrawElementsBaseVertex.nglDrawElementsBaseVertex(mode, count, type,
MemoryUtil.memGetAddress(pIndices + ((long)i * Pointer.POINTER_SIZE)),
MemoryUtil.memGetInt(pBaseVertex + off));
}
}
}
},
CORE {
@Override
public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int size, long pBaseVertex) {
GL32C.nglMultiDrawElementsBaseVertex(mode, pCount, type, pIndices, size, pBaseVertex);
}
};
public static MultidrawFunctions pickBest(RenderDevice device) {
GLCapabilities capabilities = device.getCapabilities();
if (capabilities.OpenGL32) {
return CORE;
} else if (capabilities.GL_ARB_draw_elements_base_vertex) {
return FALLBACK;
} else {
return NONE;
}
}
public abstract void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int size, long pBaseVertex);
}
@@ -0,0 +1,26 @@
package org.embeddedt.embeddium.impl.gl.shader.uniform;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryStack;
import java.nio.FloatBuffer;
public class GlUniformFloatArray extends GlUniform<float[]> {
public GlUniformFloatArray(int index) {
super(index);
}
@Override
public void set(float[] value) {
try (MemoryStack stack = MemoryStack.stackPush()) {
FloatBuffer buf = stack.callocFloat(value.length);
buf.put(value);
GL30C.glUniform1fv(this.index, buf);
}
}
public void set(FloatBuffer value) {
GL30C.glUniform1fv(this.index, value);
}
}
@@ -3,6 +3,7 @@ package org.embeddedt.embeddium.impl.gl.state;
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray; import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer; import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget; import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays; import java.util.Arrays;
@@ -30,11 +31,13 @@ public class GlStateTracker {
} }
} }
public boolean makeBufferActive(GlBufferTarget target, GlBuffer buffer) { public boolean makeBufferActive(GlBufferTarget target, @Nullable GlBuffer buffer) {
boolean changed = this.bufferState[target.ordinal()] != buffer.handle(); int handle = buffer == null ? UNASSIGNED_HANDLE : buffer.handle();
boolean changed = this.bufferState[target.ordinal()] != handle;
if (changed) { if (changed) {
this.bufferState[target.ordinal()] = buffer.handle(); this.bufferState[target.ordinal()] = handle;
} }
return changed; return changed;
@@ -2,23 +2,43 @@ package org.embeddedt.embeddium.impl.gl.tessellation;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeBinding; import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeBinding;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.lwjgl.opengl.EXTGPUShader4;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
public abstract class GlAbstractTessellation implements GlTessellation { public abstract class GlAbstractTessellation implements GlTessellation {
private static final boolean coreIPointerSupported, extIPointerSupported;
static {
var caps = GL.getCapabilities();
coreIPointerSupported = caps.OpenGL30;
extIPointerSupported = caps.GL_EXT_gpu_shader4;
}
protected final TessellationBinding[] bindings; protected final TessellationBinding[] bindings;
protected GlAbstractTessellation(TessellationBinding[] bindings) { protected GlAbstractTessellation(TessellationBinding[] bindings) {
this.bindings = bindings; this.bindings = bindings;
} }
private static void glVertexAttribIPointer(int index, int size, int type, int stride, long ptr) {
if (coreIPointerSupported) {
GL30C.glVertexAttribIPointer(index, size, type, stride, ptr);
} else if (extIPointerSupported) {
EXTGPUShader4.glVertexAttribIPointerEXT(index, size, type, stride, ptr);
} else {
throw new UnsupportedOperationException();
}
}
protected void bindAttributes(CommandList commandList) { protected void bindAttributes(CommandList commandList) {
for (TessellationBinding binding : this.bindings) { for (TessellationBinding binding : this.bindings) {
commandList.bindBuffer(binding.target(), binding.buffer()); commandList.bindBuffer(binding.target(), binding.buffer());
for (GlVertexAttributeBinding attrib : binding.attributeBindings()) { for (GlVertexAttributeBinding attrib : binding.attributeBindings()) {
if (attrib.isIntType()) { if (attrib.isIntType()) {
GL30C.glVertexAttribIPointer(attrib.getIndex(), attrib.getCount(), attrib.getFormat().typeId(), glVertexAttribIPointer(attrib.getIndex(), attrib.getCount(), attrib.getFormat().typeId(),
attrib.getStride(), attrib.getPointer()); attrib.getStride(), attrib.getPointer());
} else { } else {
GL20C.glVertexAttribPointer(attrib.getIndex(), attrib.getCount(), attrib.getFormat().typeId(), attrib.isNormalized(), GL20C.glVertexAttribPointer(attrib.getIndex(), attrib.getCount(), attrib.getFormat().typeId(), attrib.isNormalized(),
@@ -0,0 +1,116 @@
package org.embeddedt.embeddium.impl.gl.util;
import org.embeddedt.embeddium.impl.gl.array.APPLEVertexArrayObject;
import org.lwjgl.opengl.ARBVertexArrayObject;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.NativeType;
import java.nio.IntBuffer;
/**
* Provides an abstraction over various VAO implementations.
*/
public class VAOUtil {
public static final boolean coreSupported = GL.getCapabilities().OpenGL32;
public static final boolean arbSupported = GL.getCapabilities().GL_ARB_vertex_array_object;
public static final boolean appleSupported = APPLEVertexArrayObject.supported;
public static final boolean supported = coreSupported || arbSupported || appleSupported;
public static void glBindVertexArray(@NativeType("GLuint") int array) {
if (coreSupported) {
GL30C.glBindVertexArray(array);
} else if (arbSupported) {
ARBVertexArrayObject.glBindVertexArray(array);
} else if (appleSupported) {
APPLEVertexArrayObject.glBindVertexArrayAPPLE(array);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static void nglDeleteVertexArrays(int n, long arrays) {
if (coreSupported) {
GL30C.nglDeleteVertexArrays(n, arrays);
} else if (arbSupported) {
ARBVertexArrayObject.nglDeleteVertexArrays(n, arrays);
} else if (appleSupported) {
APPLEVertexArrayObject.nglDeleteVertexArraysAPPLE(n, arrays);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static void glDeleteVertexArrays(@NativeType("GLuint const *") IntBuffer arrays) {
if (coreSupported) {
GL30C.glDeleteVertexArrays(arrays);
} else if (arbSupported) {
ARBVertexArrayObject.glDeleteVertexArrays(arrays);
} else if (appleSupported) {
APPLEVertexArrayObject.glDeleteVertexArraysAPPLE(arrays);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static void glDeleteVertexArrays(@NativeType("GLuint const *") int array) {
if (coreSupported) {
GL30C.glDeleteVertexArrays(array);
} else if (arbSupported) {
ARBVertexArrayObject.glDeleteVertexArrays(array);
} else if (appleSupported) {
APPLEVertexArrayObject.glDeleteVertexArraysAPPLE(array);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static void nglGenVertexArrays(int n, long arrays) {
if (coreSupported) {
GL30C.nglGenVertexArrays(n, arrays);
} else if (arbSupported) {
ARBVertexArrayObject.nglGenVertexArrays(n, arrays);
} else if (appleSupported) {
APPLEVertexArrayObject.nglGenVertexArraysAPPLE(n, arrays);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static void glGenVertexArrays(@NativeType("GLuint *") IntBuffer arrays) {
if (coreSupported) {
GL30C.glGenVertexArrays(arrays);
} else if (arbSupported) {
ARBVertexArrayObject.glGenVertexArrays(arrays);
} else if (appleSupported) {
APPLEVertexArrayObject.glGenVertexArraysAPPLE(arrays);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static int glGenVertexArrays() {
if (coreSupported) {
return GL30C.glGenVertexArrays();
} else if (arbSupported) {
return ARBVertexArrayObject.glGenVertexArrays();
} else if (appleSupported) {
return APPLEVertexArrayObject.glGenVertexArraysAPPLE();
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
public static boolean glIsVertexArray(@NativeType("GLuint") int array) {
if (coreSupported) {
return GL30C.glIsVertexArray(array);
} else if (arbSupported) {
return ARBVertexArrayObject.glIsVertexArray(array);
} else if (appleSupported) {
return APPLEVertexArrayObject.glIsVertexArrayAPPLE(array);
} else {
throw new UnsupportedOperationException("VAO not supported");
}
}
}
@@ -0,0 +1,174 @@
package org.embeddedt.embeddium.impl.gui;
import lombok.Getter;
import org.taumc.celeritas.api.OptionGUIConstructionEvent;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionFlag;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.taumc.celeritas.api.options.structure.OptionStorage;
import org.embeddedt.embeddium.impl.gui.frame.AbstractFrame;
import org.embeddedt.embeddium.impl.gui.frame.BasicFrame;
import org.embeddedt.embeddium.impl.gui.frame.tab.Tab;
import org.embeddedt.embeddium.impl.gui.frame.tab.TabFrame;
import org.embeddedt.embeddium.impl.gui.framework.*;
import org.embeddedt.embeddium.impl.gui.widgets.FlatButtonWidget;
import org.embeddedt.embeddium.impl.util.Dim2i;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
public class CeleritasVideoOptionsController implements Renderable {
private static final float ASPECT_RATIO = 5f / 4f;
private static final int MINIMUM_WIDTH = 550;
private static final AtomicReference<TextComponent> tabFrameSelectedTab = new AtomicReference<>(null);
private final AtomicReference<Integer> tabFrameScrollBarOffset = new AtomicReference<>(0);
private final AtomicReference<Integer> optionPageScrollBarOffset = new AtomicReference<>(0);
private final List<OptionPage> pages = new ArrayList<>();
private final Runnable onClose;
private final DrawContext font;
@Getter
private AbstractFrame frame;
private FlatButtonWidget applyButton, closeButton, undoButton;
@Getter
private boolean hasPendingChanges;
private boolean firstInit = true;
private int width, height;
public CeleritasVideoOptionsController(Runnable onClose, List<OptionPage> pages, DrawContext font) {
this.onClose = onClose;
this.pages.addAll(pages);
OptionGUIConstructionEvent.BUS.post(new OptionGUIConstructionEvent(this.pages));
this.font = font;
}
public void init(int width, int height) {
this.width = width;
this.height = height;
this.frame = this.parentFrameBuilder().build();
}
protected BasicFrame.Builder parentFrameBuilder() {
BasicFrame.Builder basicFrameBuilder;
// Apply aspect ratio clamping on wide enough screens
int newWidth = this.width;
if (newWidth > MINIMUM_WIDTH && (float) this.width / (float) this.height > ASPECT_RATIO) {
newWidth = Math.max(MINIMUM_WIDTH, (int) (this.height * ASPECT_RATIO));
}
Dim2i basicFrameDim = new Dim2i((this.width - newWidth) / 2, 0, newWidth, this.height);
Dim2i tabFrameDim = new Dim2i(basicFrameDim.x() + basicFrameDim.width() / 20 / 2, basicFrameDim.y() + basicFrameDim.height() / 4 / 2, basicFrameDim.width() - (basicFrameDim.width() / 20), basicFrameDim.height() / 4 * 3);
Dim2i undoButtonDim = new Dim2i(tabFrameDim.getLimitX() - 203, tabFrameDim.getLimitY() + 5, 65, 20);
Dim2i applyButtonDim = new Dim2i(tabFrameDim.getLimitX() - 134, tabFrameDim.getLimitY() + 5, 65, 20);
Dim2i closeButtonDim = new Dim2i(tabFrameDim.getLimitX() - 65, tabFrameDim.getLimitY() + 5, 65, 20);
this.undoButton = new FlatButtonWidget(undoButtonDim, TextComponent.translatable("sodium.options.buttons.undo"), this::undoChanges);
this.applyButton = new FlatButtonWidget(applyButtonDim, TextComponent.translatable("sodium.options.buttons.apply"), this::applyChanges);
this.closeButton = new FlatButtonWidget(closeButtonDim, TextComponent.translatable("gui.done"), this.onClose);
basicFrameBuilder = this.parentBasicFrameBuilder(basicFrameDim, tabFrameDim);
return basicFrameBuilder;
}
@Override
public void render(DrawContext drawContext, int mouseX, int mouseY, float partialTicks) {
this.updateControls();
this.frame.render(drawContext, mouseX, mouseY, partialTicks);
}
private void updateControls() {
boolean hasChanges = this.getAllOptions()
.anyMatch(Option::hasChanged);
this.applyButton.setEnabled(hasChanges);
this.undoButton.setVisible(hasChanges);
this.closeButton.setEnabled(!hasChanges);
this.hasPendingChanges = hasChanges;
}
private Stream<Option<?>> getAllOptions() {
return this.pages.stream()
.flatMap(s -> s.getOptions().stream());
}
private void applyChanges() {
final HashSet<OptionStorage<?>> dirtyStorages = new HashSet<>();
final EnumSet<OptionFlag> flags = EnumSet.noneOf(OptionFlag.class);
this.getAllOptions().forEach((option -> {
if (!option.hasChanged()) {
return;
}
option.applyChanges();
flags.addAll(option.getFlags());
dirtyStorages.add(option.getStorage());
}));
for (OptionStorage<?> storage : dirtyStorages) {
storage.save(flags);
}
applyFlagSideEffects(Collections.unmodifiableSet(flags));
}
protected void applyFlagSideEffects(Set<OptionFlag> flags) {
}
private void undoChanges() {
this.getAllOptions()
.forEach(Option::reset);
}
private boolean canShowPage(OptionPage page) {
return !page.getGroups().isEmpty();
}
protected void createExtraTabs(Map<String, List<Tab<?>>> tabs) {
}
private AbstractFrame createTabFrame(Dim2i tabFrameDim) {
// TabFrame will automatically expand its height to fit all tabs, so the scrollable frame can handle it
return TabFrame.createBuilder()
.setDimension(tabFrameDim)
.shouldRenderOutline(false)
.setTabSectionScrollBarOffset(tabFrameScrollBarOffset)
.setTabSectionSelectedTab(tabFrameSelectedTab)
.addTabs(tabs -> this.pages
.stream()
.filter(this::canShowPage)
.forEach(page -> tabs.computeIfAbsent(page.getId().getModId(), $ -> new ArrayList<>()).add(Tab.from(page, o -> true, optionPageScrollBarOffset)))
)
.addTabs(this::createExtraTabs)
.onSetTab(() -> {
optionPageScrollBarOffset.set(0);
})
.build(this.font);
}
public BasicFrame.Builder parentBasicFrameBuilder(Dim2i parentBasicFrameDim, Dim2i tabFrameDim) {
return BasicFrame.createBuilder()
.setDimension(parentBasicFrameDim)
.shouldRenderOutline(false)
.addChild(parentDim -> this.createTabFrame(tabFrameDim))
.addChild(dim -> this.undoButton)
.addChild(dim -> this.applyButton)
.addChild(dim -> this.closeButton);
}
}
@@ -5,27 +5,26 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import net.minecraft.client.Minecraft; import org.apache.logging.log4j.LogManager;
import org.embeddedt.embeddium.impl.Celeritas; import org.apache.logging.log4j.Logger;
import org.taumc.celeritas.api.options.structure.OptionStorage;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.options.TextProvider; import org.embeddedt.embeddium.impl.gui.options.TextProvider;
//? if >=1.16
import net.minecraft.client.GraphicsStatus;
import net.minecraft.network.chat.Component;
import org.embeddedt.embeddium.impl.config.ConfigMigrator;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.embeddedt.embeddium.impl.util.ComponentUtil;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.List;
import static org.embeddedt.embeddium.impl.Celeritas.MODID; public class SodiumGameOptions implements OptionStorage<SodiumGameOptions> {
private static final Logger LOGGER = LogManager.getLogger();
public class SodiumGameOptions { private static final String DEFAULT_FILE_NAME = "embeddium-options.json";
private static final String DEFAULT_FILE_NAME = MODID + "-options.json";
public final QualitySettings quality = new QualitySettings(); public final QualitySettings quality = new QualitySettings();
public final AdvancedSettings advanced = new AdvancedSettings(); public final AdvancedSettings advanced = new AdvancedSettings();
@@ -43,6 +42,22 @@ public class SodiumGameOptions {
return options; return options;
} }
@Override
public SodiumGameOptions getData() {
return this;
}
@Override
public void save() {
try {
this.writeChanges();
} catch (IOException e) {
throw new RuntimeException("Couldn't save configuration changes", e);
}
LOGGER.info("Flushed changes to Embeddium configuration");
}
public static class PerformanceSettings { public static class PerformanceSettings {
public int chunkBuilderThreads = 0; public int chunkBuilderThreads = 0;
@SerializedName("always_defer_chunk_updates_v2") // this will reset the option in older configs @SerializedName("always_defer_chunk_updates_v2") // this will reset the option in older configs
@@ -79,6 +94,10 @@ public class SodiumGameOptions {
@SerializedName("use_quad_normals_for_shading_v2") @SerializedName("use_quad_normals_for_shading_v2")
public boolean useQuadNormalsForShading = true; public boolean useQuadNormalsForShading = true;
public int chunkFadeInDuration = 0;
public int legacyBiomeBlendRadius = 0;
} }
public static class NotificationSettings { public static class NotificationSettings {
@@ -89,40 +108,28 @@ public class SodiumGameOptions {
} }
public enum GraphicsQuality implements TextProvider { public enum GraphicsQuality implements TextProvider {
DEFAULT("options.gamma.default"), DEFAULT(List.of("options.gamma.default", "generator.default")),
FANCY("options.clouds.fancy"), FANCY("options.clouds.fancy"),
FAST("options.clouds.fast"); FAST("options.clouds.fast");
private final Component name; private final TextComponent name;
GraphicsQuality(String name) { GraphicsQuality(String name) {
this.name = ComponentUtil.translatable(name); this.name = TextComponent.translatable(name);
}
GraphicsQuality(List<String> names) {
this.name = TextComponent.translatable(names);
} }
@Override @Override
public Component getLocalizedName() { public TextComponent getLocalizedName() {
return this.name; return this.name;
} }
//? if >=1.16 { public boolean isFancy(boolean fancyGraphics) {
public boolean isFancy(GraphicsStatus graphicsMode) {
return (this == FANCY) || (this == DEFAULT && (graphicsMode == GraphicsStatus.FANCY || graphicsMode == GraphicsStatus.FABULOUS));
}
//?} else {
/*public boolean isFancy(boolean fancyGraphics) {
return (this == FANCY) || (this == DEFAULT && fancyGraphics); return (this == FANCY) || (this == DEFAULT && fancyGraphics);
} }
*///?}
//? if <1.16 {
/*public boolean isFancy() {
return isFancy(Minecraft.getInstance().options.fancyGraphics);
}
*///?} else {
public boolean isFancy() {
return isFancy(Minecraft.getInstance().options.graphicsMode/*? if >=1.19 {*/().get()/*?}*/);
}
//?}
} }
private static final Gson GSON = new GsonBuilder() private static final Gson GSON = new GsonBuilder()
@@ -146,7 +153,7 @@ public class SodiumGameOptions {
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Could not parse config", e); throw new RuntimeException("Could not parse config", e);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
Celeritas.logger().error("Could not parse config, will fallback to default settings", e); LOGGER.error("Could not parse config, will fallback to default settings", e);
config = new SodiumGameOptions(); config = new SodiumGameOptions();
resaveConfig = false; resaveConfig = false;
} }
@@ -170,7 +177,7 @@ public class SodiumGameOptions {
} }
private static Path getConfigPath(String name) { private static Path getConfigPath(String name) {
return ConfigMigrator.handleConfigMigration(name); return Paths.get("config", name);
} }
@Deprecated @Deprecated
@@ -0,0 +1,59 @@
package org.embeddedt.embeddium.impl.gui.frame;
import org.taumc.celeritas.api.options.control.ControlElement;
import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.gui.framework.Interactable;
import org.embeddedt.embeddium.impl.gui.framework.InteractableContainer;
import org.embeddedt.embeddium.impl.gui.framework.Renderable;
import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget;
import org.embeddedt.embeddium.impl.util.Dim2i;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public abstract class AbstractFrame extends AbstractWidget implements InteractableContainer {
protected Dim2i dim;
protected final List<AbstractWidget> children = new ArrayList<>();
protected final List<Renderable> drawable = new ArrayList<>();
protected final List<ControlElement<?>> controlElements = new ArrayList<>();
protected boolean renderOutline;
public AbstractFrame(Dim2i dim, boolean renderOutline) {
this.dim = dim;
this.renderOutline = renderOutline;
}
public void buildFrame() {
for (AbstractWidget element : this.children) {
if (element instanceof AbstractFrame) {
this.controlElements.addAll(((AbstractFrame) element).controlElements);
}
if (element instanceof ControlElement<?>) {
this.controlElements.add((ControlElement<?>) element);
}
if (element instanceof Renderable) {
this.drawable.add((Renderable) element);
}
}
}
@Override
public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
if (this.renderOutline) {
drawContext.drawBorder(this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
}
for (Renderable drawable : this.drawable) {
drawable.render(drawContext, mouseX, mouseY, delta);
}
}
@Override
public Stream<? extends Interactable> interactableChildren() {
return this.children.stream();
}
public Dim2i getDimensions() {
return this.dim;
}
}
@@ -2,10 +2,10 @@ package org.embeddedt.embeddium.impl.gui.frame;
import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget; import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget;
import org.embeddedt.embeddium.impl.util.Dim2i; import org.embeddedt.embeddium.impl.util.Dim2i;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
public class BasicFrame extends AbstractFrame { public class BasicFrame extends AbstractFrame {
@@ -54,7 +54,7 @@ public class BasicFrame extends AbstractFrame {
} }
public BasicFrame build() { public BasicFrame build() {
Validate.notNull(this.dim, "Dimension must be specified"); Objects.requireNonNull(this.dim, "Dimension must be specified");
return new BasicFrame(this.dim, this.renderOutline, this.functions); return new BasicFrame(this.dim, this.renderOutline, this.functions);
} }
@@ -1,30 +1,17 @@
package org.embeddedt.embeddium.impl.gui.frame; package org.embeddedt.embeddium.impl.gui.frame;
import com.google.common.base.Predicates; import org.taumc.celeritas.api.options.structure.Option;
import org.embeddedt.embeddium.api.options.structure.Option; import org.taumc.celeritas.api.options.structure.OptionGroup;
import org.embeddedt.embeddium.api.options.structure.OptionGroup; import org.taumc.celeritas.api.options.structure.OptionImpact;
import org.embeddedt.embeddium.api.options.structure.OptionImpact; import org.taumc.celeritas.api.options.structure.OptionPage;
import org.embeddedt.embeddium.api.options.structure.OptionPage; import org.taumc.celeritas.api.options.control.Control;
import org.embeddedt.embeddium.api.options.control.Control; import org.taumc.celeritas.api.options.control.ControlElement;
import org.embeddedt.embeddium.api.options.control.ControlElement; import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.util.ComponentUtil; import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.framework.TextFormattingStyle;
import org.embeddedt.embeddium.impl.util.Dim2i; import org.embeddedt.embeddium.impl.util.Dim2i;
import net.minecraft.ChatFormatting; import org.taumc.celeritas.api.options.OptionIdentifier;
import net.minecraft.client.Minecraft;
//$ guigfx
import net.minecraft.client.gui.GuiGraphics;
//? if >=1.20 {
import net.minecraft.client.gui.ComponentPath;
import net.minecraft.client.gui.navigation.FocusNavigationEvent;
//?}
import net.minecraft.locale.Language;
import net.minecraft.network.chat.Component;
//? if >=1.16.2
import net.minecraft.util.FormattedCharSequence;
import org.apache.commons.lang3.Validate;
import org.embeddedt.embeddium.api.options.OptionIdentifier;
import org.embeddedt.embeddium.impl.gui.theme.DefaultColors; import org.embeddedt.embeddium.impl.gui.theme.DefaultColors;
import org.embeddedt.embeddium.impl.util.PlatformUtil;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
@@ -105,18 +92,13 @@ public class OptionPageFrame extends AbstractFrame {
super.buildFrame(); super.buildFrame();
} }
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) { @Override
ControlElement<?> hoveredElement = this.controlElements.stream() public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
.filter(ControlElement::isHovered) ControlElement<?> hoveredElement = this.isMouseOver(mouseX, mouseY) ? this.controlElements.stream()
.findFirst() .filter(c -> c.isMouseOver(mouseX, mouseY))
.orElse(this.controlElements.stream() .findFirst().orElse(null) : null;
.filter(ControlElement::isFocused)
.findFirst()
.orElse(null));
super.render(drawContext, mouseX, mouseY, delta); super.render(drawContext, mouseX, mouseY, delta);
if (hoveredElement != null && this.lastHoveredElement == hoveredElement && if (hoveredElement != null && this.lastHoveredElement == hoveredElement) {
((this.dim.containsCursor(mouseX, mouseY) && hoveredElement.isHovered() && hoveredElement.isMouseOver(mouseX, mouseY))
|| hoveredElement.isFocused())) {
if (this.lastTime == 0) { if (this.lastTime == 0) {
this.lastTime = System.currentTimeMillis(); this.lastTime = System.currentTimeMillis();
} }
@@ -138,7 +120,7 @@ public class OptionPageFrame extends AbstractFrame {
} }
} }
private void renderOptionTooltip(GuiGraphics drawContext, ControlElement<?> element) { private void renderOptionTooltip(DrawContext drawContext, ControlElement<?> element) {
if (this.lastTime + 500 > System.currentTimeMillis()) return; if (this.lastTime + 500 > System.currentTimeMillis()) return;
Dim2i dim = element.getDimensions(); Dim2i dim = element.getDimensions();
@@ -153,20 +135,20 @@ public class OptionPageFrame extends AbstractFrame {
int boxX = dim.x(); int boxX = dim.x();
Option<?> option = element.getOption(); Option<?> option = element.getOption();
var tooltip = new ArrayList<>(this.split(option.getTooltip().getString(), boxWidth - (textPadding * 2))); var tooltip = new ArrayList<>(drawContext.split(option.getTooltip(), boxWidth - (textPadding * 2)));
OptionImpact impact = option.getImpact(); OptionImpact impact = option.getImpact();
if (impact != null) { if (impact != null) {
var impactString = ComponentUtil.translatable("sodium.options.performance_impact_string", impact.getLocalizedName()).withStyle(ChatFormatting.GRAY); var impactString = TextComponent.translatable("sodium.options.performance_impact_string", impact.getLocalizedName()).withStyle(TextFormattingStyle.GRAY);
tooltip.add(impactString.getString()); tooltip.add(impactString);
} }
var id = option.getId(); var id = option.getId();
if (OptionIdentifier.isPresent(page.getId()) && OptionIdentifier.isPresent(id) && !Objects.equals(normalizeModForTooltip(page.getId().getModId()), normalizeModForTooltip(id.getModId()))) { if (OptionIdentifier.isPresent(page.getId()) && OptionIdentifier.isPresent(id) && !Objects.equals(normalizeModForTooltip(page.getId().getModId()), normalizeModForTooltip(id.getModId()))) {
var addedByModString = ComponentUtil.translatable("embeddium.options.added_by_mod_string", ComponentUtil.literal(PlatformUtil.getModName(id.getModId())).withStyle(ChatFormatting.WHITE)).withStyle(ChatFormatting.GRAY); var addedByModString = TextComponent.translatable("embeddium.options.added_by_mod_string", TextComponent.literal(id.getModId()).withStyle(TextFormattingStyle.WHITE)).withStyle(TextFormattingStyle.GRAY);
tooltip.add(addedByModString.getString()); tooltip.add(addedByModString);
} }
int boxHeight = (tooltip.size() * 12) + boxPadding; int boxHeight = (tooltip.size() * 12) + boxPadding;
@@ -182,29 +164,25 @@ public class OptionPageFrame extends AbstractFrame {
boxY = dim.getLimitY(); boxY = dim.getLimitY();
} }
drawContext.pose().pushPose(); drawContext.pushMatrix();
drawContext.pose().translate(0, 0, 90);
this.drawRect(drawContext, boxX, boxY, boxX + boxWidth, boxY + boxHeight, 0xE0000000); drawContext.translate(0, 0, 90);
this.drawBorder(drawContext, boxX, boxY, boxX + boxWidth, boxY + boxHeight, DefaultColors.ELEMENT_ACTIVATED);
drawContext.fill(boxX, boxY, boxX + boxWidth, boxY + boxHeight, 0xE0000000);
drawContext.drawBorder(boxX, boxY, boxX + boxWidth, boxY + boxHeight, DefaultColors.ELEMENT_ACTIVATED);
for (int i = 0; i < tooltip.size(); i++) { for (int i = 0; i < tooltip.size(); i++) {
drawContext.drawString(Minecraft.getInstance().font, tooltip.get(i), boxX + textPadding, boxY + textPadding + (i * 12), 0xFFFFFFFF, true); drawContext.drawString(tooltip.get(i), boxX + textPadding, boxY + textPadding + (i * 12), 0xFFFFFFFF, true);
}
drawContext.pose().popPose();
} }
//? if >=1.20 { drawContext.popMatrix();
@Override
public @Nullable ComponentPath nextFocusPath(FocusNavigationEvent navigation) {
return super.nextFocusPath(navigation);
} }
//?}
public static class Builder { public static class Builder {
private Dim2i dim; private Dim2i dim;
private boolean renderOutline; private boolean renderOutline;
private OptionPage page; private OptionPage page;
private Predicate<Option<?>> optionFilter = Predicates.alwaysTrue(); private Predicate<Option<?>> optionFilter = o -> true;
public Builder setDimension(Dim2i dim) { public Builder setDimension(Dim2i dim) {
this.dim = dim; this.dim = dim;
@@ -227,8 +205,8 @@ public class OptionPageFrame extends AbstractFrame {
} }
public OptionPageFrame build() { public OptionPageFrame build() {
Validate.notNull(this.dim, "Dimension must be specified"); Objects.requireNonNull(this.dim, "Dimension must be specified");
Validate.notNull(this.page, "Option Page must be specified"); Objects.requireNonNull(this.page, "Option Page must be specified");
return new OptionPageFrame(this.dim, this.renderOutline, this.page, this.optionFilter); return new OptionPageFrame(this.dim, this.renderOutline, this.page, this.optionFilter);
} }
@@ -1,15 +1,13 @@
package org.embeddedt.embeddium.impl.gui.frame; package org.embeddedt.embeddium.impl.gui.frame;
import org.embeddedt.embeddium.api.options.control.ControlElement; import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.gui.framework.Interactable;
import org.embeddedt.embeddium.impl.gui.framework.InteractionContext;
import org.embeddedt.embeddium.impl.util.Dim2i; import org.embeddedt.embeddium.impl.util.Dim2i;
//? if >=1.20 {
import net.minecraft.client.gui.GuiGraphics;
//?} else {
/*import org.embeddedt.embeddium.impl.gui.compat.GuiGraphics;
*///?}
import org.embeddedt.embeddium.impl.gui.frame.components.ScrollBarComponent; import org.embeddedt.embeddium.impl.gui.frame.components.ScrollBarComponent;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
public class ScrollableFrame extends AbstractFrame { public class ScrollableFrame extends AbstractFrame {
@@ -100,24 +98,6 @@ public class ScrollableFrame extends AbstractFrame {
this.frame.buildFrame(); this.frame.buildFrame();
this.children.add(this.frame); this.children.add(this.frame);
super.buildFrame(); super.buildFrame();
// fixme: Ridiculous hack to snap to focused element
// for the meanwhile this works until a proper solution is implemented.
// this shouldn't be hardcoded into scrollable frame
this.frame.registerFocusListener(element -> {
if (element instanceof ControlElement<?> controlElement && this.canScrollVertical) {
Dim2i dim = controlElement.getDimensions();
int inputOffset = this.verticalScrollBar.getOffset();
int elementTop = dim.y() - inputOffset;
int elementBottom = dim.getLimitY() - inputOffset;
if (elementTop <= this.viewPortDimension.y()) {
inputOffset += elementTop - this.viewPortDimension.y();
} else if (elementBottom >= this.viewPortDimension.getLimitY()) {
inputOffset += elementBottom - this.viewPortDimension.getLimitY();
}
this.verticalScrollBar.setOffset(inputOffset);
}
});
} }
/** /**
@@ -137,17 +117,17 @@ public class ScrollableFrame extends AbstractFrame {
@Override @Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) { public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
if (this.canScrollHorizontal || this.canScrollVertical) { if (this.canScrollHorizontal || this.canScrollVertical) {
if (this.renderOutline) { if (this.renderOutline) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA); drawContext.drawBorder(this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
} }
boolean mouseInViewport = this.viewPortDimension.containsCursor(mouseX, mouseY); boolean mouseInViewport = this.viewPortDimension.containsCursor(mouseX, mouseY);
drawContext.enableScissor(this.viewPortDimension.x(), this.viewPortDimension.y(), this.viewPortDimension.getLimitX(), this.viewPortDimension.getLimitY()); drawContext.enableScissor(this.viewPortDimension.x(), this.viewPortDimension.y(), this.viewPortDimension.getLimitX(), this.viewPortDimension.getLimitY());
drawContext.pose().pushPose(); drawContext.pushMatrix();
drawContext.pose().translate(applyOffset(this.horizontalScrollBar, 0, true), applyOffset(this.verticalScrollBar, 0, true), 0); drawContext.translate(applyOffset(this.horizontalScrollBar, 0, true), applyOffset(this.verticalScrollBar, 0, true), 0);
super.render(drawContext, mouseInViewport ? (int)applyOffset(this.horizontalScrollBar, mouseX, false) : -1, mouseInViewport ? (int)applyOffset(this.verticalScrollBar, mouseY, false) : -1, delta); super.render(drawContext, mouseInViewport ? (int)applyOffset(this.horizontalScrollBar, mouseX, false) : -1, mouseInViewport ? (int)applyOffset(this.verticalScrollBar, mouseY, false) : -1, delta);
drawContext.pose().popPose(); drawContext.popMatrix();
drawContext.disableScissor(); drawContext.disableScissor();
} else { } else {
super.render(drawContext, mouseX, mouseY, delta); super.render(drawContext, mouseX, mouseY, delta);
@@ -163,23 +143,31 @@ public class ScrollableFrame extends AbstractFrame {
} }
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int button) { public boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
return (this.canScrollHorizontal && this.horizontalScrollBar.mouseClicked(mouseX, mouseY, button)) || (this.canScrollVertical && this.verticalScrollBar.mouseClicked(mouseX, mouseY, button)) || super.mouseClicked(applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button); return (this.canScrollHorizontal && this.horizontalScrollBar.mouseClicked(context, mouseX, mouseY, button)) ||
(this.canScrollVertical && this.verticalScrollBar.mouseClicked(context, mouseX, mouseY, button)) ||
super.mouseClicked(context, applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button);
} }
@Override @Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { public boolean mouseDragged(InteractionContext context, double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return (this.canScrollHorizontal && this.horizontalScrollBar.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)) || (this.canScrollVertical && this.verticalScrollBar.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)) || super.mouseDragged(applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button, deltaX, deltaY); return (this.canScrollHorizontal && this.horizontalScrollBar.mouseDragged(context, mouseX, mouseY, button, deltaX, deltaY)) ||
(this.canScrollVertical && this.verticalScrollBar.mouseDragged(context, mouseX, mouseY, button, deltaX, deltaY)) ||
super.mouseDragged(context, applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button, deltaX, deltaY);
} }
@Override @Override
public boolean mouseReleased(double mouseX, double mouseY, int button) { public boolean mouseReleased(InteractionContext context, double mouseX, double mouseY, int button) {
return (this.canScrollHorizontal && this.horizontalScrollBar.mouseReleased(mouseX, mouseY, button)) || (this.canScrollVertical && this.verticalScrollBar.mouseReleased(mouseX, mouseY, button)) || super.mouseReleased(applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button); return (this.canScrollHorizontal && this.horizontalScrollBar.mouseReleased(context, mouseX, mouseY, button))
|| (this.canScrollVertical && this.verticalScrollBar.mouseReleased(context, mouseX, mouseY, button))
|| super.mouseReleased(context, applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), button);
} }
@Override @Override
public boolean mouseScrolled(double mouseX, double mouseY, /*? if >=1.20.2 {*/ /*double horizontalAmount, *//*?}*/ double verticalAmount) { public boolean mouseScrolled(InteractionContext context, double mouseX, double mouseY, double horizontalAmount, double verticalAmount) {
return (this.canScrollHorizontal && this.horizontalScrollBar.mouseScrolled(mouseX, mouseY, /*? if >=1.20.2 {*/ /*horizontalAmount, *//*?}*/ verticalAmount)) || (this.canScrollVertical && this.verticalScrollBar.mouseScrolled(mouseX, mouseY, /*? if >=1.20.2 {*/ /*horizontalAmount, *//*?}*/ verticalAmount)) || super.mouseScrolled(applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), /*? if >=1.20.2 {*/ /*horizontalAmount, *//*?}*/ verticalAmount); return (this.canScrollHorizontal && this.horizontalScrollBar.mouseScrolled(context, mouseX, mouseY, horizontalAmount, verticalAmount))
|| (this.canScrollVertical && this.verticalScrollBar.mouseScrolled(context, mouseX, mouseY, horizontalAmount, verticalAmount))
|| super.mouseScrolled(context, applyOffset(this.horizontalScrollBar, mouseX, false), applyOffset(this.verticalScrollBar, mouseY, false), horizontalAmount, verticalAmount);
} }
public static class Builder { public static class Builder {
@@ -1,20 +1,14 @@
package org.embeddedt.embeddium.impl.gui.frame.components; package org.embeddedt.embeddium.impl.gui.frame.components;
import com.mojang.blaze3d.platform.InputConstants; import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.gui.framework.InteractionContext;
import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget; import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget;
import org.embeddedt.embeddium.impl.util.Dim2i; import org.embeddedt.embeddium.impl.util.Dim2i;
//? if >=1.20 {
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.navigation.ScreenRectangle;
//?} else {
/*import org.embeddedt.embeddium.impl.gui.compat.GuiGraphics;
*///?}
import net.minecraft.util.Mth;
import java.util.function.Consumer; import java.util.function.Consumer;
public class ScrollBarComponent extends AbstractWidget { public class ScrollBarComponent extends AbstractWidget {
protected static final int SCROLL_OFFSET = 6; protected static final int SCROLL_OFFSET = 6;
protected final Dim2i dim; protected final Dim2i dim;
@@ -54,16 +48,13 @@ public class ScrollBarComponent extends AbstractWidget {
} }
@Override @Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) { public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA); drawContext.drawBorder(this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), 0xFFAAAAAA);
this.drawRect(drawContext, this.scrollThumb.x(), this.scrollThumb.y(), this.scrollThumb.getLimitX(), this.scrollThumb.getLimitY(), 0xFFAAAAAA); drawContext.fill(this.scrollThumb.x(), this.scrollThumb.y(), this.scrollThumb.getLimitX(), this.scrollThumb.getLimitY(), 0xFFAAAAAA);
if (this.isFocused()) {
this.drawBorder(drawContext, this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), -1);
}
} }
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int button) { public boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
if (this.dim.containsCursor(mouseX, mouseY)) { if (this.dim.containsCursor(mouseX, mouseY)) {
if (this.scrollThumb.containsCursor(mouseX, mouseY)) { if (this.scrollThumb.containsCursor(mouseX, mouseY)) {
if (this.mode == Mode.VERTICAL) { if (this.mode == Mode.VERTICAL) {
@@ -89,7 +80,7 @@ public class ScrollBarComponent extends AbstractWidget {
} }
@Override @Override
public boolean mouseReleased(double mouseX, double mouseY, int button) { public boolean mouseReleased(InteractionContext context, double mouseX, double mouseY, int button) {
if (button == 0) { if (button == 0) {
this.isDragging = false; this.isDragging = false;
} }
@@ -97,7 +88,7 @@ public class ScrollBarComponent extends AbstractWidget {
} }
@Override @Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { public boolean mouseDragged(InteractionContext context, double mouseX, double mouseY, int button, double deltaX, double deltaY) {
if (this.isDragging) { if (this.isDragging) {
int value; int value;
if (this.mode == Mode.VERTICAL) { if (this.mode == Mode.VERTICAL) {
@@ -112,7 +103,7 @@ public class ScrollBarComponent extends AbstractWidget {
} }
@Override @Override
public boolean mouseScrolled(double mouseX, double mouseY, /*? if >=1.20.2 {*/ /*double horizontalAmount, *//*?}*/ double verticalAmount) { public boolean mouseScrolled(InteractionContext context, double mouseX, double mouseY, double horizontalAmount, double verticalAmount) {
if (this.dim.containsCursor(mouseX, mouseY) || this.extendedScrollArea != null && this.extendedScrollArea.containsCursor(mouseX, mouseY)) { if (this.dim.containsCursor(mouseX, mouseY) || this.extendedScrollArea != null && this.extendedScrollArea.containsCursor(mouseX, mouseY)) {
if (this.offset <= this.maxScrollBarOffset && this.offset >= 0) { if (this.offset <= this.maxScrollBarOffset && this.offset >= 0) {
int value = (int) (this.offset - verticalAmount * SCROLL_OFFSET); // todo: horizontal separation int value = (int) (this.offset - verticalAmount * SCROLL_OFFSET); // todo: horizontal separation
@@ -128,42 +119,14 @@ public class ScrollBarComponent extends AbstractWidget {
} }
public void setOffset(int value) { public void setOffset(int value) {
this.offset = Mth.clamp(value, 0, this.maxScrollBarOffset); this.offset = MathUtil.clamp(value, 0, this.maxScrollBarOffset);
this.updateThumbPosition(); this.updateThumbPosition();
this.onSetOffset.accept(this.offset); this.onSetOffset.accept(this.offset);
} }
//? if >=1.20 {
@Override @Override
public ScreenRectangle getRectangle() { public boolean isMouseOver(double mouseX, double mouseY) {
return new ScreenRectangle(this.dim.x(), this.dim.y(), this.dim.width(), this.dim.height()); return this.dim.containsCursor(mouseX, mouseY) || this.extendedScrollArea.containsCursor(mouseX, mouseY);
}
//?}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (!this.isFocused())
return false;
if (this.mode == Mode.VERTICAL) {
if (keyCode == 265) { // up
this.setOffset(this.getOffset() - SCROLL_OFFSET);
return true;
} else if (keyCode == 264) { // down
this.setOffset(this.getOffset() + SCROLL_OFFSET);
return true;
}
} else {
if (keyCode == 263) { // left
this.setOffset(this.getOffset() - SCROLL_OFFSET);
return true;
} else if (keyCode == 262) { // right
this.setOffset(this.getOffset() + SCROLL_OFFSET);
return true;
}
}
return false;
} }
public enum Mode { public enum Mode {
@@ -0,0 +1,47 @@
package org.embeddedt.embeddium.impl.gui.frame.tab;
import lombok.Builder;
import org.taumc.celeritas.api.options.structure.Option;
import org.taumc.celeritas.api.options.structure.OptionPage;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.framework.TextFormattingStyle;
import org.embeddedt.embeddium.impl.util.Dim2i;
import org.taumc.celeritas.api.options.OptionIdentifier;
import org.embeddedt.embeddium.impl.gui.frame.AbstractFrame;
import org.embeddedt.embeddium.impl.gui.frame.OptionPageFrame;
import org.embeddedt.embeddium.impl.gui.frame.ScrollableFrame;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
@Builder(builderClassName = "Builder", setterPrefix = "set")
public record Tab<T extends AbstractFrame>(OptionIdentifier<Void> id, TextComponent title, Supplier<Boolean> onSelectFunction, Function<Dim2i, T> frameFunction) {
public static Tab.Builder<?> createBuilder() {
return new Tab.Builder<>();
}
public T createFrame(Dim2i dim) {
return this.frameFunction != null ? this.frameFunction.apply(dim) : null;
}
public static Tab<ScrollableFrame> from(OptionPage page, Predicate<Option<?>> optionFilter, AtomicReference<Integer> verticalScrollBarOffset) {
Function<Dim2i, ScrollableFrame> frameFunction = dim2i -> ScrollableFrame
.createBuilder()
.setDimension(dim2i)
.setFrame(OptionPageFrame
.createBuilder()
.setDimension(new Dim2i(dim2i.x(), dim2i.y(), dim2i.width(), dim2i.height()))
.setOptionPage(page)
.setOptionFilter(optionFilter)
.build())
.setVerticalScrollBarOffset(verticalScrollBarOffset)
.build();
return Tab.<ScrollableFrame>builder()
.setTitle(page.getName())
.setId(page.getId())
.setFrameFunction(frameFunction)
.build();
}
}
@@ -1,21 +1,19 @@
package org.embeddedt.embeddium.impl.gui.frame.tab; package org.embeddedt.embeddium.impl.gui.frame.tab;
import com.google.common.collect.ImmutableListMultimap; import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import com.google.common.collect.Multimap; import org.embeddedt.embeddium.impl.gui.framework.FontMetricsProvider;
import com.google.common.collect.MultimapBuilder; import org.embeddedt.embeddium.impl.gui.framework.InteractionContext;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget; import org.embeddedt.embeddium.impl.gui.widgets.AbstractWidget;
import org.embeddedt.embeddium.impl.gui.widgets.FlatButtonWidget; import org.embeddedt.embeddium.impl.gui.widgets.FlatButtonWidget;
import org.embeddedt.embeddium.impl.util.Dim2i; import org.embeddedt.embeddium.impl.util.Dim2i;
//$ guigfx
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import org.apache.commons.lang3.Validate;
import org.embeddedt.embeddium.impl.gui.frame.AbstractFrame; import org.embeddedt.embeddium.impl.gui.frame.AbstractFrame;
import org.embeddedt.embeddium.impl.gui.frame.ScrollableFrame; import org.embeddedt.embeddium.impl.gui.frame.ScrollableFrame;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class TabFrame extends AbstractFrame { public class TabFrame extends AbstractFrame {
@@ -23,22 +21,22 @@ public class TabFrame extends AbstractFrame {
private Dim2i tabSection; private Dim2i tabSection;
private final Dim2i frameSection; private final Dim2i frameSection;
private final Multimap<String, Tab<?>> tabs; private final Map<String, List<Tab<?>>> tabs;
private final Runnable onSetTab; private final Runnable onSetTab;
private final AtomicReference<Component> tabSectionSelectedTab; private final AtomicReference<TextComponent> tabSectionSelectedTab;
private final AtomicReference<Integer> tabSectionScrollBarOffset; private final AtomicReference<Integer> tabSectionScrollBarOffset;
private Tab<?> selectedTab; private Tab<?> selectedTab;
private AbstractFrame selectedFrame; private AbstractFrame selectedFrame;
private Dim2i tabSectionInner; private Dim2i tabSectionInner;
private ScrollableFrame sidebarFrame; private ScrollableFrame sidebarFrame;
public TabFrame(Dim2i dim, boolean renderOutline, Multimap<String, Tab<?>> tabs, Runnable onSetTab, AtomicReference<Component> tabSectionSelectedTab, AtomicReference<Integer> tabSectionScrollBarOffset) { public TabFrame(DrawContext drawContext, Dim2i dim, boolean renderOutline, Map<String, List<Tab<?>>> tabs, Runnable onSetTab, AtomicReference<TextComponent> tabSectionSelectedTab, AtomicReference<Integer> tabSectionScrollBarOffset) {
super(dim, renderOutline); super(dim, renderOutline);
this.tabs = ImmutableListMultimap.copyOf(tabs); this.tabs = Collections.unmodifiableMap(tabs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> List.copyOf(e.getValue()), (a, b) -> a, LinkedHashMap::new)));
int tabSectionY = (this.tabs.size() + this.tabs.keySet().size()) * 18; int tabSectionY = ((int)tabStream().count() + this.tabs.size()) * 18;
Optional<Integer> result = Stream.concat( Optional<Integer> result = Stream.concat(
tabs.keys().stream().map(id -> this.getStringWidth(Tab.idComponent(id)) + 10), tabs.keySet().stream().map(id -> drawContext.getStringWidth(drawContext.getFriendlyModName(id)) + 10),
tabs.values().stream().map(tab -> this.getStringWidth(tab.title()) + TAB_OPTION_INDENT) tabStream().map(tab -> drawContext.getStringWidth(tab.title()) + TAB_OPTION_INDENT)
).max(Integer::compareTo); ).max(Integer::compareTo);
this.tabSection = new Dim2i(this.dim.x(), this.dim.y(), result.map(integer -> integer + (24)).orElseGet(() -> (int) (this.dim.width() * 0.35D)), this.dim.height()); this.tabSection = new Dim2i(this.dim.x(), this.dim.y(), result.map(integer -> integer + (24)).orElseGet(() -> (int) (this.dim.width() * 0.35D)), this.dim.height());
@@ -50,13 +48,19 @@ public class TabFrame extends AbstractFrame {
this.tabSectionScrollBarOffset = tabSectionScrollBarOffset; this.tabSectionScrollBarOffset = tabSectionScrollBarOffset;
if (this.tabSectionSelectedTab.get() != null) { if (this.tabSectionSelectedTab.get() != null) {
this.selectedTab = this.tabs.values().stream().filter(tab -> tab.title().getString().equals(this.tabSectionSelectedTab.get().getString())).findAny().orElse(null); this.selectedTab = tabStream().filter(tab -> tab.title().equals(this.tabSectionSelectedTab.get())).findAny().orElse(null);
} }
this.buildFrame(); this.buildFrame();
// Let's build each frame, future note for anyone: do not move this line. // Let's build each frame, future note for anyone: do not move this line.
this.tabs.values().stream().filter(tab -> this.selectedTab != tab).forEach(tab -> tab.getFrameFunction().apply(this.frameSection)); tabStream().filter(tab -> this.selectedTab != tab).forEach(tab -> {
tab.createFrame(this.frameSection);
});
}
private Stream<Tab<?>> tabStream() {
return this.tabs.values().stream().flatMap(Collection::stream);
} }
public static Builder createBuilder() { public static Builder createBuilder() {
@@ -93,7 +97,7 @@ public class TabFrame extends AbstractFrame {
int width = tabSection.width() - 4; int width = tabSection.width() - 4;
int height = 18; int height = 18;
for (var modEntry : tabs.asMap().entrySet()) { for (var modEntry : tabs.entrySet()) {
// Add a "button" as the header // Add a "button" as the header
Dim2i modHeaderDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection); Dim2i modHeaderDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection);
offsetY += height; offsetY += height;
@@ -106,13 +110,13 @@ public class TabFrame extends AbstractFrame {
Dim2i tabDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection); Dim2i tabDim = new Dim2i(0, offsetY, width, height).withParentOffset(tabSection);
FlatButtonWidget button = new FlatButtonWidget(tabDim, tab.title(), () -> { FlatButtonWidget button = new FlatButtonWidget(tabDim, tab.title(), () -> {
if(tab.onSelectFunction().get()) { if(tab.onSelectFunction() == null || tab.onSelectFunction().get()) {
TabFrame.this.setTab(tab); TabFrame.this.setTab(tab);
} }
}) { }) {
@Override @Override
protected int getLeftAlignedTextOffset() { protected int getLeftAlignedTextOffset(DrawContext drawContext) {
return TAB_OPTION_INDENT + super.getLeftAlignedTextOffset(); return TAB_OPTION_INDENT + super.getLeftAlignedTextOffset(drawContext);
} }
}; };
@@ -135,7 +139,7 @@ public class TabFrame extends AbstractFrame {
if (this.selectedTab == null) { if (this.selectedTab == null) {
if (!this.tabs.isEmpty()) { if (!this.tabs.isEmpty()) {
// Just use the first tab for now // Just use the first tab for now
this.selectedTab = this.tabs.values().iterator().next(); this.selectedTab = tabStream().findFirst().orElseThrow();
} }
} }
@@ -154,7 +158,7 @@ public class TabFrame extends AbstractFrame {
private void rebuildTabFrame() { private void rebuildTabFrame() {
if (this.selectedTab == null) return; if (this.selectedTab == null) return;
AbstractFrame frame = this.selectedTab.getFrameFunction().apply(this.frameSection); AbstractFrame frame = this.selectedTab.createFrame(this.frameSection);
if (frame != null) { if (frame != null) {
this.selectedFrame = frame; this.selectedFrame = frame;
frame.buildFrame(); frame.buildFrame();
@@ -163,7 +167,7 @@ public class TabFrame extends AbstractFrame {
} }
@Override @Override
public void render(GuiGraphics drawContext, int mouseX, int mouseY, float delta) { public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
for (AbstractWidget widget : this.children) { for (AbstractWidget widget : this.children) {
if (widget != this.selectedFrame) { if (widget != this.selectedFrame) {
widget.render(drawContext, mouseX, mouseY, delta); widget.render(drawContext, mouseX, mouseY, delta);
@@ -175,31 +179,16 @@ public class TabFrame extends AbstractFrame {
} }
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int button) { public boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
return (this.dim.containsCursor(mouseX, mouseY) && super.mouseClicked(mouseX, mouseY, button)); return (this.dim.containsCursor(mouseX, mouseY) && super.mouseClicked(context, mouseX, mouseY, button));
}
@Override
public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
return super.mouseReleased(mouseX, mouseY, button);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, /*? if >=1.20.2 {*/ /*double horizontalAmount, *//*?}*/ double verticalAmount) {
return super.mouseScrolled(mouseX, mouseY, /*? if >=1.20.2 {*/ /*horizontalAmount, *//*?}*/ verticalAmount);
} }
public static class Builder { public static class Builder {
private final Multimap<String, Tab<?>> functions = MultimapBuilder.linkedHashKeys().arrayListValues().build(); private final Map<String, List<Tab<?>>> functions = new LinkedHashMap<>();
private Dim2i dim; private Dim2i dim;
private boolean renderOutline; private boolean renderOutline;
private Runnable onSetTab; private Runnable onSetTab;
private AtomicReference<Component> tabSectionSelectedTab = new AtomicReference<>(null); private AtomicReference<TextComponent> tabSectionSelectedTab = new AtomicReference<>(null);
private AtomicReference<Integer> tabSectionScrollBarOffset = new AtomicReference<>(0); private AtomicReference<Integer> tabSectionScrollBarOffset = new AtomicReference<>(0);
public Builder setDimension(Dim2i dim) { public Builder setDimension(Dim2i dim) {
@@ -212,7 +201,7 @@ public class TabFrame extends AbstractFrame {
return this; return this;
} }
public Builder addTabs(Consumer<Multimap<String, Tab<?>>> tabs) { public Builder addTabs(Consumer<Map<String, List<Tab<?>>>> tabs) {
tabs.accept(this.functions); tabs.accept(this.functions);
return this; return this;
} }
@@ -222,7 +211,7 @@ public class TabFrame extends AbstractFrame {
return this; return this;
} }
public Builder setTabSectionSelectedTab(AtomicReference<Component> tabSectionSelectedTab) { public Builder setTabSectionSelectedTab(AtomicReference<TextComponent> tabSectionSelectedTab) {
this.tabSectionSelectedTab = tabSectionSelectedTab; this.tabSectionSelectedTab = tabSectionSelectedTab;
return this; return this;
} }
@@ -232,10 +221,10 @@ public class TabFrame extends AbstractFrame {
return this; return this;
} }
public TabFrame build() { public TabFrame build(DrawContext font) {
Validate.notNull(this.dim, "Dimension must be specified"); Objects.requireNonNull(this.dim, "Dimension must be specified");
return new TabFrame(this.dim, this.renderOutline, this.functions, this.onSetTab, this.tabSectionSelectedTab, this.tabSectionScrollBarOffset); return new TabFrame(font, this.dim, this.renderOutline, this.functions, this.onSetTab, this.tabSectionSelectedTab, this.tabSectionScrollBarOffset);
} }
} }
} }
@@ -0,0 +1,40 @@
package org.embeddedt.embeddium.impl.gui.frame.tab;
import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.framework.TextFormattingStyle;
import org.embeddedt.embeddium.impl.gui.widgets.FlatButtonWidget;
import org.embeddedt.embeddium.impl.util.Dim2i;
import java.util.Objects;
public class TabHeaderWidget extends FlatButtonWidget {
private static final String FALLBACK_TEXTURE = "textures/misc/unknown_pack.png";
private final String modId;
public TabHeaderWidget(Dim2i dim, String modId) {
super(dim, TextComponent.literal(""), () -> {});
this.modId = modId;
}
@Override
protected int getLeftAlignedTextOffset(DrawContext drawContext) {
return super.getLeftAlignedTextOffset(drawContext) + drawContext.lineHeight();
}
@Override
protected boolean isHovered(int mouseX, int mouseY) {
return false;
}
@Override
public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
this.setLabel(drawContext.getFriendlyModName(modId).withStyle(TextFormattingStyle.UNDERLINE));
super.render(drawContext, mouseX, mouseY, delta);
String icon = Objects.requireNonNullElse(drawContext.getModLogoPath(modId), FALLBACK_TEXTURE);
int fontHeight = drawContext.lineHeight();
int imgY = this.dim.getCenterY() - (fontHeight / 2);
drawContext.blitWholeImage(icon, this.dim.x() + 5, imgY, fontHeight, fontHeight);
}
}
@@ -0,0 +1,45 @@
package org.embeddedt.embeddium.impl.gui.framework;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface DrawContext extends FontMetricsProvider {
void fill(int x1, int y1, int x2, int y2, int color);
default int drawString(String str, int x, int y, int color) {
return drawString(TextComponent.literal(str), x, y, color);
}
default int drawString(TextComponent str, int x, int y, int color) {
return drawString(str, x, y, color, false);
}
int drawString(TextComponent str, int x, int y, int color, boolean shadow);
void blitWholeImage(@NotNull String icon, int x, int y, int width, int height);
void pushMatrix();
void translate(double x, double y, double z);
void popMatrix();
void enableScissor(int x1, int y1, int x2, int y2);
void disableScissor();
default void drawBorder(int x1, int y1, int x2, int y2, int color) {
fill(x1, y1, x2, y1 + 1, color);
fill(x1, y2 - 1, x2, y2, color);
fill(x1, y1, x1 + 1, y2, color);
fill(x2 - 1, y1, x2, y2, color);
}
default @Nullable String getModLogoPath(String modId) {
return null;
}
default TextComponent getFriendlyModName(String modId) {
return TextComponent.literal(modId);
}
}
@@ -0,0 +1,19 @@
package org.embeddedt.embeddium.impl.gui.framework;
import java.util.List;
public interface FontMetricsProvider {
default int getStringWidth(String str) {
return getStringWidth(new TextComponent.Literal(str));
}
int getStringWidth(TextComponent component);
String substrByWidth(String str, int maxWidth);
List<TextComponent> split(TextComponent component, int maxWidth);
String extractString(TextComponent component);
int lineHeight();
}
@@ -0,0 +1,21 @@
package org.embeddedt.embeddium.impl.gui.framework;
public interface Interactable {
boolean isMouseOver(double mouseX, double mouseY);
default boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseReleased(InteractionContext context, double mouseX, double mouseY, int button) {
return false;
}
default boolean mouseDragged(InteractionContext context, double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return false;
}
default boolean mouseScrolled(InteractionContext context, double mouseX, double mouseY, double deltaX, double deltaY) {
return false;
}
}
@@ -0,0 +1,37 @@
package org.embeddedt.embeddium.impl.gui.framework;
import java.util.function.Predicate;
import java.util.stream.Stream;
public interface InteractableContainer extends Interactable {
Stream<? extends Interactable> interactableChildren();
private boolean runSingleChildAction(Predicate<Interactable> action) {
// Defensive copy to handle mutation
return interactableChildren().toList().stream().anyMatch(action);
}
default boolean isMouseOver(double mouseX, double mouseY) {
return interactableChildren().anyMatch(i -> i.isMouseOver(mouseX, mouseY));
}
@Override
default boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
return runSingleChildAction(i -> i.mouseClicked(context, mouseX, mouseY, button));
}
@Override
default boolean mouseReleased(InteractionContext context, double mouseX, double mouseY, int button) {
return runSingleChildAction(i -> i.mouseReleased(context, mouseX, mouseY, button));
}
@Override
default boolean mouseDragged(InteractionContext context, double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return runSingleChildAction(i -> i.isMouseOver(mouseX, mouseY) && i.mouseDragged(context, mouseX, mouseY, button, deltaX, deltaY));
}
@Override
default boolean mouseScrolled(InteractionContext context, double mouseX, double mouseY, double deltaX, double deltaY) {
return runSingleChildAction(i -> i.isMouseOver(mouseX, mouseY) && i.mouseScrolled(context, mouseX, mouseY, deltaX, deltaY));
}
}
@@ -0,0 +1,17 @@
package org.embeddedt.embeddium.impl.gui.framework;
public interface InteractionContext {
default void playClickSound() {
}
default boolean isSpecialKeyDown(SpecialKey key) {
return false;
}
enum SpecialKey {
SHIFT,
CTRL,
ALT
}
}
@@ -0,0 +1,5 @@
package org.embeddedt.embeddium.impl.gui.framework;
public interface Renderable {
void render(DrawContext drawContext, int mouseX, int mouseY, float partialTicks);
}
@@ -0,0 +1,67 @@
package org.embeddedt.embeddium.impl.gui.framework;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
public interface TextComponent {
default List<TextComponent> children() {
return List.of();
}
record Literal(String text) implements TextComponent {
@Override
public @NotNull String toString() {
return text;
}
}
record Translatable(List<String> keys, List<?> args) implements TextComponent {
@Override
public @NotNull String toString() {
String keyString = keys.size() == 1 ? keys.getFirst() : keys.toString();
if (args.isEmpty()) {
return keyString;
}
return keyString + args;
}
}
record Styled(TextComponent inner, EnumSet<TextFormattingStyle> styles) implements TextComponent {
@Override
public List<TextComponent> children() {
return List.of(inner);
}
@Override
public TextComponent withStyle(TextFormattingStyle style, TextFormattingStyle... rest) {
var newSet = EnumSet.copyOf(styles);
newSet.add(style);
newSet.addAll(Arrays.asList(rest));
return new Styled(inner, newSet);
}
@Override
public @NotNull String toString() {
return inner.toString() + "[styled]";
}
}
default TextComponent withStyle(TextFormattingStyle style, TextFormattingStyle... rest) {
return new Styled(this, EnumSet.of(style, rest));
}
static TextComponent literal(String text) {
return new Literal(text);
}
static TextComponent translatable(String key, Object... args) {
return new Translatable(List.of(key), Arrays.asList(args));
}
static TextComponent translatable(List<String> keys, Object... args) {
return new Translatable(keys, Arrays.asList(args));
}
}
@@ -0,0 +1,27 @@
package org.embeddedt.embeddium.impl.gui.framework;
public enum TextFormattingStyle {
BLACK,
DARK_BLUE,
DARK_GREEN,
DARK_AQUA,
DARK_RED,
DARK_PURPLE,
GOLD,
GRAY,
DARK_GRAY,
BLUE,
GREEN,
AQUA,
RED,
LIGHT_PURPLE,
YELLOW,
WHITE,
STRIKETHROUGH,
UNDERLINE,
ITALIC;
public boolean isColor() {
return this.ordinal() < 16;
}
}
@@ -0,0 +1,164 @@
package org.embeddedt.embeddium.impl.gui.options;
import org.taumc.celeritas.api.options.control.ControlValueFormatter;
import org.taumc.celeritas.api.options.control.CyclingControl;
import org.taumc.celeritas.api.options.control.SliderControl;
import org.taumc.celeritas.api.options.control.TickBoxControl;
import org.embeddedt.embeddium.impl.gui.SodiumGameOptions;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.render.ShaderModBridge;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkBuilder;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.taumc.celeritas.api.options.structure.*;
import java.util.ArrayList;
import java.util.List;
public class CommonOptionPages {
public static OptionGroup sortingGroup(SodiumGameOptions sodiumOpts) {
return OptionGroup.createBuilder()
.setId(StandardOptions.Group.SORTING)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.TRANSLUCENT_FACE_SORTING.cast())
.setName(TextComponent.translatable("sodium.options.translucent_face_sorting.name"))
.setTooltip(TextComponent.translatable("sodium.options.translucent_face_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.VARIES)
.setBinding((opts, value) -> opts.performance.useTranslucentFaceSorting = value, opts -> opts.performance.useTranslucentFaceSorting)
.setEnabled(!ShaderModBridge.isNvidiumEnabled())
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setId(StandardOptions.Option.CHUNK_FADE_IN_DURATION.cast())
.setName(TextComponent.translatable("celeritas.options.chunk_fade_in_duration.name"))
.setTooltip(TextComponent.translatable("celeritas.options.chunk_fade_in_duration.tooltip"))
.setControl(o -> new SliderControl(o, 0, 2000, 100, ControlValueFormatter.translateVariable("celeritas.options.chunk_fade_in_duration.value")))
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.quality.chunkFadeInDuration = value, opts -> opts.quality.chunkFadeInDuration)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build();
}
public static OptionPage performance(SodiumGameOptions sodiumOpts) {
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.CHUNK_UPDATES)
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setId(StandardOptions.Option.CHUNK_UPDATE_THREADS.cast())
.setName(TextComponent.translatable("sodium.options.chunk_update_threads.name"))
.setTooltip(TextComponent.translatable("sodium.options.chunk_update_threads.tooltip"))
.setControl(o -> new SliderControl(o, 0, ChunkBuilder.getMaxThreadCount(), 1, ControlValueFormatter.quantityOrDisabled("threads", "Default")))
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.chunkBuilderThreads = value, opts -> opts.performance.chunkBuilderThreads)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.DEFFER_CHUNK_UPDATES.cast())
.setName(TextComponent.translatable("sodium.options.always_defer_chunk_updates.name"))
.setTooltip(TextComponent.translatable("sodium.options.always_defer_chunk_updates.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.alwaysDeferChunkUpdates = value, opts -> opts.performance.alwaysDeferChunkUpdates)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build())
.add(OptionImpl.createBuilder(AsyncOcclusionMode.class, sodiumOpts)
.setId(StandardOptions.Option.ASYNC_GRAPH_SEARCH.cast())
.setName(TextComponent.translatable("celeritas.options.async_graph_search.name"))
.setTooltip(TextComponent.translatable("celeritas.options.async_graph_search.tooltip"))
.setControl(o -> new CyclingControl<>(o, AsyncOcclusionMode.class, new TextComponent[] { TextComponent.literal("Off"), TextComponent.literal("Only Shadows"), TextComponent.literal("Everything") }))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.asyncOcclusionMode = value, opts -> opts.performance.asyncOcclusionMode)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build()
);
groups.add(OptionGroup.createBuilder()
.setId(StandardOptions.Group.RENDERING_CULLING)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.BLOCK_FACE_CULLING.cast())
.setName(TextComponent.translatable("sodium.options.use_block_face_culling.name"))
.setTooltip(TextComponent.translatable("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.COMPACT_VERTEX_FORMAT.cast())
.setName(TextComponent.translatable("sodium.options.use_compact_vertex_format.name"))
.setTooltip(TextComponent.translatable("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> {
opts.performance.useCompactVertexFormat = value;
}, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.FOG_OCCLUSION.cast())
.setName(TextComponent.translatable("sodium.options.use_fog_occlusion.name"))
.setTooltip(TextComponent.translatable("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.ENTITY_CULLING.cast())
.setName(TextComponent.translatable("sodium.options.use_entity_culling.name"))
.setTooltip(TextComponent.translatable("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.ANIMATE_VISIBLE_TEXTURES.cast())
.setName(TextComponent.translatable("sodium.options.animate_only_visible_textures.name"))
.setTooltip(TextComponent.translatable("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.HIGH)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.setFlags(OptionFlag.REQUIRES_RENDERER_UPDATE)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.RENDER_PASS_CONSOLIDATION.cast())
.setName(TextComponent.translatable("embeddium.options.use_render_pass_consolidation.name"))
.setTooltip(TextComponent.translatable("embeddium.options.use_render_pass_consolidation.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.performance.useRenderPassConsolidation = value, opts -> opts.performance.useRenderPassConsolidation)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.RENDER_PASS_OPTIMIZATION.cast())
.setName(TextComponent.translatable("embeddium.options.use_render_pass_optimization.name"))
.setTooltip(TextComponent.translatable("embeddium.options.use_render_pass_optimization.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.performance.useRenderPassOptimization = value, opts -> opts.performance.useRenderPassOptimization)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
//? if <1.21.2 {
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.USE_FASTER_CLOUDS.cast())
.setName(TextComponent.translatable("embeddium.options.use_faster_clouds.name"))
.setTooltip(TextComponent.translatable("embeddium.options.use_faster_clouds.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.performance.useFasterClouds = value, opts -> opts.performance.useFasterClouds)
.build())
//?}
.build());
return new OptionPage(StandardOptions.Pages.PERFORMANCE, TextComponent.translatable("sodium.options.pages.performance"), List.copyOf(groups));
}
}
@@ -0,0 +1,7 @@
package org.embeddedt.embeddium.impl.gui.options;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
public interface TextProvider {
TextComponent getLocalizedName();
}
@@ -0,0 +1,10 @@
package org.embeddedt.embeddium.impl.gui.widgets;
import org.embeddedt.embeddium.impl.gui.framework.Interactable;
import org.embeddedt.embeddium.impl.gui.framework.Renderable;
public abstract class AbstractWidget implements Renderable, Interactable {
protected AbstractWidget() {
}
}
@@ -0,0 +1,136 @@
package org.embeddedt.embeddium.impl.gui.widgets;
import org.embeddedt.embeddium.impl.gui.framework.DrawContext;
import org.embeddedt.embeddium.impl.gui.framework.InteractionContext;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.util.Dim2i;
import org.embeddedt.embeddium.impl.gui.theme.DefaultColors;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class FlatButtonWidget extends AbstractWidget {
protected final Dim2i dim;
private final Runnable action;
private @NotNull Style style = Style.defaults();
private boolean selected;
private boolean enabled = true;
private boolean visible = true;
private boolean leftAligned;
private TextComponent label;
public FlatButtonWidget(Dim2i dim, TextComponent label, Runnable action) {
this.dim = dim;
this.label = label;
this.action = action;
}
protected int getLeftAlignedTextOffset(DrawContext drawContext) {
return 10;
}
protected boolean isHovered(int mouseX, int mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
@Override
public void render(DrawContext drawContext, int mouseX, int mouseY, float delta) {
if (!this.visible) {
return;
}
boolean hovered = this.isHovered(mouseX, mouseY);
int backgroundColor = this.enabled ? (hovered ? this.style.bgHovered : this.style.bgDefault) : this.style.bgDisabled;
int textColor = this.enabled ? this.style.textDefault : this.style.textDisabled;
int strWidth = drawContext.getStringWidth(this.label);
drawContext.fill(this.dim.x(), this.dim.y(), this.dim.getLimitX(), this.dim.getLimitY(), backgroundColor);
int textX;
if (this.leftAligned) {
textX = this.dim.x() + this.getLeftAlignedTextOffset(drawContext);
} else {
textX = this.dim.getCenterX() - (strWidth / 2);
}
drawContext.drawString(this.label, textX, this.dim.getCenterY() - 4, textColor);
if (this.enabled && this.selected) {
drawContext.fill(this.dim.x(), this.leftAligned ? this.dim.y() : (this.dim.getLimitY() - 1), this.leftAligned ? (this.dim.x() + 1) : this.dim.getLimitX(), this.dim.getLimitY(), DefaultColors.ELEMENT_ACTIVATED);
}
}
public void setStyle(@NotNull Style style) {
Objects.requireNonNull(style);
this.style = style;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setLeftAligned(boolean leftAligned) {
this.leftAligned = leftAligned;
}
@Override
public boolean mouseClicked(InteractionContext context, double mouseX, double mouseY, int button) {
if (!this.enabled || !this.visible) {
return false;
}
if (button == 0 && this.dim.containsCursor(mouseX, mouseY)) {
doAction(context);
return true;
}
return false;
}
private void doAction(InteractionContext context) {
this.action.run();
context.playClickSound();
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public void setLabel(TextComponent text) {
this.label = text;
}
public TextComponent getLabel() {
return this.label;
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return this.dim.containsCursor(mouseX, mouseY);
}
public static class Style {
public int bgHovered, bgDefault, bgDisabled;
public int textDefault, textDisabled;
public static Style defaults() {
var style = new Style();
style.bgHovered = 0xE0202020;
style.bgDefault = 0x90000000;
style.bgDisabled = 0x60000000;
style.textDefault = 0xFFFFFFFF;
style.textDisabled = 0x90FFFFFF;
return style;
}
}
}
@@ -0,0 +1,13 @@
package org.embeddedt.embeddium.impl.model.light;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
public interface DiffuseProvider {
DiffuseProvider NONE = (normalX, normalY, normalZ, shade) -> 1.0f;
float getDiffuse(float normalX, float normalY, float normalZ, boolean shade);
default float getDiffuse(ModelQuadFacing lightFace, boolean shade) {
return getDiffuse(lightFace.getStepX(), lightFace.getStepY(), lightFace.getStepZ(), shade);
}
}
@@ -0,0 +1,35 @@
package org.embeddedt.embeddium.impl.model.light;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.quad.ModelQuadView;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.jetbrains.annotations.NotNull;
/**
* Light pipelines allow model quads for any location in the world to be lit regardless of what produced them
* (blocks, fluids, or block entities).
*/
public interface LightPipeline {
/**
* Calculates the light data for a given block model quad, storing the result in {@param out}.
* @param quad The block model quad
* @param x x-coordinate of the model this quad belongs to
* @param y y-coordinate of the model this quad belongs to
* @param z z-coordinate of the model this quad belongs to
* @param out The data arrays which will store the calculated light data results
* @param cullFace The cull face of the quad, may be {@link ModelQuadFacing#UNASSIGNED} if there is none
* @param lightFace The light face of the quad, must not be {@link ModelQuadFacing#UNASSIGNED}
* @param shade True if the block is shaded by ambient occlusion
* @param applyAoDepthBlending True if AO for partially inset quads should be computed via blending the results
* for fully inset and non-inset quads, rather than assuming fully inset like vanilla
*/
void calculate(ModelQuadView quad, int x, int y, int z, QuadLightData out, @NotNull ModelQuadFacing cullFace,
@NotNull ModelQuadFacing lightFace, boolean shade, boolean applyAoDepthBlending);
/**
* Reset any cached data for this pipeline.
*/
default void reset() {
}
}
@@ -1,6 +1,5 @@
package org.embeddedt.embeddium.impl.model.light; package org.embeddedt.embeddium.impl.model.light;
import org.embeddedt.embeddium.impl.loader.common.LoaderServices;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess; import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline; import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline; import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
@@ -17,15 +16,10 @@ public class LightPipelineProvider {
private final EnumMap<LightMode, LightPipeline> lighters = new EnumMap<>(LightMode.class); private final EnumMap<LightMode, LightPipeline> lighters = new EnumMap<>(LightMode.class);
private final LightDataAccess lightData; private final LightDataAccess lightData;
public LightPipelineProvider(LightDataAccess cache, boolean enableDirectionalShading) { public LightPipelineProvider(LightDataAccess cache, DiffuseProvider diffuseProvider, boolean useQuadNormalsForShading) {
this.lightData = cache; this.lightData = cache;
if (LoaderServices.INSTANCE.hasCustomLightPipeline()) { this.lighters.put(LightMode.SMOOTH, new SmoothLightPipeline(cache, diffuseProvider, useQuadNormalsForShading));
this.lighters.put(LightMode.SMOOTH, LoaderServices.INSTANCE.createCustomLightPipeline(LightMode.SMOOTH, cache)); this.lighters.put(LightMode.FLAT, new FlatLightPipeline(cache, diffuseProvider, useQuadNormalsForShading));
this.lighters.put(LightMode.FLAT, LoaderServices.INSTANCE.createCustomLightPipeline(LightMode.FLAT, cache));
} else {
this.lighters.put(LightMode.SMOOTH, new SmoothLightPipeline(cache, enableDirectionalShading));
this.lighters.put(LightMode.FLAT, new FlatLightPipeline(cache, enableDirectionalShading));
}
} }
public LightPipeline getLighter(LightMode type) { public LightPipeline getLighter(LightMode type) {
@@ -1,13 +1,9 @@
package org.embeddedt.embeddium.impl.model.light.data; package org.embeddedt.embeddium.impl.model.light.data;
import net.minecraft.client.renderer.LevelRenderer; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import net.minecraft.client.renderer.LightTexture; import org.embeddedt.embeddium.impl.util.position.SectionPos;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import java.util.Arrays;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.block.state.BlockState;
import org.embeddedt.embeddium.impl.util.WorldUtil;
/** /**
* The light data cache is used to make accessing the light data and occlusion properties of blocks cheaper. The data * The light data cache is used to make accessing the light data and occlusion properties of blocks cheaper. The data
@@ -29,76 +25,61 @@ import org.embeddedt.embeddium.impl.util.WorldUtil;
* You can use the various static pack/unpack methods to extract these values in a usable format. * You can use the various static pack/unpack methods to extract these values in a usable format.
*/ */
public abstract class LightDataAccess { public abstract class LightDataAccess {
private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); private static final int NEIGHBOR_BLOCK_RADIUS = 2;
protected BlockAndTintGetter world; private static final int BLOCK_LENGTH = 16 + (NEIGHBOR_BLOCK_RADIUS * 2);
public int get(int x, int y, int z, Direction d1, Direction d2) { private final int[] light;
return this.get(x + d1.getStepX() + d2.getStepX(),
y + d1.getStepY() + d2.getStepY(), private int xOffset, yOffset, zOffset;
z + d1.getStepZ() + d2.getStepZ());
public LightDataAccess() {
this.light = new int[BLOCK_LENGTH * BLOCK_LENGTH * BLOCK_LENGTH];
} }
public int get(int x, int y, int z, Direction dir) { public void reset(int minBlockX, int minBlockY, int minBlockZ) {
return this.get(x + dir.getStepX(), this.xOffset = minBlockX - NEIGHBOR_BLOCK_RADIUS;
y + dir.getStepY(), this.yOffset = minBlockY - NEIGHBOR_BLOCK_RADIUS;
z + dir.getStepZ()); this.zOffset = minBlockZ - NEIGHBOR_BLOCK_RADIUS;
Arrays.fill(this.light, 0);
} }
public int get(BlockPos pos, Direction dir) { private int index(int x, int y, int z) {
return this.get(pos.getX(), pos.getY(), pos.getZ(), dir); int x2 = x - this.xOffset;
int y2 = y - this.yOffset;
int z2 = z - this.zOffset;
return (z2 * BLOCK_LENGTH * BLOCK_LENGTH) + (y2 * BLOCK_LENGTH) + x2;
} }
public int get(BlockPos pos) { protected abstract int compute(int x, int y, int z);
return this.get(pos.getX(), pos.getY(), pos.getZ());
}
/** /**
* Returns the light data for the block at the given position. The property fields can then be accessed using * Returns the light data for the block at the given position. The property fields can then be accessed using
* the various unpack methods below. * the various unpack methods below.
*/ */
public abstract int get(int x, int y, int z); public int get(int x, int y, int z) {
int l = this.index(x, y, z);
protected int compute(int x, int y, int z) { int word = this.light[l];
BlockPos pos = this.pos.set(x, y, z);
BlockAndTintGetter world = this.world;
BlockState state = world.getBlockState(pos); if (word != 0) {
return word;
boolean em = state.emissiveRendering(/*? if >=1.16 {*/world, pos/*?}*/);
boolean op = state.isViewBlocking(world, pos) && state.getLightBlock(/*? if <1.21.2 {*/world, pos/*?}*/) != 0;
boolean fo = state.isSolidRender(/*? if <1.21.2 {*/world, pos/*?}*/);
boolean fc = state.isCollisionShapeFullBlock(world, pos);
int lu = WorldUtil.getLightEmission(state, world, pos);
// OPTIMIZE: Do not calculate light data if the block is full and opaque and does not emit light.
int bl;
int sl;
if (fo && lu == 0) {
bl = 0;
sl = 0;
} else {
// calculate light data using custom approach for emissive blocks, and vanilla otherwise
if (em) {
bl = world.getBrightness(LightLayer.BLOCK, pos);
sl = world.getBrightness(LightLayer.SKY, pos);
} else {
// call the vanilla method so mods using custom lightmap logic work correctly
int packedCoords = LevelRenderer.getLightColor(/*? if >=1.21.5 {*//*LevelRenderer.BrightnessGetter.DEFAULT,*//*?}*/ world, state, pos);
bl = LightTexture.block(packedCoords);
sl = LightTexture.sky(packedCoords);
}
} }
// FIX: Do not apply AO from blocks that emit light return this.light[l] = this.compute(x, y, z);
float ao;
if (lu == 0) {
ao = state.getShadeBrightness(world, pos);
} else {
ao = 1.0f;
} }
return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packAO(ao) | packLU(lu) | packSL(sl) | packBL(bl); public int get(int x, int y, int z, ModelQuadFacing d1, ModelQuadFacing d2) {
return this.get(x + d1.getStepX() + d2.getStepX(),
y + d1.getStepY() + d2.getStepY(),
z + d1.getStepZ() + d2.getStepZ());
}
public int get(int x, int y, int z, ModelQuadFacing dir) {
return this.get(x + dir.getStepX(),
y + dir.getStepY(),
z + dir.getStepZ());
} }
public static int packBL(int blockLight) { public static int packBL(int blockLight) {
@@ -167,6 +148,18 @@ public abstract class LightDataAccess {
return ((word >>> 31) & 0b1) != 0; return ((word >>> 31) & 0b1) != 0;
} }
public static int pack(int block, int sky) {
return block << 4 | sky << 20;
}
public static int unpackBlock(int packed) {
return (packed & 0xFFFF) >> 4;
}
public static int unpackSky(int packed) {
return (packed >> 20) & 0xFFFF;
}
/** /**
* Computes the combined lightmap using block light, sky light, and luminance values. * Computes the combined lightmap using block light, sky light, and luminance values.
* *
@@ -175,10 +168,10 @@ public abstract class LightDataAccess {
* emissive check. * emissive check.
*/ */
public static int getLightmap(int word) { public static int getLightmap(int word) {
return LightTexture.pack(Math.max(unpackBL(word), unpackLU(word)), unpackSL(word)); return pack(Math.max(unpackBL(word), unpackLU(word)), unpackSL(word));
} }
public static final int FULL_BRIGHT = LightTexture.pack(15, 15); public static final int FULL_BRIGHT = pack(15, 15);
/** /**
* Like {@link #getLightmap(int)}, but checks {@link #unpackEM(int)} first and returns * Like {@link #getLightmap(int)}, but checks {@link #unpackEM(int)} first and returns
@@ -194,8 +187,4 @@ public abstract class LightDataAccess {
return getLightmap(word); return getLightmap(word);
} }
} }
public BlockAndTintGetter getWorld() {
return this.world;
}
} }
@@ -1,21 +1,14 @@
package org.embeddedt.embeddium.impl.model.light.flat; package org.embeddedt.embeddium.impl.model.light.flat;
//? if forgelike && <1.19 import lombok.RequiredArgsConstructor;
/*import net.minecraftforge.client.model.pipeline.LightUtil;*/ import org.embeddedt.embeddium.impl.model.light.DiffuseProvider;
import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.model.light.LightPipeline; import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess; import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData; import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.quad.ModelQuadView; import org.embeddedt.embeddium.impl.model.quad.ModelQuadView;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.api.util.NormI8; import org.embeddedt.embeddium.api.util.NormI8;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState;
import org.embeddedt.embeddium.impl.util.WorldUtil;
import java.util.Arrays; import java.util.Arrays;
@@ -25,81 +18,68 @@ import static org.embeddedt.embeddium.impl.model.light.data.LightDataAccess.*;
* A light pipeline which implements "classic-style" lighting through simply using the light value of the adjacent * A light pipeline which implements "classic-style" lighting through simply using the light value of the adjacent
* block to a face. * block to a face.
*/ */
@RequiredArgsConstructor
public class FlatLightPipeline implements LightPipeline { public class FlatLightPipeline implements LightPipeline {
/** /**
* The cache which light data will be accessed from. * The cache which light data will be accessed from.
*/ */
private final LightDataAccess lightCache; private final LightDataAccess lightCache;
/**
* Used to retrieve the directional shading value for quads.
*/
private final DiffuseProvider diffuseProvider;
/** /**
* Whether or not to even attempt to shade quads using their normals rather than light face. * Whether or not to even attempt to shade quads using their normals rather than light face.
*/ */
private final boolean useQuadNormalsForShading; private final boolean useQuadNormalsForShading;
/**
* Whether directional shading should be enabled.
*/
private final boolean enableDirectionalShading;
public FlatLightPipeline(LightDataAccess lightCache, boolean enableDirectionalShading) {
this.lightCache = lightCache;
this.enableDirectionalShading = enableDirectionalShading;
this.useQuadNormalsForShading = Celeritas.options().quality.useQuadNormalsForShading;
}
@Override @Override
public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade) { public void calculate(ModelQuadView quad, int x, int y, int z, QuadLightData out, ModelQuadFacing cullFace, ModelQuadFacing lightFace, boolean shade, boolean applyAoDepthBlending) {
int lightmap; int lightmap;
if (!lightFace.isDirection()) {
throw new IllegalStateException();
}
// To match vanilla behavior, use the cull face if it exists/is available // To match vanilla behavior, use the cull face if it exists/is available
if (cullFace != null) { if (cullFace.isDirection()) {
lightmap = getOffsetLightmap(pos, cullFace); lightmap = getOffsetLightmap(x, y, z, cullFace);
} else { } else {
int flags = quad.getFlags(); int flags = quad.getFlags();
// If the face is aligned, use the light data above it // If the face is aligned, use the light data above it
// To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube // To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube
if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && unpackFC(this.lightCache.get(pos)))) { if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && unpackFC(this.lightCache.get(x, y, z)))) {
lightmap = getOffsetLightmap(pos, lightFace); lightmap = getOffsetLightmap(x, y, z, lightFace);
} else { } else {
lightmap = getEmissiveLightmap(this.lightCache.get(pos)); lightmap = getEmissiveLightmap(this.lightCache.get(x, y, z));
} }
} }
Arrays.fill(out.lm, lightmap); Arrays.fill(out.lm, lightmap);
if (enableDirectionalShading) {
//? if forgelike
if ((quad.getFlags() & ModelQuadFlags.IS_VANILLA_SHADED) != 0 || !this.useQuadNormalsForShading) { if ((quad.getFlags() & ModelQuadFlags.IS_VANILLA_SHADED) != 0 || !this.useQuadNormalsForShading) {
Arrays.fill(out.br, WorldUtil.getShade(this.lightCache.getWorld(), lightFace, shade)); Arrays.fill(out.br, this.diffuseProvider.getDiffuse(lightFace, shade));
/*? if forgelike {*/ } else {
this.applySidedBrightnessFromNormals(quad, out, shade);
} /*?}*/
} else { } else {
Arrays.fill(out.br, 1.0f); this.applySidedBrightnessFromNormals(quad, out, shade);
} }
} }
//? if forgelike && >=1.19 {
public void applySidedBrightnessFromNormals(ModelQuadView quad, QuadLightData out, boolean shade) { public void applySidedBrightnessFromNormals(ModelQuadView quad, QuadLightData out, boolean shade) {
int normal = quad.getModFaceNormal(); int normal = quad.getModFaceNormal();
Arrays.fill(out.br, this.lightCache.getWorld().getShade(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal), shade)); Arrays.fill(out.br, this.diffuseProvider.getDiffuse(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal), shade));
} }
//?} else if forgelike && <=1.19 {
/*private void applySidedBrightnessFromNormals(ModelQuadView quad, QuadLightData out, boolean shade) {
int normal = quad.getModFaceNormal();
Arrays.fill(out.br, shade ? LightUtil.diffuseLight(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal)) : 1.0f);
}
*///?}
/** /**
* When vanilla computes an offset lightmap with flat lighting, it passes the original BlockState but the * When vanilla computes an offset lightmap with flat lighting, it passes the original BlockState but the
* offset BlockPos to {@link LevelRenderer#getLightColor(BlockAndTintGetter, BlockState, BlockPos)}. * offset BlockPos to LevelRenderer.getLightColor(BlockAndTintGetter, BlockState, BlockPos).
* This does not make much sense but fixes certain issues, primarily dark quads on light-emitting blocks * This does not make much sense but fixes certain issues, primarily dark quads on light-emitting blocks
* behind tinted glass. {@link LightDataAccess} cannot efficiently store lightmaps computed with * behind tinted glass. {@link LightDataAccess} cannot efficiently store lightmaps computed with
* inconsistent values so this method exists to mirror vanilla behavior as closely as possible. * inconsistent values so this method exists to mirror vanilla behavior as closely as possible.
*/ */
private int getOffsetLightmap(BlockPos pos, Direction face) { private int getOffsetLightmap(int x, int y, int z, ModelQuadFacing face) {
int word = this.lightCache.get(pos); int word = this.lightCache.get(x, y, z);
// Check emissivity of the origin state // Check emissivity of the origin state
if (unpackEM(word)) { if (unpackEM(word)) {
@@ -107,7 +87,7 @@ public class FlatLightPipeline implements LightPipeline {
} }
// Use world light values from the offset pos, but luminance from the origin pos // Use world light values from the offset pos, but luminance from the origin pos
int adjWord = this.lightCache.get(pos, face); int adjWord = this.lightCache.get(x, y, z, face);
return LightTexture.pack(Math.max(unpackBL(adjWord), unpackLU(word)), unpackSL(adjWord)); return LightDataAccess.pack(Math.max(unpackBL(adjWord), unpackLU(word)), unpackSL(adjWord));
} }
} }
@@ -1,11 +1,9 @@
package org.embeddedt.embeddium.impl.model.light.smooth; package org.embeddedt.embeddium.impl.model.light.smooth;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess; import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import net.minecraft.client.renderer.LightTexture; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import static org.embeddedt.embeddium.impl.model.light.data.ArrayLightDataCache.*; import static org.embeddedt.embeddium.impl.model.light.data.LightDataAccess.*;
class AoFaceData { class AoFaceData {
public final int[] lm = new int[4]; public final int[] lm = new int[4];
@@ -16,11 +14,7 @@ class AoFaceData {
private int flags; private int flags;
public void initLightData(LightDataAccess cache, BlockPos pos, Direction direction, boolean offset) { public void initLightData(LightDataAccess cache, int x, int y, int z, ModelQuadFacing direction, boolean offset) {
final int x = pos.getX();
final int y = pos.getY();
final int z = pos.getZ();
final int adjX; final int adjX;
final int adjY; final int adjY;
final int adjZ; final int adjZ;
@@ -51,7 +45,7 @@ class AoFaceData {
final float caao = unpackAO(adjWord); final float caao = unpackAO(adjWord);
Direction[] faces = AoNeighborInfo.get(direction).faces; ModelQuadFacing[] faces = AoNeighborInfo.get(direction).faces;
final int e0 = cache.get(adjX, adjY, adjZ, faces[0]); final int e0 = cache.get(adjX, adjY, adjZ, faces[0]);
final int e0lm = getLightmap(e0); final int e0lm = getLightmap(e0);
@@ -1,6 +1,6 @@
package org.embeddedt.embeddium.impl.model.light.smooth; package org.embeddedt.embeddium.impl.model.light.smooth;
import net.minecraft.core.Direction; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
/** /**
* The neighbor information for each face of a block, used when performing smooth lighting in order to calculate * The neighbor information for each face of a block, used when performing smooth lighting in order to calculate
@@ -8,11 +8,11 @@ import net.minecraft.core.Direction;
*/ */
@SuppressWarnings("UnnecessaryLocalVariable") @SuppressWarnings("UnnecessaryLocalVariable")
enum AoNeighborInfo { enum AoNeighborInfo {
DOWN(new Direction[] { Direction.WEST, Direction.EAST, Direction.NORTH, Direction.SOUTH }, 0.5F) { POS_X(new ModelQuadFacing[] { ModelQuadFacing.NEG_Y, ModelQuadFacing.POS_Y, ModelQuadFacing.NEG_Z, ModelQuadFacing.POS_Z }, 0.6F) {
@Override @Override
public void calculateCornerWeights(float x, float y, float z, float[] out) { public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = z; final float u = z;
final float v = 1.0f - x; final float v = 1.0f - y;
out[0] = v * u; out[0] = v * u;
out[1] = v * (1.0f - u); out[1] = v * (1.0f - u);
@@ -22,23 +22,23 @@ enum AoNeighborInfo {
@Override @Override
public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) {
lm1[0] = lm0[0]; lm1[1] = lm0[0];
lm1[1] = lm0[1]; lm1[2] = lm0[1];
lm1[2] = lm0[2]; lm1[3] = lm0[2];
lm1[3] = lm0[3]; lm1[0] = lm0[3];
ao1[0] = ao0[0]; ao1[1] = ao0[0];
ao1[1] = ao0[1]; ao1[2] = ao0[1];
ao1[2] = ao0[2]; ao1[3] = ao0[2];
ao1[3] = ao0[3]; ao1[0] = ao0[3];
} }
@Override @Override
public float getDepth(float x, float y, float z) { public float getDepth(float x, float y, float z) {
return y; return 1.0f - x;
} }
}, },
UP(new Direction[] { Direction.EAST, Direction.WEST, Direction.NORTH, Direction.SOUTH }, 1.0F) { POS_Y(new ModelQuadFacing[] { ModelQuadFacing.POS_X, ModelQuadFacing.NEG_X, ModelQuadFacing.NEG_Z, ModelQuadFacing.POS_Z }, 1.0F) {
@Override @Override
public void calculateCornerWeights(float x, float y, float z, float[] out) { public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = z; final float u = z;
@@ -68,37 +68,7 @@ enum AoNeighborInfo {
return 1.0f - y; return 1.0f - y;
} }
}, },
NORTH(new Direction[] { Direction.UP, Direction.DOWN, Direction.EAST, Direction.WEST }, 0.8F) { POS_Z(new ModelQuadFacing[] { ModelQuadFacing.NEG_X, ModelQuadFacing.POS_X, ModelQuadFacing.NEG_Y, ModelQuadFacing.POS_Y }, 0.8F) {
@Override
public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = 1.0f - x;
final float v = y;
out[0] = v * u;
out[1] = v * (1.0f - u);
out[2] = (1.0f - v) * (1.0f - u);
out[3] = (1.0f - v) * u;
}
@Override
public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) {
lm1[3] = lm0[0];
lm1[0] = lm0[1];
lm1[1] = lm0[2];
lm1[2] = lm0[3];
ao1[3] = ao0[0];
ao1[0] = ao0[1];
ao1[1] = ao0[2];
ao1[2] = ao0[3];
}
@Override
public float getDepth(float x, float y, float z) {
return z;
}
},
SOUTH(new Direction[] { Direction.WEST, Direction.EAST, Direction.DOWN, Direction.UP }, 0.8F) {
@Override @Override
public void calculateCornerWeights(float x, float y, float z, float[] out) { public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = y; final float u = y;
@@ -128,7 +98,7 @@ enum AoNeighborInfo {
return 1.0f - z; return 1.0f - z;
} }
}, },
WEST(new Direction[] { Direction.UP, Direction.DOWN, Direction.NORTH, Direction.SOUTH }, 0.6F) { NEG_X(new ModelQuadFacing[] { ModelQuadFacing.POS_Y, ModelQuadFacing.NEG_Y, ModelQuadFacing.NEG_Z, ModelQuadFacing.POS_Z }, 0.6F) {
@Override @Override
public void calculateCornerWeights(float x, float y, float z, float[] out) { public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = z; final float u = z;
@@ -158,11 +128,11 @@ enum AoNeighborInfo {
return x; return x;
} }
}, },
EAST(new Direction[] { Direction.DOWN, Direction.UP, Direction.NORTH, Direction.SOUTH }, 0.6F) { NEG_Y(new ModelQuadFacing[] { ModelQuadFacing.NEG_X, ModelQuadFacing.POS_X, ModelQuadFacing.NEG_Z, ModelQuadFacing.POS_Z }, 0.5F) {
@Override @Override
public void calculateCornerWeights(float x, float y, float z, float[] out) { public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = z; final float u = z;
final float v = 1.0f - y; final float v = 1.0f - x;
out[0] = v * u; out[0] = v * u;
out[1] = v * (1.0f - u); out[1] = v * (1.0f - u);
@@ -172,40 +142,81 @@ enum AoNeighborInfo {
@Override @Override
public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) { public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) {
lm1[1] = lm0[0]; lm1[0] = lm0[0];
lm1[2] = lm0[1]; lm1[1] = lm0[1];
lm1[3] = lm0[2]; lm1[2] = lm0[2];
lm1[0] = lm0[3]; lm1[3] = lm0[3];
ao1[1] = ao0[0]; ao1[0] = ao0[0];
ao1[2] = ao0[1]; ao1[1] = ao0[1];
ao1[3] = ao0[2]; ao1[2] = ao0[2];
ao1[0] = ao0[3]; ao1[3] = ao0[3];
} }
@Override @Override
public float getDepth(float x, float y, float z) { public float getDepth(float x, float y, float z) {
return 1.0f - x; return y;
}
},
NEG_Z(new ModelQuadFacing[] { ModelQuadFacing.POS_Y, ModelQuadFacing.NEG_Y, ModelQuadFacing.POS_X, ModelQuadFacing.NEG_X }, 0.8F) {
@Override
public void calculateCornerWeights(float x, float y, float z, float[] out) {
final float u = 1.0f - x;
final float v = y;
out[0] = v * u;
out[1] = v * (1.0f - u);
out[2] = (1.0f - v) * (1.0f - u);
out[3] = (1.0f - v) * u;
}
@Override
public void mapCorners(int[] lm0, float[] ao0, int[] lm1, float[] ao1) {
lm1[3] = lm0[0];
lm1[0] = lm0[1];
lm1[1] = lm0[2];
lm1[2] = lm0[3];
ao1[3] = ao0[0];
ao1[0] = ao0[1];
ao1[1] = ao0[2];
ao1[2] = ao0[3];
}
@Override
public float getDepth(float x, float y, float z) {
return z;
} }
}; };
private static final AoNeighborInfo[] VALUES = AoNeighborInfo.values();
/** /**
* The direction of each corner block from this face, which can be retrieved by offsetting the position of the origin * The direction of each corner block from this face, which can be retrieved by offsetting the position of the origin
* block by the direction vector. * block by the direction vector.
*/ */
public final Direction[] faces; public final ModelQuadFacing[] faces;
/** /**
* The constant brightness modifier for this face. This data exists to emulate the results of the OpenGL lighting * The constant brightness modifier for this face. This data exists to emulate the results of the OpenGL lighting
* model which gives a faux directional light appearance to blocks in the game. Not currently used. * model which gives a faux directional light appearance to blocks in the game. Not currently used.
*/ */
public final float strength; public final float strength;
AoNeighborInfo(Direction[] directions, float strength) { AoNeighborInfo(ModelQuadFacing[] directions, float strength) {
this.faces = directions; this.faces = directions;
this.strength = strength; this.strength = strength;
} }
/**
* @return Returns the {@link AoNeighborInfo} which corresponds with the specified direction
*/
public static AoNeighborInfo get(ModelQuadFacing direction) {
if (!direction.isDirection()) {
throw new IllegalArgumentException();
}
return VALUES[direction.ordinal()];
}
/** /**
* Calculates how much each corner contributes to the final "darkening" of the vertex at the specified position. The * Calculates how much each corner contributes to the final "darkening" of the vertex at the specified position. The
* weight is a function of the distance from the vertex's position to the corner block's position. * weight is a function of the distance from the vertex's position to the corner block's position.
@@ -238,13 +249,4 @@ enum AoNeighborInfo {
* @return The depth of the vertex into this face * @return The depth of the vertex into this face
*/ */
public abstract float getDepth(float x, float y, float z); public abstract float getDepth(float x, float y, float z);
private static final AoNeighborInfo[] VALUES = AoNeighborInfo.values();
/**
* @return Returns the {@link AoNeighborInfo} which corresponds with the specified direction
*/
public static AoNeighborInfo get(Direction direction) {
return VALUES[direction.get3DDataValue()];
}
} }
@@ -1,20 +1,15 @@
package org.embeddedt.embeddium.impl.model.light.smooth; package org.embeddedt.embeddium.impl.model.light.smooth;
//? if forgelike && <1.19 import org.embeddedt.embeddium.impl.common.util.MathUtil;
/*import net.minecraftforge.client.model.pipeline.LightUtil;*/ import org.embeddedt.embeddium.impl.model.light.DiffuseProvider;
import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.model.light.LightPipeline; import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess; import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData; import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.quad.ModelQuadView; import org.embeddedt.embeddium.impl.model.quad.ModelQuadView;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.api.util.NormI8; import org.embeddedt.embeddium.api.util.NormI8;
import net.minecraft.core.BlockPos; import org.embeddedt.embeddium.impl.util.PositionUtil;
import net.minecraft.core.Direction;
import net.minecraft.util.Mth;
import org.embeddedt.embeddium.impl.util.WorldUtil;
import java.util.Arrays;
/** /**
* A light pipeline which produces smooth interpolated lighting and ambient occlusion for model quads. This * A light pipeline which produces smooth interpolated lighting and ambient occlusion for model quads. This
@@ -22,8 +17,6 @@ import java.util.Arrays;
* *
* - Corner blocks are now selected from the correct set of neighbors above block faces (fixes MC-148689 and MC-12558) * - Corner blocks are now selected from the correct set of neighbors above block faces (fixes MC-148689 and MC-12558)
* - Shading issues caused by anisotropy are fixed by re-orientating quads to a consistent ordering (fixes MC-138211) * - Shading issues caused by anisotropy are fixed by re-orientating quads to a consistent ordering (fixes MC-138211)
* - Inset block faces are correctly shaded by their neighbors, fixing a number of problems with non-full blocks such as
* grass paths (fixes MC-11783 and MC-108621)
* - Blocks next to emissive blocks are too bright (MC-260989) * - Blocks next to emissive blocks are too bright (MC-260989)
* - Synchronization issues between the main render thread's light engine and chunk build worker threads are corrected * - Synchronization issues between the main render thread's light engine and chunk build worker threads are corrected
* by copying light data alongside block states, fixing a number of inconsistencies in baked chunks (no open issue) * by copying light data alongside block states, fixing a number of inconsistencies in baked chunks (no open issue)
@@ -68,24 +61,27 @@ public class SmoothLightPipeline implements LightPipeline {
private final boolean useQuadNormalsForShading; private final boolean useQuadNormalsForShading;
/** /**
* Whether directional shading should be enabled. * Used to retrieve the directional shading value for quads.
*/ */
private final boolean enableDirectionalShading; private final DiffuseProvider diffuseProvider;
public SmoothLightPipeline(LightDataAccess cache, boolean enableDirectionalShading) { private float lastAo, lastBl, lastSl;
public SmoothLightPipeline(LightDataAccess cache, DiffuseProvider diffuseProvider, boolean useQuadNormalsForShading) {
this.lightCache = cache; this.lightCache = cache;
for (int i = 0; i < this.cachedFaceData.length; i++) { for (int i = 0; i < this.cachedFaceData.length; i++) {
this.cachedFaceData[i] = new AoFaceData(); this.cachedFaceData[i] = new AoFaceData();
} }
this.useQuadNormalsForShading = Celeritas.options().quality.useQuadNormalsForShading; this.useQuadNormalsForShading = useQuadNormalsForShading;
this.enableDirectionalShading = enableDirectionalShading; this.diffuseProvider = diffuseProvider;
} }
@Override @Override
public void calculate(ModelQuadView quad, BlockPos pos, QuadLightData out, Direction cullFace, Direction lightFace, boolean shade) { public void calculate(ModelQuadView quad, int x, int y, int z, QuadLightData out, ModelQuadFacing cullFace, ModelQuadFacing lightFace,
this.updateCachedData(pos.asLong()); boolean shade, boolean applyAoDepthBlending) {
this.updateCachedData(PositionUtil.packBlock(x, y, z));
int flags = quad.getFlags(); int flags = quad.getFlags();
@@ -95,29 +91,27 @@ public class SmoothLightPipeline implements LightPipeline {
// map the corner values onto this quad's vertices. This covers most situations during rendering and provides // map the corner values onto this quad's vertices. This covers most situations during rendering and provides
// a modest speed-up. // a modest speed-up.
// To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube // To match vanilla behavior, also treat the face as aligned if it is parallel and the block state is a full cube
if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(pos)))) { if ((flags & ModelQuadFlags.IS_ALIGNED) != 0 || ((flags & ModelQuadFlags.IS_PARALLEL) != 0 && LightDataAccess.unpackFC(this.lightCache.get(x, y, z)))) {
if ((flags & ModelQuadFlags.IS_PARTIAL) == 0) { if ((flags & ModelQuadFlags.IS_PARTIAL) == 0) {
this.applyAlignedFullFace(neighborInfo, pos, lightFace, out); this.applyAlignedFullFace(neighborInfo, x, y, z, lightFace, out);
} else { } else {
this.applyAlignedPartialFace(neighborInfo, quad, pos, lightFace, out); this.applyAlignedPartialFace(neighborInfo, quad, x, y, z, lightFace, out);
} }
} else if ((flags & ModelQuadFlags.IS_PARALLEL) != 0) {
this.applyParallelFace(neighborInfo, quad, pos, lightFace, out);
} else { } else {
this.applyNonParallelFace(neighborInfo, quad, pos, lightFace, out); if ((flags & ModelQuadFlags.IS_VANILLA_SHADED) == 0 && quad.getNormalFace() == ModelQuadFacing.UNASSIGNED) {
// Normal has multiple nonzero components
this.applyIrregularFace(quad, x, y, z, out, applyAoDepthBlending);
} else {
// Normal has a single nonzero component
this.applyNonParallelFace(neighborInfo, quad, x, y, z, lightFace, out, applyAoDepthBlending);
}
} }
if (enableDirectionalShading) {
//? if forgelike {
if((flags & ModelQuadFlags.IS_VANILLA_SHADED) != 0 || !this.useQuadNormalsForShading) { if((flags & ModelQuadFlags.IS_VANILLA_SHADED) != 0 || !this.useQuadNormalsForShading) {
this.applySidedBrightness(out, lightFace, shade); this.applySidedBrightness(out, lightFace, shade);
} else { } else {
this.applySidedBrightnessFromNormals(out, quad, shade); this.applySidedBrightnessFromNormals(out, quad, shade);
} }
//?} else {
/*this.applySidedBrightness(out, lightFace, shade);
*///?}
}
} }
@Override @Override
@@ -131,8 +125,8 @@ public class SmoothLightPipeline implements LightPipeline {
* have two contributing sides. * have two contributing sides.
* Flags: IS_ALIGNED, !IS_PARTIAL * Flags: IS_ALIGNED, !IS_PARTIAL
*/ */
private void applyAlignedFullFace(AoNeighborInfo neighborInfo, BlockPos pos, Direction dir, QuadLightData out) { private void applyAlignedFullFace(AoNeighborInfo neighborInfo, int x, int y, int z, ModelQuadFacing dir, QuadLightData out) {
AoFaceData faceData = this.getCachedFaceData(pos, dir, true); AoFaceData faceData = this.getCachedFaceData(x, y, z, dir, true);
neighborInfo.mapCorners(faceData.lm, faceData.ao, out.lm, out.br); neighborInfo.mapCorners(faceData.lm, faceData.ao, out.lm, out.br);
} }
@@ -140,7 +134,7 @@ public class SmoothLightPipeline implements LightPipeline {
* Calculates the light data for a grid-aligned quad that does not cover the entire block volume's face. * Calculates the light data for a grid-aligned quad that does not cover the entire block volume's face.
* Flags: IS_ALIGNED, IS_PARTIAL * Flags: IS_ALIGNED, IS_PARTIAL
*/ */
private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, Direction dir, QuadLightData out) { private void applyAlignedPartialFace(AoNeighborInfo neighborInfo, ModelQuadView quad, int x, int y, int z, ModelQuadFacing dir, QuadLightData out) {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
// Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting
float cx = clamp(quad.getX(i)); float cx = clamp(quad.getX(i));
@@ -149,45 +143,17 @@ public class SmoothLightPipeline implements LightPipeline {
float[] weights = this.weights; float[] weights = this.weights;
neighborInfo.calculateCornerWeights(cx, cy, cz, weights); neighborInfo.calculateCornerWeights(cx, cy, cz, weights);
this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, true); this.applyAlignedPartialFaceVertex(x, y, z, dir, weights, true);
} out.br[i] = lastAo;
} out.lm[i] = getLightMapCoord(lastSl, lastBl);
/**
* This method is the same as {@link #applyNonParallelFace(AoNeighborInfo, ModelQuadView, BlockPos, Direction,
* QuadLightData)} but with the check for a depth of approximately 0 removed. If the quad is parallel but not
* aligned, all of its vertices will have the same depth and this depth must be approximately greater than 0,
* meaning the check for 0 will always return false.
* Flags: !IS_ALIGNED, IS_PARALLEL
*/
private void applyParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, Direction dir, QuadLightData out) {
for (int i = 0; i < 4; i++) {
// Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting
float cx = clamp(quad.getX(i));
float cy = clamp(quad.getY(i));
float cz = clamp(quad.getZ(i));
float[] weights = this.weights;
neighborInfo.calculateCornerWeights(cx, cy, cz, weights);
float depth = neighborInfo.getDepth(cx, cy, cz);
// If the quad is approximately grid-aligned (not inset) to the other side of the block, avoid unnecessary
// computation by treating it is as aligned
if (Mth.equal(depth, 1.0F)) {
this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, false);
} else {
// Blend the occlusion factor between the blocks directly beside this face and the blocks above it
// based on how inset the face is. This fixes a few issues with blocks such as farmland and paths.
this.applyInsetPartialFaceVertex(pos, dir, depth, 1.0f - depth, weights, i, out);
}
} }
} }
/** /**
* Flags: !IS_ALIGNED, !IS_PARALLEL * Flags: !IS_ALIGNED, !IS_PARALLEL
*/ */
private void applyNonParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, BlockPos pos, Direction dir, QuadLightData out) { private void applyNonParallelFace(AoNeighborInfo neighborInfo, ModelQuadView quad, int x, int y, int z, ModelQuadFacing dir,
QuadLightData out, boolean applyAoDepthBlending) {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
// Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting // Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting
float cx = clamp(quad.getX(i)); float cx = clamp(quad.getX(i));
@@ -199,58 +165,123 @@ public class SmoothLightPipeline implements LightPipeline {
float depth = neighborInfo.getDepth(cx, cy, cz); float depth = neighborInfo.getDepth(cx, cy, cz);
// If the quad is approximately grid-aligned (not inset), avoid unnecessary computation by treating it is as aligned if (applyAoDepthBlending) {
if (Mth.equal(depth, 0.0F)) {
this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, true);
} else if (Mth.equal(depth, 1.0F)) {
this.applyAlignedPartialFaceVertex(pos, dir, weights, i, out, false);
} else {
// Blend the occlusion factor between the blocks directly beside this face and the blocks above it // Blend the occlusion factor between the blocks directly beside this face and the blocks above it
// based on how inset the face is. This fixes a few issues with blocks such as farmland and paths. // based on how inset the face is. This fixes a few issues with blocks such as farmland and paths.
this.applyInsetPartialFaceVertex(pos, dir, depth, 1.0f - depth, weights, i, out); this.applyInsetPartialFaceVertex(x, y, z, dir, depth, 1.0f - depth, weights);
} } else {
} this.applyAlignedPartialFaceVertex(x, y, z, dir, weights, MathUtil.roughlyEqual(depth, 0.0F));
} }
private void applyAlignedPartialFaceVertex(BlockPos pos, Direction dir, float[] w, int i, QuadLightData out, boolean offset) { out.br[i] = lastAo;
AoFaceData faceData = this.getCachedFaceData(pos, dir, offset); out.lm[i] = getLightMapCoord(lastSl, lastBl);
}
if (!faceData.hasUnpackedLightData()) {
faceData.unpackLightData();
} }
float sl = faceData.getBlendedSkyLight(w); private void applyInsetPartialFaceVertex(int x, int y, int z, ModelQuadFacing dir, float n1d, float n2d, float[] w) {
float bl = faceData.getBlendedBlockLight(w); // Avoid blending when the depth is close to one value or the other
float ao = faceData.getBlendedShade(w); if (MathUtil.roughlyEqual(n1d, 0.0f)) {
this.applyAlignedPartialFaceVertex(x, y, z, dir, w, true);
out.br[i] = ao; return;
out.lm[i] = getLightMapCoord(sl, bl); } else if (MathUtil.roughlyEqual(n1d, 1.0f)) {
this.applyAlignedPartialFaceVertex(x, y, z, dir, w, false);
return;
} }
private void applyInsetPartialFaceVertex(BlockPos pos, Direction dir, float n1d, float n2d, float[] w, int i, QuadLightData out) { AoFaceData n1 = this.getCachedFaceData(x, y, z, dir, false);
AoFaceData n1 = this.getCachedFaceData(pos, dir, false);
if (!n1.hasUnpackedLightData()) { if (!n1.hasUnpackedLightData()) {
n1.unpackLightData(); n1.unpackLightData();
} }
AoFaceData n2 = this.getCachedFaceData(pos, dir, true); AoFaceData n2 = this.getCachedFaceData(x, y, z, dir, true);
if (!n2.hasUnpackedLightData()) { if (!n2.hasUnpackedLightData()) {
n2.unpackLightData(); n2.unpackLightData();
} }
// Blend between the direct neighbors and above based on the passed weights // Blend between the direct neighbors and above based on the passed weights
float ao = (n1.getBlendedShade(w) * n1d) + (n2.getBlendedShade(w) * n2d); this.lastAo = (n1.getBlendedShade(w) * n1d) + (n2.getBlendedShade(w) * n2d);
float sl = (n1.getBlendedSkyLight(w) * n1d) + (n2.getBlendedSkyLight(w) * n2d); this.lastSl = (n1.getBlendedSkyLight(w) * n1d) + (n2.getBlendedSkyLight(w) * n2d);
float bl = (n1.getBlendedBlockLight(w) * n1d) + (n2.getBlendedBlockLight(w) * n2d); this.lastBl = (n1.getBlendedBlockLight(w) * n1d) + (n2.getBlendedBlockLight(w) * n2d);
out.br[i] = ao;
out.lm[i] = getLightMapCoord(sl, bl);
} }
private void applySidedBrightness(QuadLightData out, Direction face, boolean shade) { private static final float BLENDED_WEIGHT = 0.75f;
float brightness = WorldUtil.getShade(this.lightCache.getWorld(), face, shade); private static final float MAX_WEIGHT = 1f - BLENDED_WEIGHT;
private void applyIrregularFace(ModelQuadView quad, int x, int y, int z, QuadLightData out, boolean applyAoDepthBlending) {
for (int i = 0; i < 4; i++) {
// Clamp the vertex positions to the block's boundaries to prevent weird errors in lighting
float cx = clamp(quad.getX(i));
float cy = clamp(quad.getY(i));
float cz = clamp(quad.getZ(i));
int normal = quad.getForgeNormal(i);
if (normal == 0) {
normal = quad.getComputedFaceNormal();
}
float weightedAo = 0, weightedBl = 0, weightedSl = 0;
float maxAo = 0, maxBl = 0, maxSl = 0;
// Compute the values that each axis would contribute, then combine them
for (int axis = 0; axis < 3; axis++) {
// Unpack the desired normal component
float projectedNormal = NormI8.unpackX(normal >> (axis * 8));
// Skip any components that are zero (they will never contribute anything)
if (projectedNormal == 0) {
continue;
}
var dir = ModelQuadFacing.AXES[axis].getFacing(projectedNormal > 0);
var neighborInfo = AoNeighborInfo.get(dir);
float[] weights = this.weights;
neighborInfo.calculateCornerWeights(cx, cy, cz, weights);
float depth = neighborInfo.getDepth(cx, cy, cz);
if (applyAoDepthBlending) {
// Blend the occlusion factor between the blocks directly beside this face and the blocks above it
// based on how inset the face is. This fixes a few issues with blocks such as farmland and paths.
this.applyInsetPartialFaceVertex(x, y, z, dir, depth, 1.0f - depth, weights);
} else {
// Use inset data as soon as the face is even partially inset
this.applyAlignedPartialFaceVertex(x, y, z, dir, weights, MathUtil.roughlyEqual(depth, 0.0F));
}
float ao = this.lastAo, sl = this.lastSl, bl = this.lastBl;
float combineWeight = projectedNormal * projectedNormal;
weightedAo += ao * combineWeight;
weightedBl += bl * combineWeight;
weightedSl += sl * combineWeight;
maxAo = Math.max(ao, maxAo);
maxSl = Math.max(sl, maxSl);
maxBl = Math.max(bl, maxBl);
}
out.br[i] = clamp(weightedAo * BLENDED_WEIGHT + maxAo * MAX_WEIGHT);
out.lm[i] = getLightMapCoord(weightedSl * BLENDED_WEIGHT + maxSl * MAX_WEIGHT, weightedBl * BLENDED_WEIGHT + maxBl * MAX_WEIGHT);
}
}
private void applyAlignedPartialFaceVertex(int x, int y, int z, ModelQuadFacing dir, float[] w, boolean offset) {
AoFaceData faceData = this.getCachedFaceData(x, y, z, dir, offset);
if (!faceData.hasUnpackedLightData()) {
faceData.unpackLightData();
}
this.lastSl = faceData.getBlendedSkyLight(w);
this.lastBl = faceData.getBlendedBlockLight(w);
this.lastAo = faceData.getBlendedShade(w);
}
private void applySidedBrightness(QuadLightData out, ModelQuadFacing face, boolean shade) {
float brightness = this.diffuseProvider.getDiffuse(face, shade);
float[] br = out.br; float[] br = out.br;
for (int i = 0; i < br.length; i++) { for (int i = 0; i < br.length; i++) {
@@ -258,37 +289,25 @@ public class SmoothLightPipeline implements LightPipeline {
} }
} }
//? if forgelike && >=1.19 {
private void applySidedBrightnessFromNormals(QuadLightData out, ModelQuadView quad, boolean shade) { private void applySidedBrightnessFromNormals(QuadLightData out, ModelQuadView quad, boolean shade) {
// TODO: consider calculating for vertex if mods actually change normals per-vertex // TODO: consider calculating for vertex if mods actually change normals per-vertex
int normal = quad.getModFaceNormal(); int normal = quad.getModFaceNormal();
float brightness = this.lightCache.getWorld().getShade(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal), shade); float brightness = this.diffuseProvider.getDiffuse(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal), shade);
float[] br = out.br; float[] br = out.br;
for (int i = 0; i < br.length; i++) { for (int i = 0; i < br.length; i++) {
br[i] *= brightness; br[i] *= brightness;
} }
} }
//?} else if forgelike && <1.19 {
/*private void applySidedBrightnessFromNormals(QuadLightData out, ModelQuadView quad, boolean shade) {
int normal = quad.getModFaceNormal();
float brightness = shade ? LightUtil.diffuseLight(NormI8.unpackX(normal), NormI8.unpackY(normal), NormI8.unpackZ(normal)) : 1.0f;
float[] br = out.br;
for (int i = 0; i < br.length; i++) {
br[i] *= brightness;
}
}
*///?}
/** /**
* Returns the cached data for a given facing or calculates it if it hasn't been cached. * Returns the cached data for a given facing or calculates it if it hasn't been cached.
*/ */
private AoFaceData getCachedFaceData(BlockPos pos, Direction face, boolean offset) { private AoFaceData getCachedFaceData(int x, int y, int z, ModelQuadFacing face, boolean offset) {
AoFaceData data = this.cachedFaceData[offset ? face.ordinal() : face.ordinal() + 6]; AoFaceData data = this.cachedFaceData[offset ? face.ordinal() : face.ordinal() + 6];
if (!data.hasLightData()) { if (!data.hasLightData()) {
data.initLightData(this.lightCache, pos, face, offset); data.initLightData(this.lightCache, x, y, z, face, offset);
} }
return data; return data;
@@ -1,10 +1,10 @@
package org.embeddedt.embeddium.impl.model.quad; package org.embeddedt.embeddium.impl.model.quad;
import net.minecraft.client.renderer.block.model.BakedQuad;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.sprite.SpriteTransparencyLevel; import org.embeddedt.embeddium.impl.render.chunk.sprite.SpriteTransparencyLevel;
import org.jetbrains.annotations.Nullable;
import javax.annotation.Nullable; import java.util.List;
public interface BakedQuadView extends ModelQuadView { public interface BakedQuadView extends ModelQuadView {
ModelQuadFacing getNormalFace(); ModelQuadFacing getNormalFace();
@@ -17,7 +17,12 @@ public interface BakedQuadView extends ModelQuadView {
@Nullable SpriteTransparencyLevel getTransparencyLevel(); @Nullable SpriteTransparencyLevel getTransparencyLevel();
static BakedQuadView of(BakedQuad quad) { static BakedQuadView of(Object o) {
return (BakedQuadView)(Object)quad; return (BakedQuadView)o;
}
@SuppressWarnings("unchecked")
static <T> List<? extends BakedQuadView> ofList(List<T> quads) {
return (List<? extends BakedQuadView>)(List<?>)quads;
} }
} }
@@ -2,9 +2,8 @@ package org.embeddedt.embeddium.impl.model.quad;
import static org.embeddedt.embeddium.impl.util.ModelQuadUtil.*; import static org.embeddedt.embeddium.impl.util.ModelQuadUtil.*;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.util.ModelQuadUtil; import org.embeddedt.embeddium.impl.util.ModelQuadUtil;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.Direction;
/** /**
* A simple implementation of the {@link ModelQuadViewMutable} interface which can provide an on-heap scratch area * A simple implementation of the {@link ModelQuadViewMutable} interface which can provide an on-heap scratch area
@@ -14,25 +13,30 @@ public class ModelQuad implements ModelQuadViewMutable {
private final int[] data = new int[VERTEX_SIZE * 4]; private final int[] data = new int[VERTEX_SIZE * 4];
private int flags; private int flags;
private TextureAtlasSprite sprite; private int normal;
private Object sprite;
private int colorIdx; private int colorIdx;
private Direction direction; private ModelQuadFacing direction;
private boolean hasAmbientOcclusion = true; private boolean hasAmbientOcclusion = true;
@Override @Override
public void setX(int idx, float x) { public void setX(int idx, float x) {
this.data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x); this.data[vertexOffset(idx) + POSITION_INDEX] = Float.floatToRawIntBits(x);
this.normal = 0;
} }
@Override @Override
public void setY(int idx, float y) { public void setY(int idx, float y) {
this.data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y); this.data[vertexOffset(idx) + POSITION_INDEX + 1] = Float.floatToRawIntBits(y);
this.normal = 0;
} }
@Override @Override
public void setZ(int idx, float z) { public void setZ(int idx, float z) {
this.data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z); this.data[vertexOffset(idx) + POSITION_INDEX + 2] = Float.floatToRawIntBits(z);
this.normal = 0;
} }
@Override @Override
@@ -61,7 +65,7 @@ public class ModelQuad implements ModelQuadViewMutable {
} }
@Override @Override
public void setSprite(TextureAtlasSprite sprite) { public void setSprite(Object sprite) {
this.sprite = sprite; this.sprite = sprite;
} }
@@ -71,7 +75,10 @@ public class ModelQuad implements ModelQuadViewMutable {
} }
@Override @Override
public void setLightFace(Direction face) { public void setLightFace(ModelQuadFacing face) {
if (!face.isDirection()) {
throw new IllegalArgumentException();
}
this.direction = face; this.direction = face;
} }
@@ -125,9 +132,23 @@ public class ModelQuad implements ModelQuadViewMutable {
return this.data[vertexOffset(idx) + NORMAL_INDEX]; return this.data[vertexOffset(idx) + NORMAL_INDEX];
} }
@Override
public void setForgeNormal(int idx, int normal) {
this.data[vertexOffset(idx) + NORMAL_INDEX] = normal;
}
@Override @Override
public int getComputedFaceNormal() { public int getComputedFaceNormal() {
return ModelQuadUtil.calculateNormal(this); int n = this.normal;
if (n == 0) {
this.normal = n = ModelQuadUtil.calculateNormal(this);
}
return n;
}
@Override
public ModelQuadFacing getNormalFace() {
return ModelQuadUtil.findNormalFace(getComputedFaceNormal());
} }
@Override @Override
@@ -136,12 +157,12 @@ public class ModelQuad implements ModelQuadViewMutable {
} }
@Override @Override
public TextureAtlasSprite getSprite() { public Object celeritas$getSprite() {
return this.sprite; return this.sprite;
} }
@Override @Override
public Direction getLightFace() { public ModelQuadFacing getLightFace() {
return this.direction; return this.direction;
} }
@@ -1,8 +1,7 @@
package org.embeddedt.embeddium.impl.model.quad; package org.embeddedt.embeddium.impl.model.quad;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.Direction;
/** /**
* Provides a read-only view of a model quad. For mutable access to a model quad, see {@link ModelQuadViewMutable}. * Provides a read-only view of a model quad. For mutable access to a model quad, see {@link ModelQuadViewMutable}.
@@ -57,12 +56,17 @@ public interface ModelQuadView {
/** /**
* @return The sprite texture used by this quad, or null if none is attached * @return The sprite texture used by this quad, or null if none is attached
*/ */
TextureAtlasSprite getSprite(); Object celeritas$getSprite();
/** /**
* @return The face used by this quad for lighting effects * @return The face used by this quad for lighting effects
*/ */
Direction getLightFace(); ModelQuadFacing getLightFace();
/**
* @return The direction in which this quad is pointing, based on its geometry
*/
ModelQuadFacing getNormalFace();
int getForgeNormal(int idx); int getForgeNormal(int idx);
@@ -1,8 +1,7 @@
package org.embeddedt.embeddium.impl.model.quad; package org.embeddedt.embeddium.impl.model.quad;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.Direction;
/** /**
* Provides a mutable view to a model quad. * Provides a mutable view to a model quad.
@@ -51,7 +50,7 @@ public interface ModelQuadViewMutable extends ModelQuadView {
/** /**
* Sets the sprite used by this quad * Sets the sprite used by this quad
*/ */
void setSprite(TextureAtlasSprite sprite); void setSprite(Object sprite);
/** /**
* Sets the color index used by this quad * Sets the color index used by this quad
@@ -61,7 +60,12 @@ public interface ModelQuadViewMutable extends ModelQuadView {
/** /**
* Sets the face used by this quad for lighting effects * Sets the face used by this quad for lighting effects
*/ */
void setLightFace(Direction face); void setLightFace(ModelQuadFacing face);
void setHasAmbientOcclusion(boolean hasAmbientOcclusion); void setHasAmbientOcclusion(boolean hasAmbientOcclusion);
/**
* Sets the packed normal vector embedded in the vertex data.
*/
void setForgeNormal(int idx, int normal);
} }
@@ -16,6 +16,7 @@ public enum ModelQuadFacing {
public static final ModelQuadFacing[] VALUES = ModelQuadFacing.values(); public static final ModelQuadFacing[] VALUES = ModelQuadFacing.values();
public static final ModelQuadFacing[] DIRECTIONS = Arrays.stream(VALUES).filter(facing -> facing != UNASSIGNED).toArray(ModelQuadFacing[]::new); public static final ModelQuadFacing[] DIRECTIONS = Arrays.stream(VALUES).filter(facing -> facing != UNASSIGNED).toArray(ModelQuadFacing[]::new);
public static final Axis[] AXES = ModelQuadFacing.Axis.values();
public static final int COUNT = VALUES.length; public static final int COUNT = VALUES.length;
@@ -51,9 +52,21 @@ public enum ModelQuadFacing {
}; };
} }
public boolean isDirection() {
return this != UNASSIGNED;
}
public enum Axis { public enum Axis {
X, X,
Y, Y,
Z Z;
public ModelQuadFacing getFacing(boolean positive) {
return switch (this) {
case X -> positive ? POS_X : NEG_X;
case Y -> positive ? POS_Y : NEG_Y;
case Z -> positive ? POS_Z : NEG_Z;
};
}
}; };
} }
@@ -0,0 +1,207 @@
package org.embeddedt.embeddium.impl.model.quad.properties;
import org.embeddedt.embeddium.impl.common.util.MathUtil;
import org.embeddedt.embeddium.impl.model.quad.BakedQuadView;
import org.embeddedt.embeddium.impl.model.quad.ModelQuadView;
import org.embeddedt.embeddium.api.util.ColorABGR;
public class ModelQuadFlags {
/**
* Indicates that the quad does not fully cover the given face for the model.
*/
public static final int IS_PARTIAL = 0b001;
/**
* Indicates that the quad is parallel to its light face.
*/
public static final int IS_PARALLEL = 0b010;
/**
* Indicates that the quad is aligned to the block grid.
* This flag is only set if {@link #IS_PARALLEL} is set.
*/
public static final int IS_ALIGNED = 0b100;
/**
* Indicates that the quad should be shaded using vanilla's getShade logic and the light face, rather than
* the normals of each vertex.
*/
public static final int IS_VANILLA_SHADED = 0b1000;
/**
* Indicates that the particle sprite on this quad can be trusted to be the only sprite it shows.
*/
public static final int IS_TRUSTED_SPRITE = (1 << 4);
/**
* Indicates that this quad can use a more optimal terrain render pass based on its sprite.
*/
public static final int IS_PASS_OPTIMIZABLE = (1 << 5);
/**
* Indicates that the flags are populated for the quad.
*/
public static final int IS_POPULATED = (1 << 31);
/**
* @return True if the bit-flag of {@link ModelQuadFlags} contains the given flag
*/
public static boolean contains(int flags, int mask) {
return (flags & mask) != 0;
}
public static int getQuadFlags(ModelQuadView quad, ModelQuadFacing face) {
return getQuadFlags(quad, face, 0);
}
/**
* Checks whether a quad's vertex ordering matches Minecraft's canonical baked order
* for the given face.
* <p>
* Minecraft allows four different permutations of a quad's vertices that will
* render identically. However, the baked model pipeline (e.g. ambient occlusion,
* lighting interpolation, and back-face culling) assumes a specific ordering
* that is hardcoded in the model baking logic. This method verifies
* that a quad's vertices are listed in that exact canonical order.
* <p>
* The canonical order is:
* <ul>
* <li>Vertices are arranged counter-clockwise (CCW) as seen from outside the block face.</li>
* <li>Each face (±X, ±Y, ±Z) starts at a specific corner and proceeds CCW around the face.</li>
* <li>For example, the -Y face (DOWN) starts at {@code (minX, minY, maxZ)} and proceeds
* through {@code (minX, minY, minZ)}, {@code (maxX, minY, minZ)}, {@code (maxX, minY, maxZ)}.</li>
* </ul>
* <p>
* This method avoids allocations by comparing directly against the expected coordinates
* for each vertex index based on the given {@code face} and bounding box.
*
* @param face the face direction of the quad; determines which axis is fixed and
* which two axes form the quad plane
* @return {@code true} if the quad's vertices match Minecraft's canonical baked order
* for the given face, {@code false} otherwise
*/
private static boolean canonicalVertexOrder(ModelQuadView quad, ModelQuadFacing face, float minX, float minY, float minZ,
float maxX, float maxY, float maxZ) {
return switch (face) {
case NEG_Y -> MathUtil.roughlyEqual(quad.getX(0), minX) && MathUtil.roughlyEqual(quad.getY(0), minY) && MathUtil.roughlyEqual(quad.getZ(0), maxZ)
&& MathUtil.roughlyEqual(quad.getX(1), minX) && MathUtil.roughlyEqual(quad.getY(1), minY) && MathUtil.roughlyEqual(quad.getZ(1), minZ)
&& MathUtil.roughlyEqual(quad.getX(2), maxX) && MathUtil.roughlyEqual(quad.getY(2), minY) && MathUtil.roughlyEqual(quad.getZ(2), minZ)
&& MathUtil.roughlyEqual(quad.getX(3), maxX) && MathUtil.roughlyEqual(quad.getY(3), minY) && MathUtil.roughlyEqual(quad.getZ(3), maxZ);
case POS_Y -> MathUtil.roughlyEqual(quad.getX(0), minX) && MathUtil.roughlyEqual(quad.getY(0), maxY) && MathUtil.roughlyEqual(quad.getZ(0), minZ)
&& MathUtil.roughlyEqual(quad.getX(1), minX) && MathUtil.roughlyEqual(quad.getY(1), maxY) && MathUtil.roughlyEqual(quad.getZ(1), maxZ)
&& MathUtil.roughlyEqual(quad.getX(2), maxX) && MathUtil.roughlyEqual(quad.getY(2), maxY) && MathUtil.roughlyEqual(quad.getZ(2), maxZ)
&& MathUtil.roughlyEqual(quad.getX(3), maxX) && MathUtil.roughlyEqual(quad.getY(3), maxY) && MathUtil.roughlyEqual(quad.getZ(3), minZ);
case NEG_Z -> MathUtil.roughlyEqual(quad.getX(0), maxX) && MathUtil.roughlyEqual(quad.getY(0), maxY) && MathUtil.roughlyEqual(quad.getZ(0), minZ)
&& MathUtil.roughlyEqual(quad.getX(1), maxX) && MathUtil.roughlyEqual(quad.getY(1), minY) && MathUtil.roughlyEqual(quad.getZ(1), minZ)
&& MathUtil.roughlyEqual(quad.getX(2), minX) && MathUtil.roughlyEqual(quad.getY(2), minY) && MathUtil.roughlyEqual(quad.getZ(2), minZ)
&& MathUtil.roughlyEqual(quad.getX(3), minX) && MathUtil.roughlyEqual(quad.getY(3), maxY) && MathUtil.roughlyEqual(quad.getZ(3), minZ);
case POS_Z -> MathUtil.roughlyEqual(quad.getX(0), minX) && MathUtil.roughlyEqual(quad.getY(0), maxY) && MathUtil.roughlyEqual(quad.getZ(0), maxZ)
&& MathUtil.roughlyEqual(quad.getX(1), minX) && MathUtil.roughlyEqual(quad.getY(1), minY) && MathUtil.roughlyEqual(quad.getZ(1), maxZ)
&& MathUtil.roughlyEqual(quad.getX(2), maxX) && MathUtil.roughlyEqual(quad.getY(2), minY) && MathUtil.roughlyEqual(quad.getZ(2), maxZ)
&& MathUtil.roughlyEqual(quad.getX(3), maxX) && MathUtil.roughlyEqual(quad.getY(3), maxY) && MathUtil.roughlyEqual(quad.getZ(3), maxZ);
case NEG_X -> MathUtil.roughlyEqual(quad.getX(0), minX) && MathUtil.roughlyEqual(quad.getY(0), maxY) && MathUtil.roughlyEqual(quad.getZ(0), minZ)
&& MathUtil.roughlyEqual(quad.getX(1), minX) && MathUtil.roughlyEqual(quad.getY(1), minY) && MathUtil.roughlyEqual(quad.getZ(1), minZ)
&& MathUtil.roughlyEqual(quad.getX(2), minX) && MathUtil.roughlyEqual(quad.getY(2), minY) && MathUtil.roughlyEqual(quad.getZ(2), maxZ)
&& MathUtil.roughlyEqual(quad.getX(3), minX) && MathUtil.roughlyEqual(quad.getY(3), maxY) && MathUtil.roughlyEqual(quad.getZ(3), maxZ);
case POS_X -> MathUtil.roughlyEqual(quad.getX(0), maxX) && MathUtil.roughlyEqual(quad.getY(0), maxY) && MathUtil.roughlyEqual(quad.getZ(0), maxZ)
&& MathUtil.roughlyEqual(quad.getX(1), maxX) && MathUtil.roughlyEqual(quad.getY(1), minY) && MathUtil.roughlyEqual(quad.getZ(1), maxZ)
&& MathUtil.roughlyEqual(quad.getX(2), maxX) && MathUtil.roughlyEqual(quad.getY(2), minY) && MathUtil.roughlyEqual(quad.getZ(2), minZ)
&& MathUtil.roughlyEqual(quad.getX(3), maxX) && MathUtil.roughlyEqual(quad.getY(3), maxY) && MathUtil.roughlyEqual(quad.getZ(3), minZ);
case UNASSIGNED -> false;
};
}
/**
* Calculates the properties of the given quad. This data is used later by the light pipeline in order to make
* certain optimizations.
*/
public static int getQuadFlags(ModelQuadView quad, ModelQuadFacing face, int existingFlags) {
float minX = 32.0F;
float minY = 32.0F;
float minZ = 32.0F;
float maxX = -32.0F;
float maxY = -32.0F;
float maxZ = -32.0F;
int numVertices = 4;
if (quad instanceof BakedQuadView bakedQuad) {
numVertices = Math.min(numVertices, bakedQuad.getVerticesCount());
}
boolean degenerate = false, nonOpaqueColor = false;
for (int i = 0; i < numVertices; ++i) {
float x = quad.getX(i);
float y = quad.getY(i);
float z = quad.getZ(i);
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
for (int j = 0; j < i; ++j) {
float px = quad.getX(j);
float py = quad.getY(j);
float pz = quad.getZ(j);
if (MathUtil.roughlyEqual(px, x) &&
MathUtil.roughlyEqual(py, y) &&
MathUtil.roughlyEqual(pz, z)) {
degenerate = true;
break;
}
}
if(ColorABGR.unpackAlpha(quad.getColor(i)) != 255) {
nonOpaqueColor = true;
}
}
// Do not set the partial flag if the vertices are not listed in the expected order. The optimization assumes
// it can map directly onto corners in specific locations.
boolean partial = degenerate || (switch (face.getAxis()) {
case X -> minY >= 0.0001f || minZ >= 0.0001f || maxY <= 0.9999F || maxZ <= 0.9999F;
case Y -> minX >= 0.0001f || minZ >= 0.0001f || maxX <= 0.9999F || maxZ <= 0.9999F;
case Z -> minX >= 0.0001f || minY >= 0.0001f || maxX <= 0.9999F || maxY <= 0.9999F;
}) || !canonicalVertexOrder(quad, face, minX, minY, minZ, maxX, maxY, maxZ);
boolean parallel = switch(face.getAxis()) {
case X -> minX == maxX;
case Y -> minY == maxY;
case Z -> minZ == maxZ;
};
boolean aligned = parallel && switch (face) {
case NEG_Y -> minY < 0.0001f;
case POS_Y -> maxY > 0.9999F;
case NEG_Z -> minZ < 0.0001f;
case POS_Z -> maxZ > 0.9999F;
case NEG_X -> minX < 0.0001f;
case POS_X -> maxX > 0.9999F;
case UNASSIGNED -> throw new IllegalArgumentException();
};
int flags = existingFlags & ~(IS_PARTIAL | IS_PARALLEL | IS_ALIGNED);
if (partial) {
flags |= IS_PARTIAL;
}
if (parallel) {
flags |= IS_PARALLEL;
}
if (aligned) {
flags |= IS_ALIGNED;
}
if (!nonOpaqueColor && (flags & IS_TRUSTED_SPRITE) != 0) {
flags |= IS_PASS_OPTIMIZABLE;
}
flags |= IS_POPULATED;
return flags;
}
}
@@ -7,8 +7,6 @@ import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeBinding;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.tessellation.*; import org.embeddedt.embeddium.impl.gl.tessellation.*;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing; import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
@@ -17,17 +15,17 @@ import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe; import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable; import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable;
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList; import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.util.BitwiseMath; import org.embeddedt.embeddium.impl.util.BitwiseMath;
import org.lwjgl.system.MemoryUtil;
import java.util.Iterator; import java.util.Iterator;
public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
private final MultiDrawBatch batch; private final MultiDrawEmitter emitter;
private final Reference2ReferenceMap<ChunkPrimitiveType, SharedQuadIndexBuffer> sharedIndexBuffers; private final Reference2ReferenceMap<ChunkPrimitiveType, SharedQuadIndexBuffer> sharedIndexBuffers;
@@ -35,9 +33,13 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
private GlVertexFormat currentVertexFormat; private GlVertexFormat currentVertexFormat;
public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
this(device, renderPassConfiguration, new DirectMultiDrawEmitter());
}
public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration, MultiDrawEmitter emitter) {
super(device, renderPassConfiguration); super(device, renderPassConfiguration);
this.batch = new MultiDrawBatch((ModelQuadFacing.COUNT * RenderRegion.REGION_SIZE) + 1); this.emitter = emitter;
this.sharedIndexBuffers = new Reference2ReferenceOpenHashMap<>(); this.sharedIndexBuffers = new Reference2ReferenceOpenHashMap<>();
} }
@@ -88,6 +90,8 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
this.configureShaderInterface(shader); this.configureShaderInterface(shader);
long timestamp = System.nanoTime();
while (iterator.hasNext()) { while (iterator.hasNext()) {
ChunkRenderList renderList = iterator.next(); ChunkRenderList renderList = iterator.next();
@@ -98,20 +102,21 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
continue; continue;
} }
fillCommandBuffer(this.batch, region, storage, renderList, occlusionCamera, renderPass, useBlockFaceCulling && !renderPass.isSorted()); fillCommandBuffer(this.emitter, region, storage, renderList, occlusionCamera, renderPass, useBlockFaceCulling && !renderPass.isSorted());
if (this.batch.isEmpty()) { if (this.emitter.isEmpty()) {
continue; continue;
} }
if (!renderPass.isSorted()) { if (!renderPass.isSorted()) {
getSharedIndexBuffer(renderPassConfiguration.getPrimitiveTypeForPass(renderPass), commandList).ensureCapacity(commandList, this.batch.getIndexBufferSize()); getSharedIndexBuffer(renderPassConfiguration.getPrimitiveTypeForPass(renderPass), commandList).ensureCapacity(commandList, this.emitter.getIndexBufferSize());
} }
var tessellation = this.prepareTessellation(commandList, region); var tessellation = this.prepareTessellation(commandList, region);
setModelMatrixUniforms(shader, region, camera); setModelMatrixUniforms(shader, region, camera);
executeDrawBatch(commandList, tessellation, primitiveType, this.batch); shader.setSectionAges(timestamp, region.getSectionLoadTimes());
this.emitter.executeBatch(commandList, tessellation, primitiveType);
} }
this.currentVertexFormat = null; this.currentVertexFormat = null;
@@ -123,14 +128,14 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
this.end(renderPass); this.end(renderPass);
} }
private static void fillCommandBuffer(MultiDrawBatch batch, private static void fillCommandBuffer(MultiDrawEmitter emitter,
RenderRegion renderRegion, RenderRegion renderRegion,
SectionRenderDataStorage renderDataStorage, SectionRenderDataStorage renderDataStorage,
ChunkRenderList renderList, ChunkRenderList renderList,
CameraTransform camera, CameraTransform camera,
TerrainRenderPass pass, TerrainRenderPass pass,
boolean useBlockFaceCulling) { boolean useBlockFaceCulling) {
batch.clear(); emitter.clear();
var iterator = renderList.sectionsWithGeometryIterator(pass.isReverseOrder()); var iterator = renderList.sectionsWithGeometryIterator(pass.isReverseOrder());
@@ -164,30 +169,11 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData); slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData);
if (slices != 0) { if (slices != 0) {
addDrawCommands(batch, pMeshData, slices, indexPointerMask); emitter.addDrawCommands(pMeshData, slices, indexPointerMask);
} }
} }
} }
@SuppressWarnings("IntegerMultiplicationImplicitCastToLong")
private static void addDrawCommands(MultiDrawBatch batch, long pMeshData, int mask, int indexPointerMask) {
final var pBaseVertex = batch.pBaseVertex;
final var pElementCount = batch.pElementCount;
final var pElementPointer = batch.pElementPointer;
int size = batch.size;
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
MemoryUtil.memPutInt(pBaseVertex + (size << 2), SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing));
MemoryUtil.memPutInt(pElementCount + (size << 2), SectionRenderDataUnsafe.getElementCount(pMeshData, facing));
MemoryUtil.memPutAddress(pElementPointer + (size << 3), SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask);
size += (mask >> facing) & 1;
}
batch.size = size;
}
private static final int MODEL_UNASSIGNED = ModelQuadFacing.UNASSIGNED.ordinal(); private static final int MODEL_UNASSIGNED = ModelQuadFacing.UNASSIGNED.ordinal();
private static final int MODEL_POS_X = ModelQuadFacing.POS_X.ordinal(); private static final int MODEL_POS_X = ModelQuadFacing.POS_X.ordinal();
private static final int MODEL_POS_Y = ModelQuadFacing.POS_Y.ordinal(); private static final int MODEL_POS_Y = ModelQuadFacing.POS_Y.ordinal();
@@ -310,17 +296,11 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
return tessellation; return tessellation;
} }
private static void executeDrawBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, MultiDrawBatch batch) {
try (DrawCommandList drawCommandList = commandList.beginTessellating(tessellation)) {
drawCommandList.multiDrawElementsBaseVertex(batch, primitiveType, GlIndexType.UNSIGNED_INT);
}
}
@Override @Override
public void delete(CommandList commandList) { public void delete(CommandList commandList) {
super.delete(commandList); super.delete(commandList);
this.sharedIndexBuffers.values().forEach(buffer -> buffer.delete(commandList)); this.sharedIndexBuffers.values().forEach(buffer -> buffer.delete(commandList));
this.batch.delete(); this.emitter.delete();
} }
} }
@@ -68,6 +68,10 @@ public class RenderSection extends AbstractSection {
// Lifetime state // Lifetime state
private boolean disposed; private boolean disposed;
@Getter
@Setter
private long lastBuildDurationNanos;
// Used by the translucency sorter, to determine when a section needs sorting again // Used by the translucency sorter, to determine when a section needs sorting again
public double lastCameraX, lastCameraY, lastCameraZ; public double lastCameraX, lastCameraY, lastCameraZ;
@@ -98,6 +102,9 @@ public class RenderSection extends AbstractSection {
public boolean setInfo(@Nullable BuiltRenderSectionData info) { public boolean setInfo(@Nullable BuiltRenderSectionData info) {
boolean changed = !Objects.equals(info, this.contextData); boolean changed = !Objects.equals(info, this.contextData);
if (changed) { if (changed) {
if (this.contextData == null) {
this.getRegion().updateSectionLoadTime(this);
}
this.contextData = info; this.contextData = info;
this.updateCachedContextDataFlags(); this.updateCachedContextDataFlags();
} }
@@ -163,6 +170,23 @@ public class RenderSection extends AbstractSection {
this.pendingUpdateType = type; this.pendingUpdateType = type;
} }
/**
* Request a type of chunk update for this render section. This may "upgrade" an existing pending update for the
* section.
* @param type the chunk update
* @return true if the section's chunk update type has changed
*/
public boolean requestUpdate(ChunkUpdateType type) {
type = ChunkUpdateType.getPromotionUpdateType(this.pendingUpdateType, type);
if (type != null) {
this.pendingUpdateType = type;
return true;
} else {
return false;
}
}
public int getLastBuiltFrame() { public int getLastBuiltFrame() {
return this.lastBuiltFrame; return this.lastBuiltFrame;
} }
@@ -10,7 +10,9 @@ import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.profiling.TimerQueryManager; import org.embeddedt.embeddium.impl.gl.profiling.TimerQueryManager;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkTaskOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkBuilder; import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkBuilder;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobMetricsTracker;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobResult; import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobResult;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobCollector; import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobCollector;
import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderSortTask; import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderSortTask;
@@ -22,6 +24,7 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.lists.RenderListManager; import org.embeddedt.embeddium.impl.render.chunk.lists.RenderListManager;
import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker; import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker;
import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists; import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists;
import org.embeddedt.embeddium.impl.render.chunk.metrics.RenderSectionMetricsTracker;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode; import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding; import org.embeddedt.embeddium.impl.render.chunk.occlusion.VisibilityEncoding;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
@@ -49,6 +52,12 @@ import java.util.function.BooleanSupplier;
import java.util.function.Supplier; import java.util.function.Supplier;
public abstract class RenderSectionManager { public abstract class RenderSectionManager {
/**
* When true, the section manager will continuously mark all sections as needing to be remeshed whenever the
* update queue empties.
*/
protected static final boolean CONTINUOUSLY_REMESH_WORLD = false;
private final ChunkBuilder builder; private final ChunkBuilder builder;
private final Thread renderThread = Thread.currentThread(); private final Thread renderThread = Thread.currentThread();
@@ -57,7 +66,7 @@ public abstract class RenderSectionManager {
private final Long2ReferenceMap<RenderSection> sectionByPosition = new Long2ReferenceOpenHashMap<>(); private final Long2ReferenceMap<RenderSection> sectionByPosition = new Long2ReferenceOpenHashMap<>();
private final ConcurrentLinkedDeque<ChunkJobResult<ChunkBuildOutput>> buildResults = new ConcurrentLinkedDeque<>(); private final ConcurrentLinkedDeque<ChunkJobResult<? extends ChunkTaskOutput>> buildResults = new ConcurrentLinkedDeque<>();
private final ConcurrentLinkedDeque<Runnable> asyncSubmittedTasks = new ConcurrentLinkedDeque<>(); private final ConcurrentLinkedDeque<Runnable> asyncSubmittedTasks = new ConcurrentLinkedDeque<>();
private final ChunkRenderer chunkRenderer; private final ChunkRenderer chunkRenderer;
@@ -85,6 +94,12 @@ public abstract class RenderSectionManager {
protected final ReferenceSet<RenderSection> sectionsRequestingUpdate = new ReferenceOpenHashSet<>(); protected final ReferenceSet<RenderSection> sectionsRequestingUpdate = new ReferenceOpenHashSet<>();
@Getter
protected final ChunkJobMetricsTracker jobMetricsTracker = new ChunkJobMetricsTracker();
@Getter
protected final RenderSectionMetricsTracker sectionMetricsTracker = new RenderSectionMetricsTracker();
@Deprecated @Deprecated
public RenderSectionManager(RenderPassConfiguration<?> configuration, Supplier<ChunkBuildContext> contextSupplier, public RenderSectionManager(RenderPassConfiguration<?> configuration, Supplier<ChunkBuildContext> contextSupplier,
BiFunction<RenderDevice, RenderPassConfiguration<?>, ChunkRenderer> chunkRenderer, BiFunction<RenderDevice, RenderPassConfiguration<?>, ChunkRenderer> chunkRenderer,
@@ -246,13 +261,20 @@ public abstract class RenderSectionManager {
} }
} }
protected abstract boolean shouldRespectUpdateTaskQueueSizeLimit(); /**
* {@return true if the renderer should respect per-frame queue limits and not try to update as many chunks as
* possible per frame}
*/
protected boolean shouldRespectUpdateTaskQueueSizeLimit() {
return true;
}
private void createTerrainRenderList(Viewport viewport, int frame, boolean spectator) { private void createTerrainRenderList(Viewport viewport, int frame, boolean spectator) {
final var searchDistance = this.getSearchDistance(); final var searchDistance = this.getSearchDistance();
final var useOcclusionCulling = this.shouldUseOcclusionCulling(viewport, spectator); final var useOcclusionCulling = this.shouldUseOcclusionCulling(viewport, spectator);
this.getCurrentRenderListManager().startGraphUpdate(viewport, frame, searchDistance, useOcclusionCulling, !this.shouldRespectUpdateTaskQueueSizeLimit()); this.getCurrentRenderListManager().startGraphUpdate(viewport, frame, this.regions.getRegionIdsLength(),
searchDistance, useOcclusionCulling, !this.shouldRespectUpdateTaskQueueSizeLimit());
} }
protected abstract boolean useFogOcclusion(); protected abstract boolean useFogOcclusion();
@@ -296,6 +318,8 @@ public abstract class RenderSectionManager {
this.shadowRenderListManager.attachRenderSection(renderSection); this.shadowRenderListManager.attachRenderSection(renderSection);
} }
this.invalidateCachedSectionData(renderSection);
if (this.isSectionVisuallyEmpty(x, y, z)) { if (this.isSectionVisuallyEmpty(x, y, z)) {
this.updateSectionInfo(renderSection, RenderSection.EMPTY_DATA); this.updateSectionInfo(renderSection, RenderSection.EMPTY_DATA);
} else { } else {
@@ -319,6 +343,8 @@ public abstract class RenderSectionManager {
region.removeSection(section); region.removeSection(section);
} }
this.invalidateCachedSectionData(section);
this.updateSectionInfo(section, null); this.updateSectionInfo(section, null);
this.renderListManager.detachRenderSection(section); this.renderListManager.detachRenderSection(section);
@@ -326,6 +352,8 @@ public abstract class RenderSectionManager {
this.shadowRenderListManager.detachRenderSection(section); this.shadowRenderListManager.detachRenderSection(section);
} }
this.sectionMetricsTracker.removeSection(section);
section.delete(); section.delete();
this.markGraphDirty(); this.markGraphDirty();
@@ -382,6 +410,7 @@ public abstract class RenderSectionManager {
public void updateChunks(boolean updateImmediately) { public void updateChunks(boolean updateImmediately) {
this.regions.update(); this.regions.update();
this.jobMetricsTracker.tick();
// Promotion of the interim rebuild list is not required if a graph update is requested, as the graph // Promotion of the interim rebuild list is not required if a graph update is requested, as the graph
// generates a new rebuild list anyway // generates a new rebuild list anyway
@@ -392,6 +421,9 @@ public abstract class RenderSectionManager {
this.sectionsRequestingUpdate.clear(); this.sectionsRequestingUpdate.clear();
if (!rebuildListHasUpdates()) { if (!rebuildListHasUpdates()) {
if (CONTINUOUSLY_REMESH_WORLD && !this.getCurrentRenderListManager().getRebuildLists().hasAdditionalUpdates()) {
this.scheduleRebuildAll();
}
return; return;
} }
@@ -426,7 +458,7 @@ public abstract class RenderSectionManager {
this.processChunkBuildResults(results); this.processChunkBuildResults(results);
for (var result : results) { for (var result : results) {
result.delete(); result.output().delete();
} }
// Forcefully mark the graph as needing updates if the previous render list detected an overflow of the // Forcefully mark the graph as needing updates if the previous render list detected an overflow of the
@@ -440,14 +472,15 @@ public abstract class RenderSectionManager {
this.getCurrentRenderListManager().tickVisibleRenders(); this.getCurrentRenderListManager().tickVisibleRenders();
} }
private void processChunkBuildResults(ArrayList<ChunkBuildOutput> results) { private void processChunkBuildResults(ArrayList<ChunkJobResult.Success<? extends ChunkTaskOutput>> results) {
var filtered = filterChunkBuildResults(results); var filtered = filterChunkBuildResults(results);
this.regions.uploadMeshes(RenderDevice.INSTANCE.createCommandList(), filtered); this.regions.uploadMeshes(RenderDevice.INSTANCE.createCommandList(), filtered, this::markGraphDirty);
for (var result : filtered) { for (var holder : filtered) {
if(result.info != null) { var result = holder.output();
boolean changed = this.updateSectionInfo(result.render, result.info); if (result instanceof ChunkBuildOutput buildResult) {
boolean changed = this.updateSectionInfo(result.render, buildResult.info);
if (changed) { if (changed) {
// The chunk graph must be rebuilt if the render section reports the info has changed. This // The chunk graph must be rebuilt if the render section reports the info has changed. This
@@ -457,7 +490,7 @@ public abstract class RenderSectionManager {
} }
// We only change the translucency info on full rebuilds, as sorts can keep using the same data // We only change the translucency info on full rebuilds, as sorts can keep using the same data
this.updateTranslucencyInfo(result.render, result.meshes); this.updateTranslucencyInfo(result.render, buildResult.meshes);
} }
var job = result.render.getBuildCancellationToken(); var job = result.render.getBuildCancellationToken();
@@ -467,6 +500,7 @@ public abstract class RenderSectionManager {
} }
result.render.setLastBuiltFrame(result.buildTime); result.render.setLastBuiltFrame(result.buildTime);
this.sectionMetricsTracker.updateSectionBuildDuration(result.render, holder.executionTimeNanos());
} }
} }
@@ -474,7 +508,7 @@ public abstract class RenderSectionManager {
Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> sortStates = new Reference2ObjectArrayMap<>(); Map<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> sortStates = new Reference2ObjectArrayMap<>();
for(var entry : meshes.entrySet()) { for(var entry : meshes.entrySet()) {
if(entry.getKey().isSorted()) { if(entry.getKey().isSorted()) {
sortStates.put(entry.getKey(), entry.getValue().getSortState().compactForStorage()); sortStates.put(entry.getKey(), Objects.requireNonNull(entry.getValue().sortState()).compactForStorage());
} }
} }
render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates); render.setTranslucencySortStates(sortStates.isEmpty() ? Collections.emptyMap() : sortStates);
@@ -501,31 +535,39 @@ public abstract class RenderSectionManager {
return changed; return changed;
} }
private static List<ChunkBuildOutput> filterChunkBuildResults(ArrayList<ChunkBuildOutput> outputs) { private static List<ChunkJobResult.Success<? extends ChunkTaskOutput>> filterChunkBuildResults(ArrayList<ChunkJobResult.Success<? extends ChunkTaskOutput>> outputs) {
var map = new Reference2ReferenceLinkedOpenHashMap<RenderSection, ChunkBuildOutput>(); var map = new Reference2ReferenceLinkedOpenHashMap<RenderSection, ChunkJobResult.Success<? extends ChunkTaskOutput>>();
for (var output : outputs) { for (var holder : outputs) {
var output = holder.output();
if (output.render.isDisposed() || output.render.getLastBuiltFrame() > output.buildTime) { if (output.render.isDisposed() || output.render.getLastBuiltFrame() > output.buildTime) {
continue; continue;
} }
var render = output.render; var render = output.render;
var previous = map.get(render); var previousHolder = map.get(render);
if (previous == null || previous.buildTime < output.buildTime) { if (previousHolder == null || previousHolder.output().buildTime < output.buildTime) {
map.put(render, output); map.put(render, holder);
} }
} }
return new ArrayList<>(map.values()); return new ArrayList<>(map.values());
} }
private ArrayList<ChunkBuildOutput> collectChunkBuildResults() { private ArrayList<ChunkJobResult.Success<? extends ChunkTaskOutput>> collectChunkBuildResults() {
ArrayList<ChunkBuildOutput> results = new ArrayList<>(); ArrayList<ChunkJobResult.Success<? extends ChunkTaskOutput>> results = new ArrayList<>();
ChunkJobResult<ChunkBuildOutput> result; ChunkJobResult<? extends ChunkTaskOutput> result;
while ((result = this.buildResults.poll()) != null) { while ((result = this.buildResults.poll()) != null) {
results.add(result.unwrap()); if (result instanceof ChunkJobResult.Success<? extends ChunkTaskOutput> successfulResult) {
this.jobMetricsTracker.collectMetrics(successfulResult);
results.add(successfulResult);
} else if (result instanceof ChunkJobResult.Failure<? extends ChunkTaskOutput> failure) {
failure.abort();
} else {
throw new AssertionError();
}
} }
return results; return results;
@@ -549,7 +591,7 @@ public abstract class RenderSectionManager {
continue; continue;
} }
ChunkBuilderTask<ChunkBuildOutput> task = type.isSort() ? this.createSortTask(section, frame) : this.createRebuildTask(section, frame); ChunkBuilderTask<? extends ChunkTaskOutput> task = type.isSort() ? this.createSortTask(section, frame) : this.createRebuildTask(section, frame);
if (task == null && type.isSort()) { if (task == null && type.isSort()) {
// Ignore sorts that became invalid // Ignore sorts that became invalid
@@ -568,7 +610,7 @@ public abstract class RenderSectionManager {
section.setNeedsDynamicTranslucencySorting(false); section.setNeedsDynamicTranslucencySorting(false);
} }
} else { } else {
var result = ChunkJobResult.successfully(new ChunkBuildOutput(section, RenderSection.EMPTY_DATA, Reference2ReferenceMaps.emptyMap(), frame)); var result = new ChunkJobResult.Success<>(new ChunkBuildOutput(section, RenderSection.EMPTY_DATA, Reference2ReferenceMaps.emptyMap(), frame), -1);
this.buildResults.add(result); this.buildResults.add(result);
section.setBuildCancellationToken(null); section.setBuildCancellationToken(null);
@@ -615,7 +657,7 @@ public abstract class RenderSectionManager {
this.builder.shutdown(); // stop all the workers, and cancel any tasks this.builder.shutdown(); // stop all the workers, and cancel any tasks
for (var result : this.collectChunkBuildResults()) { for (var result : this.collectChunkBuildResults()) {
result.delete(); // delete resources for any pending tasks (including those that were cancelled) result.output().delete(); // delete resources for any pending tasks (including those that were cancelled)
} }
this.renderListManager.destroy(); this.renderListManager.destroy();
@@ -650,9 +692,14 @@ public abstract class RenderSectionManager {
return sections; return sections;
} }
public void scheduleAsyncTask(Runnable runnable) { public final void scheduleAsyncTask(Runnable runnable) {
if (Thread.currentThread() == this.renderThread) {
// Run immediately, otherwise the thread may deadlock waiting for itself
runnable.run();
} else {
asyncSubmittedTasks.add(runnable); asyncSubmittedTasks.add(runnable);
} }
}
private void scheduleRebuildOffThread(int x, int y, int z, boolean important) { private void scheduleRebuildOffThread(int x, int y, int z, boolean important) {
scheduleAsyncTask(() -> this.scheduleSectionForRebuild(x, y, z, important)); scheduleAsyncTask(() -> this.scheduleSectionForRebuild(x, y, z, important));
@@ -667,10 +714,16 @@ public abstract class RenderSectionManager {
this.scheduleSectionForRebuild(x, y, z, important); this.scheduleSectionForRebuild(x, y, z, important);
} }
protected void invalidateCachedSectionData(RenderSection section) {
}
protected void scheduleSectionForRebuild(int x, int y, int z, boolean important) { protected void scheduleSectionForRebuild(int x, int y, int z, boolean important) {
RenderSection section = this.sectionByPosition.get(PositionUtil.packSection(x, y, z)); RenderSection section = this.sectionByPosition.get(PositionUtil.packSection(x, y, z));
if (section != null) { if (section != null) {
this.invalidateCachedSectionData(section);
ChunkUpdateType pendingUpdate; ChunkUpdateType pendingUpdate;
if (allowImportantRebuilds() && (important || this.shouldPrioritizeRebuild(section))) { if (allowImportantRebuilds() && (important || this.shouldPrioritizeRebuild(section))) {
@@ -679,10 +732,7 @@ public abstract class RenderSectionManager {
pendingUpdate = ChunkUpdateType.REBUILD; pendingUpdate = ChunkUpdateType.REBUILD;
} }
pendingUpdate = ChunkUpdateType.getPromotionUpdateType(section.getPendingUpdate(), pendingUpdate); if (section.requestUpdate(pendingUpdate)) {
if (pendingUpdate != null) {
section.setPendingUpdate(pendingUpdate);
if (!this.getCurrentRenderListManager().isNeedsUpdate() && this.sectionsRequestingUpdate.size() < this.builder.getSchedulingBudget()) { if (!this.getCurrentRenderListManager().isNeedsUpdate() && this.sectionsRequestingUpdate.size() < this.builder.getSchedulingBudget()) {
this.sectionsRequestingUpdate.add(section); this.sectionsRequestingUpdate.add(section);
} else { } else {
@@ -692,13 +742,29 @@ public abstract class RenderSectionManager {
} }
} }
public void scheduleRebuildAll() {
for (var section : this.sectionByPosition.values()) {
if (!this.isSectionVisuallyEmpty(section.getChunkX(), section.getChunkY(), section.getChunkZ())) {
this.invalidateCachedSectionData(section);
section.requestUpdate(ChunkUpdateType.REBUILD);
}
}
this.markGraphDirty();
}
private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f); private static final float NEARBY_REBUILD_DISTANCE = MathUtil.square(16.0f);
private boolean shouldPrioritizeRebuild(RenderSection section) { private boolean shouldPrioritizeRebuild(RenderSection section) {
return this.lastCameraPosition != null && section.getSquaredDistanceFromBlockCenter(this.lastCameraPosition.x(), this.lastCameraPosition.y(), this.lastCameraPosition.z()) < NEARBY_REBUILD_DISTANCE; return this.lastCameraPosition != null && section.getSquaredDistanceFromBlockCenter(this.lastCameraPosition.x(), this.lastCameraPosition.y(), this.lastCameraPosition.z()) < NEARBY_REBUILD_DISTANCE;
} }
protected abstract boolean allowImportantRebuilds(); /**
* {@return true if rebuilds of chunks near the player should block the main thread, reduces flickering but will
* potentially cause lag spikes}
*/
protected boolean allowImportantRebuilds() {
return false;
}
private float getEffectiveRenderDistance() { private float getEffectiveRenderDistance() {
var color = ChunkShaderFogComponent.FOG_SERVICE.getFogColor(); var color = ChunkShaderFogComponent.FOG_SERVICE.getFogColor();
@@ -880,4 +946,8 @@ public abstract class RenderSectionManager {
public final Collection<RenderSection> getSectionsWithGlobalEntities() { public final Collection<RenderSection> getSectionsWithGlobalEntities() {
return ReferenceSets.unmodifiable(this.sectionsWithGlobalEntities); return ReferenceSets.unmodifiable(this.sectionsWithGlobalEntities);
} }
public String getTickerDebugString() {
return this.getCurrentRenderListManager().getTickerDebugString();
}
} }
@@ -17,6 +17,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Pattern;
public abstract class ShaderChunkRenderer implements ChunkRenderer { public abstract class ShaderChunkRenderer implements ChunkRenderer {
private static final Logger LOGGER = LogManager.getLogger(ShaderChunkRenderer.class); private static final Logger LOGGER = LogManager.getLogger(ShaderChunkRenderer.class);
@@ -29,9 +30,15 @@ public abstract class ShaderChunkRenderer implements ChunkRenderer {
protected GlProgram<ChunkShaderInterface> activeProgram; protected GlProgram<ChunkShaderInterface> activeProgram;
protected final boolean enableLegacyGLPatches;
public ShaderChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public ShaderChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
this.device = device; this.device = device;
this.renderPassConfiguration = renderPassConfiguration; this.renderPassConfiguration = renderPassConfiguration;
this.enableLegacyGLPatches = !device.getCapabilities().OpenGL32;
if (this.enableLegacyGLPatches) {
LOGGER.warn("System does not support modern GLSL, will attempt to patch terrain shaders");
}
} }
protected @Nullable GlProgram<ChunkShaderInterface> compileProgram(ChunkShaderOptions options) { protected @Nullable GlProgram<ChunkShaderInterface> compileProgram(ChunkShaderOptions options) {
@@ -49,15 +56,44 @@ public abstract class ShaderChunkRenderer implements ChunkRenderer {
return program; return program;
} }
private static final Pattern VERSION_DIRECTIVE = Pattern.compile("^#version.*$", Pattern.MULTILINE);
private static final Pattern IN_PARAM = Pattern.compile("^in ", Pattern.MULTILINE);
private static final Pattern OUT_PARAM = Pattern.compile("^out ", Pattern.MULTILINE);
private static final String LEGACY_PREAMBLE = String.join("\n",
"#version 120",
"#extension GL_EXT_gpu_shader4 : require",
"#define LEGACY",
"#define uint unsigned int",
"#define texture texture2D"
) + "\n";
private GlShader loadShader(ShaderType type, String path, ShaderConstants constants) {
String shaderSource = ShaderParser.parseShader(ShaderLoader.getShaderSource(path), ShaderLoader::getShaderSource, constants);
if (this.enableLegacyGLPatches) {
if (type != ShaderType.VERTEX && type != ShaderType.FRAGMENT) {
throw new IllegalStateException("Cannot load non-vertex/fragment shader on old GL");
}
// Downlevel to GLSL 1.20
shaderSource = VERSION_DIRECTIVE.matcher(shaderSource).replaceFirst(LEGACY_PREAMBLE);
if (type == ShaderType.VERTEX) {
shaderSource = IN_PARAM.matcher(shaderSource).replaceAll("attribute ");
} else {
shaderSource = IN_PARAM.matcher(shaderSource).replaceAll("varying ");
}
shaderSource = OUT_PARAM.matcher(shaderSource).replaceAll("varying ");
}
return new GlShader(type, path, shaderSource);
}
protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) { protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) {
ShaderConstants constants = options.constants(); ShaderConstants constants = options.constants();
List<GlShader> loadedShaders = new ArrayList<>(); List<GlShader> loadedShaders = new ArrayList<>();
loadedShaders.add(ShaderLoader.loadShader(ShaderType.VERTEX, loadedShaders.add(loadShader(ShaderType.VERTEX,
"sodium:" + path + ".vsh", constants)); "sodium:" + path + ".vsh", constants));
loadedShaders.add(ShaderLoader.loadShader(ShaderType.FRAGMENT, loadedShaders.add(loadShader(ShaderType.FRAGMENT,
"sodium:" + path + ".fsh", constants)); "sodium:" + path + ".fsh", constants));
try { try {
@@ -67,7 +103,9 @@ public abstract class ShaderChunkRenderer implements ChunkRenderer {
for (var attr : options.pass().vertexType().getVertexFormat().getAttributes()) { for (var attr : options.pass().vertexType().getVertexFormat().getAttributes()) {
builder.bindAttribute(attr.getName(), i++); builder.bindAttribute(attr.getName(), i++);
} }
if (!this.enableLegacyGLPatches) {
builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR); builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR);
}
return builder.link((shader) -> new DefaultChunkShaderInterface(shader, options)); return builder.link((shader) -> new DefaultChunkShaderInterface(shader, options));
} finally { } finally {
loadedShaders.forEach(GlShader::delete); loadedShaders.forEach(GlShader::delete);
@@ -17,10 +17,7 @@ import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/** /**
* A collection of temporary buffers for each worker thread which will be used to build chunk meshes for given render * A collection of temporary buffers for each worker thread which will be used to build chunk meshes for given render
@@ -88,7 +85,7 @@ public final class ChunkBuildBuffers {
} }
List<ByteBuffer> vertexBuffers = new ArrayList<>(); List<ByteBuffer> vertexBuffers = new ArrayList<>();
VertexRange[] vertexRanges = new VertexRange[ModelQuadFacing.COUNT]; var vertexRanges = new EnumMap<ModelQuadFacing, VertexRange>(ModelQuadFacing.class);
int vertexCount = 0; int vertexCount = 0;
@@ -103,7 +100,7 @@ public final class ChunkBuildBuffers {
} }
vertexBuffers.add(buffer.slice()); vertexBuffers.add(buffer.slice());
vertexRanges[facing.ordinal()] = new VertexRange(vertexCount, buffer.count()); vertexRanges.put(facing, new VertexRange(vertexCount, buffer.count()));
vertexCount += buffer.count(); vertexCount += buffer.count();
} }
@@ -12,48 +12,24 @@ import org.jetbrains.annotations.Nullable;
* the main thread. If a task is cancelled after finishing its work and not before the result is processed, the result * the main thread. If a task is cancelled after finishing its work and not before the result is processed, the result
* will instead be discarded. * will instead be discarded.
*/ */
public class ChunkBuildOutput { public class ChunkBuildOutput extends ChunkTaskOutput {
public final RenderSection render; public final BuiltRenderSectionData info;
public final @Nullable BuiltRenderSectionData info;
public final Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes; public final Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes;
public final int buildTime; public ChunkBuildOutput(RenderSection render, BuiltRenderSectionData info, Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes, int buildTime) {
super(render, buildTime);
private boolean partialUpload;
public ChunkBuildOutput(RenderSection render, @Nullable BuiltRenderSectionData info, Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes, int buildTime) {
this.render = render;
this.info = info; this.info = info;
this.meshes = meshes; this.meshes = meshes;
this.buildTime = buildTime;
if (this.info != null) { if (this.info != null) {
this.info.bake(); this.info.bake();
} }
} }
public BuiltSectionMeshParts getMesh(TerrainRenderPass pass) { @Override
return this.meshes.get(pass);
}
public void delete() { public void delete() {
for (BuiltSectionMeshParts data : this.meshes.values()) { for (BuiltSectionMeshParts data : this.meshes.values()) {
if(data.getVertexData() != null) { data.free();
data.getVertexData().free();
} }
if(data.getIndexData() != null) {
data.getIndexData().free();
}
}
}
public boolean isIndexOnlyUpload() {
return partialUpload;
}
public void setIndexOnlyUpload(boolean flag) {
partialUpload = flag;
} }
} }
@@ -0,0 +1,24 @@
package org.embeddedt.embeddium.impl.render.chunk.compile;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
import org.embeddedt.embeddium.impl.common.util.NativeBuffer;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
public class ChunkSortOutput extends ChunkTaskOutput {
public record SortedMesh(NativeBuffer indexData) {}
public final Reference2ReferenceMap<TerrainRenderPass, SortedMesh> meshes;
public ChunkSortOutput(RenderSection render, int buildTime, Reference2ReferenceMap<TerrainRenderPass, SortedMesh> meshes) {
super(render, buildTime);
this.meshes = meshes;
}
@Override
public void delete() {
for (SortedMesh data : this.meshes.values()) {
data.indexData().free();
}
}
}
@@ -0,0 +1,17 @@
package org.embeddedt.embeddium.impl.render.chunk.compile;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
public abstract class ChunkTaskOutput {
public final RenderSection render;
public final int buildTime;
protected ChunkTaskOutput(RenderSection render, int buildTime) {
this.render = render;
this.buildTime = buildTime;
}
public void delete() {
}
}
@@ -198,6 +198,10 @@ public class ChunkBuilder {
return this.threads.size(); return this.threads.size();
} }
public void managedBlock(BooleanSupplier isDone) {
this.managedBlocker.managedBlock(isDone);
}
public static final class WorkerThread extends Thread implements GlobalChunkBuildContext.Holder { public static final class WorkerThread extends Thread implements GlobalChunkBuildContext.Holder {
private final ChunkBuildContext context; private final ChunkBuildContext context;
@@ -1,25 +1,26 @@
package org.embeddedt.embeddium.impl.render.chunk.compile.executor; package org.embeddedt.embeddium.impl.render.chunk.compile.executor;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkTaskOutput;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer; import java.util.function.Consumer;
public class ChunkJobCollector { public class ChunkJobCollector {
private final Semaphore semaphore = new Semaphore(0); private final Semaphore semaphore = new Semaphore(0);
private final Consumer<ChunkJobResult<ChunkBuildOutput>> collector; private final Consumer<ChunkJobResult<? extends ChunkTaskOutput>> collector;
private final List<ChunkJob> submitted = new ArrayList<>(); private final List<ChunkJob> submitted = new ArrayList<>();
private final int budget; private final int budget;
public ChunkJobCollector(int budget, Consumer<ChunkJobResult<ChunkBuildOutput>> collector) { public ChunkJobCollector(int budget, Consumer<ChunkJobResult<? extends ChunkTaskOutput>> collector) {
this.budget = budget; this.budget = budget;
this.collector = collector; this.collector = collector;
} }
public void onJobFinished(ChunkJobResult<ChunkBuildOutput> result) { public void onJobFinished(ChunkJobResult<? extends ChunkTaskOutput> result) {
this.semaphore.release(1); this.semaphore.release(1);
this.collector.accept(result); this.collector.accept(result);
} }
@@ -37,7 +38,24 @@ public class ChunkJobCollector {
builder.tryStealTask(job); builder.tryStealTask(job);
} }
this.semaphore.acquireUninterruptibly(this.submitted.size()); // Acquire all the permits while running the managed block logic (to handle tasks requiring input from
// the main thread)
int remaining = this.submitted.size();
BooleanSupplier isDone = () -> this.semaphore.availablePermits() > 0;
while (remaining > 0) {
int avail = this.semaphore.availablePermits();
if (avail > 0) {
int toTake = Math.min(avail, remaining);
if (this.semaphore.tryAcquire(toTake)) {
remaining -= toTake;
continue;
}
}
// otherwise, help by running a task
builder.managedBlock(isDone);
}
} }
public void addSubmittedJob(ChunkJob job) { public void addSubmittedJob(ChunkJob job) {
@@ -0,0 +1,99 @@
package org.embeddedt.embeddium.impl.render.chunk.compile.executor;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMaps;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkTaskOutput;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
import java.util.function.LongFunction;
public class ChunkJobMetricsTracker {
public static final long OBSERVATION_COUNT_TIME = TimeUnit.SECONDS.toNanos(1);
public record MetricStats(long avg, long max, long min) {
public String toString(LongFunction<String> observationStringifier) {
return "avg = " + observationStringifier.apply(avg)
+ ", max = " + observationStringifier.apply(max)
+ ", min = " + observationStringifier.apply(min);
}
@Override
public @NotNull String toString() {
return toString(String::valueOf);
}
}
public static class MetricsData {
private static final int MAX_OBSERVATIONS = 10000;
private final LongArrayList observations = new LongArrayList(MAX_OBSERVATIONS);
private int nextInsertPoint = 0;
private int observationsInLastTimeInterval;
private int observationsInCurrentTimeInterval;
public void collect(long observation) {
if (observations.size() < MAX_OBSERVATIONS) {
observations.add(observation);
} else {
observations.set(nextInsertPoint++, observation);
if (nextInsertPoint >= MAX_OBSERVATIONS) {
nextInsertPoint = 0;
}
}
observationsInCurrentTimeInterval++;
}
public int getObservationsInLastTimeInterval() {
return this.observationsInLastTimeInterval;
}
public MetricStats getStats() {
int count = observations.size();
if (count == 0) {
return new MetricStats(0, 0, 0);
}
var iter = observations.iterator();
long sum = 0;
long min = Long.MAX_VALUE;
long max = Long.MIN_VALUE;
while (iter.hasNext()) {
long observation = iter.next();
sum += observation;
min = Math.min(min, observation);
max = Math.max(max, observation);
}
return new MetricStats(sum / count, max, min);
}
}
private final Reference2ReferenceMap<Class<? extends ChunkTaskOutput>, MetricsData> metricsByTask = new Reference2ReferenceArrayMap<>(2);
private long lastTimeIntervalFlip = System.nanoTime();
public void tick() {
long time = System.nanoTime();
if ((time - lastTimeIntervalFlip) >= OBSERVATION_COUNT_TIME) {
for (var data : metricsByTask.values()) {
data.observationsInLastTimeInterval = data.observationsInCurrentTimeInterval;
data.observationsInCurrentTimeInterval = 0;
}
lastTimeIntervalFlip = time;
}
}
public void collectMetrics(ChunkJobResult.Success<? extends ChunkTaskOutput> successfulResult) {
if (successfulResult.executionTimeNanos() < 0) {
return;
}
var data = metricsByTask.computeIfAbsent(successfulResult.output().getClass(), $ -> new MetricsData());
data.collect(successfulResult.executionTimeNanos());
}
public Reference2ReferenceMap<Class<? extends ChunkTaskOutput>, MetricsData> getMetrics() {
return Reference2ReferenceMaps.unmodifiable(metricsByTask);
}
}
@@ -1,30 +1,24 @@
package org.embeddedt.embeddium.impl.render.chunk.compile.executor; package org.embeddedt.embeddium.impl.render.chunk.compile.executor;
public class ChunkJobResult<OUTPUT> { import java.util.Objects;
private final OUTPUT output;
private final Throwable throwable; public sealed interface ChunkJobResult<OUTPUT> permits ChunkJobResult.Success, ChunkJobResult.Failure {
record Success<OUTPUT>(OUTPUT output, long executionTimeNanos) implements ChunkJobResult<OUTPUT> {
private ChunkJobResult(OUTPUT output, Throwable throwable) {
this.output = output;
this.throwable = throwable;
} }
public static <OUTPUT> ChunkJobResult<OUTPUT> exceptionally(Throwable throwable) { record Failure<OUTPUT>(Throwable throwable) implements ChunkJobResult<OUTPUT> {
return new ChunkJobResult<>(null, throwable); public Failure {
Objects.requireNonNull(throwable);
} }
public static <OUTPUT> ChunkJobResult<OUTPUT> successfully(OUTPUT output) { public void abort() {
return new ChunkJobResult<>(output, null);
}
public OUTPUT unwrap() {
if (this.throwable instanceof RuntimeException crashException) { if (this.throwable instanceof RuntimeException crashException) {
// Propagate RuntimeExceptions directly to provide extra information if they are a vanilla crash exception // Propagate RuntimeExceptions directly to provide extra information if they are a vanilla crash exception
throw crashException; throw crashException;
} else if (this.throwable != null) { } else {
throw new RuntimeException("Exception thrown while executing job", this.throwable); throw new RuntimeException("Exception thrown while executing job", this.throwable);
} }
}
return this.output;
} }
} }
@@ -40,6 +40,8 @@ public class ChunkJobTyped<TASK extends ChunkBuilderTask<OUTPUT>, OUTPUT>
ChunkJobResult<OUTPUT> result; ChunkJobResult<OUTPUT> result;
long startTime = System.nanoTime();
try { try {
var output = this.task.execute(context, this); var output = this.task.execute(context, this);
@@ -48,9 +50,9 @@ public class ChunkJobTyped<TASK extends ChunkBuilderTask<OUTPUT>, OUTPUT>
return; return;
} }
result = ChunkJobResult.successfully(output); result = new ChunkJobResult.Success<>(output, System.nanoTime() - startTime);
} catch (Throwable throwable) { } catch (Throwable throwable) {
result = ChunkJobResult.exceptionally(throwable); result = new ChunkJobResult.Failure<>(throwable);
ChunkBuilder.LOGGER.error("Chunk build failed", throwable); ChunkBuilder.LOGGER.error("Chunk build failed", throwable);
} }
@@ -0,0 +1,113 @@
package org.embeddedt.embeddium.impl.render.chunk.compile.pipeline;
import org.embeddedt.embeddium.impl.model.quad.BakedQuadView;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.sprite.SpriteTransparencyLevel;
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
import java.util.List;
public class BakedQuadGroupAnalyzer {
/**
* Tracks whether the MC-138211 quad reorienting fix should be applied during emission of quad geometry.
* This fix must be disabled with certain modded models that use superimposed quads, as it can alter the triangulation
* of some layers but not others, resulting in Z-fighting.
*/
public static final int USE_REORIENTING = 0x1;
public static final int USE_RENDER_PASS_OPTIMIZATION = 0x2;
public static final int USE_ALL_THINGS = 0xFFFFFFFF;
private int defaultRenderingFlags = 0;
private int unassignedFaceRenderingFlags = 0;
private static int computeLightFlagMask(BakedQuadView quad) {
int flag = 0;
if (quad.hasAmbientOcclusion()) {
flag |= 1;
}
if (quad.hasShade()) {
flag |= 2;
}
return flag;
}
private SpriteTransparencyLevel getQuadTransparencyLevel(BakedQuadView quad) {
if ((quad.getFlags() & ModelQuadFlags.IS_PASS_OPTIMIZABLE) == 0 || quad.celeritas$getSprite() == null) {
return SpriteTransparencyLevel.TRANSLUCENT;
}
return SpriteTransparencyLevel.Holder.getTransparencyLevel(quad.celeritas$getSprite());
}
public void setDefaultRenderingFlags(int flags) {
this.defaultRenderingFlags = flags;
this.unassignedFaceRenderingFlags = flags;
}
public int getFlagsForRendering(ModelQuadFacing facing, List<? extends BakedQuadView> quads) {
int quadRenderingFlags = facing == ModelQuadFacing.UNASSIGNED ? this.unassignedFaceRenderingFlags : this.defaultRenderingFlags;
int quadsSize = quads.size();
// By definition, singleton or empty lists of quads have a common config. Only check larger lists
if (quadsSize >= 2) {
// Disable reorienting if quads use different light configurations, as otherwise layered quads
// may be triangulated differently from others in the stack, and that will cause z-fighting.
int flagMask = -1;
SpriteTransparencyLevel highestSeenLevel = SpriteTransparencyLevel.OPAQUE;
// noinspection ForLoopReplaceableByForEach
for (int i = 0; i < quadsSize; i++) {
var quad = BakedQuadView.of(quads.get(i));
int newFlag = computeLightFlagMask(quad);
if (flagMask == -1) {
flagMask = newFlag;
} else if (newFlag != flagMask) {
// Disable reorienting
quadRenderingFlags &= ~USE_REORIENTING;
}
SpriteTransparencyLevel level = getQuadTransparencyLevel(quad);
if (level.ordinal() < highestSeenLevel.ordinal()) {
// Downgrading will result in the quads being rendered in the wrong order, disable
quadRenderingFlags &= ~USE_RENDER_PASS_OPTIMIZATION;
} else {
highestSeenLevel = level;
}
}
}
// Disable any flags in the null cullface that were disabled in other cullfaces
this.unassignedFaceRenderingFlags &= quadRenderingFlags;
return quadRenderingFlags;
}
public static Material chooseOptimalMaterial(int analyzerFlags, Material defaultMaterial, RenderPassConfiguration<?> renderPassConfiguration, BakedQuadView quad) {
if (defaultMaterial == renderPassConfiguration.defaultSolidMaterial() || (analyzerFlags & USE_RENDER_PASS_OPTIMIZATION) == 0 || (quad.getFlags() & ModelQuadFlags.IS_PASS_OPTIMIZABLE) == 0 || quad.celeritas$getSprite() == null) {
// No improvement possible
return defaultMaterial;
}
SpriteTransparencyLevel level = SpriteTransparencyLevel.Holder.getTransparencyLevel(quad.celeritas$getSprite());
if (level == SpriteTransparencyLevel.OPAQUE) {
// Can use solid with no visual difference
return renderPassConfiguration.defaultSolidMaterial();
} else if (level == SpriteTransparencyLevel.TRANSPARENT && defaultMaterial == renderPassConfiguration.defaultTranslucentMaterial()) {
// Can use cutout_mipped with no visual difference
return renderPassConfiguration.defaultCutoutMippedMaterial();
} else {
// Have to use default
return defaultMaterial;
}
}
}
@@ -4,8 +4,7 @@ import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput;
import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.common.util.NativeBuffer;
import org.embeddedt.embeddium.impl.util.task.CancellationToken; import org.embeddedt.embeddium.impl.util.task.CancellationToken;
@@ -13,7 +12,7 @@ import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer
import java.util.Map; import java.util.Map;
public class ChunkBuilderSortTask extends ChunkBuilderTask<ChunkBuildOutput> { public class ChunkBuilderSortTask extends ChunkBuilderTask<ChunkSortOutput> {
private final RenderSection render; private final RenderSection render;
private final float cameraX, cameraY, cameraZ; private final float cameraX, cameraY, cameraZ;
private final int frame; private final int frame;
@@ -31,22 +30,17 @@ public class ChunkBuilderSortTask extends ChunkBuilderTask<ChunkBuildOutput> {
} }
@Override @Override
public ChunkBuildOutput execute(ChunkBuildContext context, CancellationToken cancellationSource) { public ChunkSortOutput execute(ChunkBuildContext context, CancellationToken cancellationSource) {
Reference2ReferenceOpenHashMap<TerrainRenderPass, BuiltSectionMeshParts> meshes = new Reference2ReferenceOpenHashMap<>(); var meshes = new Reference2ReferenceOpenHashMap<TerrainRenderPass, ChunkSortOutput.SortedMesh>();
for(Map.Entry<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> entry : translucentMeshes.entrySet()) { for(Map.Entry<TerrainRenderPass, TranslucentQuadAnalyzer.SortState> entry : translucentMeshes.entrySet()) {
var sortBuffer = entry.getValue(); var sortInfo = entry.getValue();
var primitiveType = this.renderPassConfiguration.getPrimitiveTypeForPass(entry.getKey()); var primitiveType = this.renderPassConfiguration.getPrimitiveTypeForPass(entry.getKey());
var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortBuffer.centersLength() / 3)); var newIndexBuffer = new NativeBuffer(primitiveType.getIndexBufferSize(sortInfo.centersLength() / 3));
primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortBuffer.centersLength() / 3, sortBuffer, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ()); primitiveType.generateSortedIndexBuffer(newIndexBuffer.getDirectBuffer(), sortInfo.centersLength() / 3, sortInfo, cameraX - this.render.getOriginX(), cameraY - this.render.getOriginY(), cameraZ - this.render.getOriginZ());
meshes.put(entry.getKey(), new BuiltSectionMeshParts( meshes.put(entry.getKey(), new ChunkSortOutput.SortedMesh(
null, newIndexBuffer
newIndexBuffer,
sortBuffer,
null
)); ));
} }
ChunkBuildOutput result = new ChunkBuildOutput(render, null, meshes, this.frame); return new ChunkSortOutput(render, this.frame, meshes);
result.setIndexOnlyUpload(true);
return result;
} }
} }
@@ -4,39 +4,20 @@ import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import org.embeddedt.embeddium.impl.gl.util.VertexRange; import org.embeddedt.embeddium.impl.gl.util.VertexRange;
import org.embeddedt.embeddium.impl.common.util.NativeBuffer; import org.embeddedt.embeddium.impl.common.util.NativeBuffer;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers;
import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer; import org.embeddedt.embeddium.impl.render.chunk.sorting.TranslucentQuadAnalyzer;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class BuiltSectionMeshParts { import java.util.Map;
private final VertexRange[] ranges;
private final NativeBuffer buffer;
private final NativeBuffer indexBuffer;
private final TranslucentQuadAnalyzer.SortState sortState;
public BuiltSectionMeshParts(NativeBuffer buffer, @Nullable NativeBuffer indexBuffer, TranslucentQuadAnalyzer.SortState sortState, VertexRange[] ranges) { public record BuiltSectionMeshParts(NativeBuffer vertexBuffer, @Nullable NativeBuffer indexBuffer, @Nullable TranslucentQuadAnalyzer.SortState sortState, Map<ModelQuadFacing, VertexRange> ranges) {
this.ranges = ranges; public void free() {
this.buffer = buffer; vertexBuffer.free();
this.indexBuffer = indexBuffer; if (indexBuffer != null) {
this.sortState = sortState; indexBuffer.free();
} }
public NativeBuffer getVertexData() {
return this.buffer;
}
@Nullable
public NativeBuffer getIndexData() {
return this.indexBuffer;
}
public VertexRange[] getVertexRanges() {
return this.ranges;
}
public TranslucentQuadAnalyzer.SortState getSortState() {
return this.sortState;
} }
public static Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> groupFromBuildBuffers(ChunkBuildBuffers buffers, float relativeCameraX, float relativeCameraY, float relativeCameraZ) { public static Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> groupFromBuildBuffers(ChunkBuildBuffers buffers, float relativeCameraX, float relativeCameraY, float relativeCameraZ) {
@@ -8,6 +8,7 @@ import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map;
public class SectionRenderDataStorage { public class SectionRenderDataStorage {
private final GlBufferSegment[] allocations = new GlBufferSegment[RenderRegion.REGION_SIZE]; private final GlBufferSegment[] allocations = new GlBufferSegment[RenderRegion.REGION_SIZE];
@@ -31,7 +32,7 @@ public class SectionRenderDataStorage {
} }
public void setMeshes(int localSectionIndex, public void setMeshes(int localSectionIndex,
GlBufferSegment allocation, @Nullable GlBufferSegment indexAllocation, VertexRange[] ranges) { GlBufferSegment allocation, @Nullable GlBufferSegment indexAllocation, Map<ModelQuadFacing, VertexRange> ranges) {
if (this.allocations[localSectionIndex] != null) { if (this.allocations[localSectionIndex] != null) {
this.allocations[localSectionIndex].delete(); this.allocations[localSectionIndex].delete();
this.allocations[localSectionIndex] = null; this.allocations[localSectionIndex] = null;
@@ -57,7 +58,7 @@ public class SectionRenderDataStorage {
int verticesPerPrimitive = primitiveType.getVerticesPerPrimitive(); int verticesPerPrimitive = primitiveType.getVerticesPerPrimitive();
for (int facingIndex = 0; facingIndex < ModelQuadFacing.COUNT; facingIndex++) { for (int facingIndex = 0; facingIndex < ModelQuadFacing.COUNT; facingIndex++) {
VertexRange vertexRange = ranges[facingIndex]; VertexRange vertexRange = ranges.get(ModelQuadFacing.VALUES[facingIndex]);
int vertexCount; int vertexCount;
if (vertexRange != null) { if (vertexRange != null) {
@@ -19,6 +19,18 @@ public record ChunkRebuildLists(Map<ChunkUpdateType, ArrayDeque<RenderSection>>
return byUpdateType.get(type).size() + queueOverflowCounts.getOrDefault(type, 0); return byUpdateType.get(type).size() + queueOverflowCounts.getOrDefault(type, 0);
} }
public boolean isEmpty() {
if (hasAdditionalUpdates) {
return false;
}
for (var queue : byUpdateType.values()) {
if (!queue.isEmpty()) {
return false;
}
}
return true;
}
static { static {
Map<ChunkUpdateType, ArrayDeque<RenderSection>> rebuildLists = new EnumMap<>(ChunkUpdateType.class); Map<ChunkUpdateType, ArrayDeque<RenderSection>> rebuildLists = new EnumMap<>(ChunkUpdateType.class);
@@ -94,12 +94,12 @@ public class RenderListManager {
this.rebuildLists = ChunkRebuildLists.EMPTY; this.rebuildLists = ChunkRebuildLists.EMPTY;
} }
public void startGraphUpdate(Viewport viewport, int frame, float searchDistance, boolean useOcclusionCulling, boolean allowInfiniteUpdateTasks) { public void startGraphUpdate(Viewport viewport, int frame, int regionIdsLength, float searchDistance, boolean useOcclusionCulling, boolean allowInfiniteUpdateTasks) {
if (this.currentOcclusionFuture != null) { if (this.currentOcclusionFuture != null) {
throw new IllegalStateException("Occlusion work in progress while trying to submit next task"); throw new IllegalStateException("Occlusion work in progress while trying to submit next task");
} }
var visitor = new VisibleChunkCollector(frame, allowInfiniteUpdateTasks); var visitor = new VisibleChunkCollector(frame, regionIdsLength, allowInfiniteUpdateTasks);
Supplier<VisibleChunkCollector> occlusionTask = () -> { Supplier<VisibleChunkCollector> occlusionTask = () -> {
this.occlusionCuller.findVisible(visitor, viewport, searchDistance, useOcclusionCulling, frame); this.occlusionCuller.findVisible(visitor, viewport, searchDistance, useOcclusionCulling, frame);
@@ -270,6 +270,13 @@ public class RenderListManager {
return this.debugStatistics; return this.debugStatistics;
} }
public String getTickerDebugString() {
if (this.sectionTicker == null) {
return "";
}
return this.sectionTicker.getDebugString();
}
private RenderListDebugStatistics computeDebugStatistics() { private RenderListDebugStatistics computeDebugStatistics() {
Object2IntOpenHashMap<TerrainRenderPass> renderPassCounts = new Object2IntOpenHashMap<>(); Object2IntOpenHashMap<TerrainRenderPass> renderPassCounts = new Object2IntOpenHashMap<>();
@@ -5,4 +5,8 @@ import java.util.List;
public interface SectionTicker { public interface SectionTicker {
void tickVisibleRenders(); void tickVisibleRenders();
void onRenderListUpdated(List<ChunkRenderList> renderLists); void onRenderListUpdated(List<ChunkRenderList> renderLists);
default String getDebugString() {
return "";
}
} }
@@ -19,7 +19,7 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
private final ObjectArrayList<ChunkRenderList> sortedRenderLists; private final ObjectArrayList<ChunkRenderList> sortedRenderLists;
private final EnumMap<ChunkUpdateType, ArrayDeque<RenderSection>> sortedRebuildLists; private final EnumMap<ChunkUpdateType, ArrayDeque<RenderSection>> sortedRebuildLists;
private final int[] rebuildQueueOverflowCounts; private final int[] rebuildQueueOverflowCounts;
private final Reference2ReferenceOpenHashMap<RenderRegion, ChunkRenderList> renderListsByRegion; private final ChunkRenderList[] renderListsByRegion;
private final int frame; private final int frame;
@@ -27,14 +27,14 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
private boolean hasAdditionalUpdates; private boolean hasAdditionalUpdates;
public VisibleChunkCollector(int frame, boolean ignoreQueueSizeLimit) { public VisibleChunkCollector(int frame, int regionIdsLength, boolean ignoreQueueSizeLimit) {
this.frame = frame; this.frame = frame;
this.sortedRenderLists = new ObjectArrayList<>(); this.sortedRenderLists = new ObjectArrayList<>();
this.sortedRebuildLists = new EnumMap<>(ChunkUpdateType.class); this.sortedRebuildLists = new EnumMap<>(ChunkUpdateType.class);
this.rebuildQueueOverflowCounts = new int[ChunkUpdateType.values().length]; this.rebuildQueueOverflowCounts = new int[ChunkUpdateType.values().length];
this.ignoreQueueSizeLimit = ignoreQueueSizeLimit; this.ignoreQueueSizeLimit = ignoreQueueSizeLimit;
this.renderListsByRegion = new Reference2ReferenceOpenHashMap<>(); this.renderListsByRegion = new ChunkRenderList[regionIdsLength];
for (var type : ChunkUpdateType.values()) { for (var type : ChunkUpdateType.values()) {
this.sortedRebuildLists.put(type, new ArrayDeque<>()); this.sortedRebuildLists.put(type, new ArrayDeque<>());
@@ -44,7 +44,7 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
private ChunkRenderList createRenderList(RenderRegion region) { private ChunkRenderList createRenderList(RenderRegion region) {
ChunkRenderList renderList = new ChunkRenderList(region); ChunkRenderList renderList = new ChunkRenderList(region);
this.sortedRenderLists.add(renderList); this.sortedRenderLists.add(renderList);
this.renderListsByRegion.put(region, renderList); this.renderListsByRegion[region.getId()] = renderList;
return renderList; return renderList;
} }
@@ -54,19 +54,21 @@ public class VisibleChunkCollector implements OcclusionCuller.Visitor {
// Note: even if a section does not have render objects, we must ensure the render list is initialized and put // Note: even if a section does not have render objects, we must ensure the render list is initialized and put
// into the sorted queue of lists, so that we maintain the correct order of draw calls. // into the sorted queue of lists, so that we maintain the correct order of draw calls.
RenderRegion region = section.getRegion(); int regionId = node.getRenderRegionId();
ChunkRenderList renderList = this.renderListsByRegion.get(region); ChunkRenderList renderList = this.renderListsByRegion[regionId];
if (renderList == null) { if (renderList == null) {
renderList = this.createRenderList(region); renderList = this.createRenderList(section.getRegion());
} }
if (visible && section.hasAnythingToRender()) { if (visible) {
if (section.hasAnythingToRender()) {
renderList.add(section); renderList.add(section);
} }
this.addToRebuildLists(section); this.addToRebuildLists(section);
} }
}
private void addToRebuildLists(RenderSection section) { private void addToRebuildLists(RenderSection section) {
ChunkUpdateType type = section.getPendingUpdate(); ChunkUpdateType type = section.getPendingUpdate();
@@ -10,8 +10,26 @@ public class ChunkTracker implements ClientChunkEventListener {
private final LongSet unloadQueue = new LongOpenHashSet(); private final LongSet unloadQueue = new LongOpenHashSet();
private final LongSet loadQueue = new LongOpenHashSet(); private final LongSet loadQueue = new LongOpenHashSet();
public ChunkTracker() { private final int requiredNeighborRadius;
public ChunkTracker() {
this(1);
}
/**
* Constructs a new chunk tracker.
* @param requiredNeighborRadius the radius of chunks around a given chunk that must be available before the chunk
* itself is considered loaded (0 requires no chunks to be loaded, 1 requires
* all adjacent chunks). Note that a radius of 0 is guaranteed to produce incorrect
* rendering of the edge chunks for blocks that rely on data from the adjacent chunk
* (e.g. fences, fluids). Vanilla handles this by updating the chunks again as
* neighbors load, but this wastes CPU time and looks bad
*/
public ChunkTracker(int requiredNeighborRadius) {
if (requiredNeighborRadius < 0) {
throw new IllegalArgumentException("requiredNeighborRadius must be positive");
}
this.requiredNeighborRadius = requiredNeighborRadius;
} }
@Override @Override
@@ -61,8 +79,9 @@ public class ChunkTracker implements ClientChunkEventListener {
} }
private void updateNeighbors(int x, int z) { private void updateNeighbors(int x, int z) {
for (int ox = -1; ox <= 1; ox++) { int r = this.requiredNeighborRadius;
for (int oz = -1; oz <= 1; oz++) { for (int ox = -r; ox <= r; ox++) {
for (int oz = -r; oz <= r; oz++) {
this.updateMerged(ox + x, oz + z); this.updateMerged(ox + x, oz + z);
} }
} }
@@ -71,10 +90,11 @@ public class ChunkTracker implements ClientChunkEventListener {
private void updateMerged(int x, int z) { private void updateMerged(int x, int z) {
long key = PositionUtil.packChunk(x, z); long key = PositionUtil.packChunk(x, z);
int r = this.requiredNeighborRadius;
int flags = this.chunkStatus.get(key); int flags = this.chunkStatus.get(key);
for (int ox = -1; ox <= 1; ox++) { for (int ox = -r; ox <= r; ox++) {
for (int oz = -1; oz <= 1; oz++) { for (int oz = -r; oz <= r; oz++) {
flags &= this.chunkStatus.get(PositionUtil.packChunk(ox + x, oz + z)); flags &= this.chunkStatus.get(PositionUtil.packChunk(ox + x, oz + z));
} }
} }
@@ -0,0 +1,44 @@
package org.embeddedt.embeddium.impl.render.chunk.metrics;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
public class RenderSectionMetricsTracker {
public static final Comparator<RenderSection> BY_BUILD_TIME = Comparator.comparingLong(RenderSection::getLastBuildDurationNanos);
private static final int MAX_TRACKED_SECTIONS = 5;
private final PriorityQueue<RenderSection> slowestSections = new PriorityQueue<>(BY_BUILD_TIME);
private final ReferenceOpenHashSet<RenderSection> sectionsInHeap = new ReferenceOpenHashSet<>();
private void addSection(RenderSection section) {
slowestSections.add(section);
sectionsInHeap.add(section);
}
public void removeSection(RenderSection section) {
if (sectionsInHeap.remove(section)) {
slowestSections.remove(section);
}
}
public void updateSectionBuildDuration(RenderSection section, long duration) {
removeSection(section);
section.setLastBuildDurationNanos(duration);
if (slowestSections.size() < MAX_TRACKED_SECTIONS) {
addSection(section);
} else if (duration > slowestSections.peek().getLastBuildDurationNanos()) {
sectionsInHeap.remove(slowestSections.poll());
addSection(section);
}
}
public Collection<RenderSection> getSlowestSections() {
return Collections.unmodifiableCollection(this.slowestSections);
}
}
@@ -0,0 +1,65 @@
package org.embeddedt.embeddium.impl.render.chunk.multidraw;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
import org.lwjgl.system.MemoryUtil;
public record DirectMultiDrawEmitter(MultiDrawBatch batch) implements MultiDrawEmitter {
public DirectMultiDrawEmitter() {
this(new MultiDrawBatch(MAX_COMMAND_COUNT));
}
@Override
@SuppressWarnings("IntegerMultiplicationImplicitCastToLong")
public void addDrawCommands(long pMeshData, int mask, int indexPointerMask) {
var batch = this.batch;
final var pBaseVertex = batch.pBaseVertex;
final var pElementCount = batch.pElementCount;
final var pElementPointer = batch.pElementPointer;
int size = batch.size;
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
MemoryUtil.memPutInt(pBaseVertex + (size << 2), SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing));
MemoryUtil.memPutInt(pElementCount + (size << 2), SectionRenderDataUnsafe.getElementCount(pMeshData, facing));
MemoryUtil.memPutAddress(pElementPointer + (size << 3), SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask);
size += (mask >> facing) & 1;
}
batch.size = size;
}
@Override
public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
try (DrawCommandList drawCommandList = commandList.beginTessellating(tessellation)) {
drawCommandList.multiDrawElementsBaseVertex(batch, primitiveType, GlIndexType.UNSIGNED_INT);
}
}
@Override
public int getIndexBufferSize() {
return this.batch.getIndexBufferSize();
}
@Override
public boolean isEmpty() {
return this.batch.isEmpty();
}
@Override
public void clear() {
this.batch.clear();
}
@Override
public void delete() {
this.batch.delete();
}
}
@@ -0,0 +1,112 @@
package org.embeddedt.embeddium.impl.render.chunk.multidraw;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage;
import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
import org.lwjgl.system.MemoryUtil;
/**
* A multidraw emitter that uses indirect rendering to exploit hardware acceleration, which
* reduces CPU overhead on some platforms.
* @author Ven
*/
public class IndirectMultiDrawEmitter implements MultiDrawEmitter {
// uint count;
// uint instanceCount;
// uint firstIndex;
// int baseVertex;
// uint baseInstance;
private static final int COMMAND_SIZE = 4 * 5;
private static final int BUFFER_SIZE = MultiDrawEmitter.MAX_COMMAND_COUNT * COMMAND_SIZE;
private final long indirectBuffer;
private int numCommands;
private final GlMutableBuffer indirectBufferGpu;
public IndirectMultiDrawEmitter() {
this.indirectBuffer = MemoryUtil.nmemAlignedAlloc(32, BUFFER_SIZE);
if (this.indirectBuffer == MemoryUtil.NULL) {
throw new OutOfMemoryError("Failed to allocate indirect buffer");
}
this.prefillConstants();
this.indirectBufferGpu = new GlMutableBuffer();
}
private void prefillConstants() {
// Prefill constants
long ptr = this.indirectBuffer;
for (int i = 0; i < MultiDrawEmitter.MAX_COMMAND_COUNT; i++) {
MemoryUtil.memPutInt(ptr + 4L, 1); // instanceCount
MemoryUtil.memPutInt(ptr + 16L, 0); // baseInstance
ptr += COMMAND_SIZE;
}
}
@Override
public void addDrawCommands(long pMeshData, int facingMask, int indexPointerMask) {
int size = this.numCommands;
long basePtr = this.indirectBuffer;
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
long ptr = basePtr + (long)size * COMMAND_SIZE;
MemoryUtil.memPutInt(ptr + 0L, SectionRenderDataUnsafe.getElementCount(pMeshData, facing)); // count
int indexOffset = SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask;
MemoryUtil.memPutInt(ptr + 8L, indexOffset / 4);
MemoryUtil.memPutInt(ptr + 12L, SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing)); // baseVertex
size += (facingMask >> facing) & 1;
}
this.numCommands = size;
}
@Override
public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
commandList.uploadData(this.indirectBufferGpu, this.indirectBuffer, (long)this.numCommands * COMMAND_SIZE,
GlBufferUsage.STREAM_DRAW);
commandList.bindBuffer(GlBufferTarget.DRAW_INDIRECT_BUFFER, this.indirectBufferGpu);
try (DrawCommandList drawCommandList = commandList.beginTessellating(tessellation)) {
drawCommandList.multiDrawElementsIndirect(indirectBufferGpu, numCommands, primitiveType, GlIndexType.UNSIGNED_INT);
}
commandList.bindBuffer(GlBufferTarget.DRAW_INDIRECT_BUFFER, null);
}
@Override
public boolean isEmpty() {
return this.numCommands == 0;
}
@Override
public int getIndexBufferSize() {
int elements = 0;
long pElementCount = this.indirectBuffer;
for (var index = 0; index < this.numCommands; index++) {
elements = Math.max(elements, MemoryUtil.memGetInt(pElementCount));
pElementCount += COMMAND_SIZE;
}
return elements;
}
@Override
public void clear() {
this.numCommands = 0;
}
@Override
public void delete() {
MemoryUtil.nmemAlignedFree(this.indirectBuffer);
this.indirectBufferGpu.delete();
}
}
@@ -0,0 +1,18 @@
package org.embeddedt.embeddium.impl.render.chunk.multidraw;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
public interface MultiDrawEmitter {
int MAX_COMMAND_COUNT = (ModelQuadFacing.COUNT * RenderRegion.REGION_SIZE) + 1;
void addDrawCommands(long pMeshData, int facingMask, int indexPointerMask);
void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType);
boolean isEmpty();
int getIndexBufferSize();
void clear();
void delete();
}
@@ -26,10 +26,13 @@ public class OcclusionNode extends AbstractSection {
private long visibilityData = VisibilityEncoding.NULL; private long visibilityData = VisibilityEncoding.NULL;
private final RenderSection section; private final RenderSection section;
@Getter
private final int renderRegionId;
public OcclusionNode(RenderSection section) { public OcclusionNode(RenderSection section) {
super(section.getChunkX(), section.getChunkY(), section.getChunkZ()); super(section.getChunkX(), section.getChunkY(), section.getChunkZ());
this.section = section; this.section = section;
this.renderRegionId = section.getRegion().getId();
} }
public OcclusionNode getAdjacent(int direction) { public OcclusionNode getAdjacent(int direction) {
@@ -1,6 +1,7 @@
package org.embeddedt.embeddium.impl.render.chunk.region; package org.embeddedt.embeddium.impl.render.chunk.region;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import lombok.Getter;
import org.embeddedt.embeddium.impl.gl.arena.GlBufferArena; import org.embeddedt.embeddium.impl.gl.arena.GlBufferArena;
import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer; import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
@@ -42,7 +43,15 @@ public class RenderRegion {
private final StagingBuffer stagingBuffer; private final StagingBuffer stagingBuffer;
private final int x, y, z; private final int x, y, z;
@Getter
private final int id;
private final RenderSection[] sections = new RenderSection[RenderRegion.REGION_SIZE]; private final RenderSection[] sections = new RenderSection[RenderRegion.REGION_SIZE];
@Getter
private final long[] sectionLoadTimes = new long[RenderRegion.REGION_SIZE];
@Getter
private long newestSectionLoadTime;
private int sectionCount; private int sectionCount;
private final Map<TerrainRenderPass, SectionRenderDataStorage> sectionRenderData = new Reference2ReferenceOpenHashMap<>(); private final Map<TerrainRenderPass, SectionRenderDataStorage> sectionRenderData = new Reference2ReferenceOpenHashMap<>();
@@ -50,11 +59,18 @@ public class RenderRegion {
@Unmodifiable @Unmodifiable
private List<DeviceResources> allDeviceResources = List.of(); private List<DeviceResources> allDeviceResources = List.of();
public RenderRegion(int x, int y, int z, StagingBuffer stagingBuffer) { /**
* Incremented each time the set of render passes in the region is changed.
*/
@Getter
private int passSetUpdateCount = 0;
RenderRegion(int x, int y, int z, int id, StagingBuffer stagingBuffer) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
this.id = id;
this.stagingBuffer = stagingBuffer; this.stagingBuffer = stagingBuffer;
} }
@@ -109,6 +125,7 @@ public class RenderRegion {
this.allDeviceResources = List.of(); this.allDeviceResources = List.of();
Arrays.fill(this.sections, null); Arrays.fill(this.sections, null);
Arrays.fill(this.sectionLoadTimes, 0);
} }
public boolean isEmpty() { public boolean isEmpty() {
@@ -124,6 +141,7 @@ public class RenderRegion {
if (storage == null) { if (storage == null) {
this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(renderPassConfiguration.getPrimitiveTypeForPass(pass))); this.sectionRenderData.put(pass, storage = new SectionRenderDataStorage(renderPassConfiguration.getPrimitiveTypeForPass(pass)));
this.passSetUpdateCount++;
} }
return storage; return storage;
@@ -134,7 +152,7 @@ public class RenderRegion {
return; return;
} }
this.sectionRenderData.values().removeIf(s -> { boolean anyRemoved = this.sectionRenderData.values().removeIf(s -> {
if (s.isEmpty()) { if (s.isEmpty()) {
s.delete(); s.delete();
return true; return true;
@@ -142,6 +160,10 @@ public class RenderRegion {
return false; return false;
} }
}); });
if (anyRemoved) {
this.passSetUpdateCount++;
}
} }
public void removeMeshes(int sectionIndex) { public void removeMeshes(int sectionIndex) {
@@ -178,6 +200,7 @@ public class RenderRegion {
} }
this.sections[sectionIndex] = section; this.sections[sectionIndex] = section;
this.sectionLoadTimes[sectionIndex] = 0;
this.sectionCount++; this.sectionCount++;
} }
@@ -196,9 +219,16 @@ public class RenderRegion {
} }
this.sections[sectionIndex] = null; this.sections[sectionIndex] = null;
this.sectionLoadTimes[sectionIndex] = 0;
this.sectionCount--; this.sectionCount--;
} }
public void updateSectionLoadTime(RenderSection section) {
long timestamp = System.nanoTime();
this.sectionLoadTimes[section.getSectionIndex()] = timestamp;
this.newestSectionLoadTime = timestamp;
}
@Nullable @Nullable
public RenderSection getSection(int id) { public RenderSection getSection(int id) {
return this.sections[id]; return this.sections[id];
@@ -12,15 +12,19 @@ import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput; import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkSortOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkTaskOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.executor.ChunkJobResult;
import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts; import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.*; import java.util.*;
import java.util.function.Consumer;
public class RenderRegionManager { public class RenderRegionManager {
private final Long2ReferenceOpenHashMap<RenderRegion> regions = new Long2ReferenceOpenHashMap<>(); private final Long2ReferenceOpenHashMap<RenderRegion> regions = new Long2ReferenceOpenHashMap<>();
private final BitSet regionIds = new BitSet();
private int nextFreeId = 0;
private final StagingBuffer stagingBuffer; private final StagingBuffer stagingBuffer;
@@ -46,15 +50,17 @@ public class RenderRegionManager {
region.delete(commandList); region.delete(commandList);
it.remove(); it.remove();
this.regionIds.clear(region.getId());
this.nextFreeId = Math.min(this.nextFreeId, region.getId());
} }
} }
} }
} }
public void uploadMeshes(CommandList commandList, Collection<ChunkBuildOutput> results) { public void uploadMeshes(CommandList commandList, Collection<ChunkJobResult.Success<? extends ChunkTaskOutput>> results, Runnable graphUpdateTrigger) {
for (var entry : this.createMeshUploadQueues(results)) { for (var entry : this.createMeshUploadQueues(results)) {
this.uploadMeshes(commandList, entry.getKey(), entry.getValue().stream().filter(o -> !o.isIndexOnlyUpload()).toList()); new MeshUploader(commandList, entry.getKey(), graphUpdateTrigger).processResults(entry.getValue());
this.uploadResorts(commandList, entry.getKey(), entry.getValue().stream().filter(ChunkBuildOutput::isIndexOnlyUpload).toList());
} }
} }
@@ -64,25 +70,64 @@ public class RenderRegionManager {
return entries instanceof Reference2ReferenceMap.FastEntrySet ? () -> ((Reference2ReferenceMap.FastEntrySet<K, V>)entries).fastIterator() : entries; return entries instanceof Reference2ReferenceMap.FastEntrySet ? () -> ((Reference2ReferenceMap.FastEntrySet<K, V>)entries).fastIterator() : entries;
} }
private void uploadMeshes(CommandList commandList, RenderRegion region, Collection<ChunkBuildOutput> results) { private class MeshUploader {
Map<GlVertexFormat, ArrayList<PendingSectionUpload>> uploadsByFormat = new Object2ObjectOpenHashMap<>(2); private final Map<GlVertexFormat, ArrayList<PendingSectionUpload>> uploadsByFormat = new Object2ObjectOpenHashMap<>(2);
private final CommandList commandList;
private final RenderRegion region;
private final Runnable graphUpdateTrigger;
boolean needIndexBuffer = false; private boolean needIndexBuffer;
for (ChunkBuildOutput result : results) { private MeshUploader(CommandList commandList, RenderRegion region, Runnable graphUpdateTrigger) {
this.commandList = commandList;
this.region = region;
this.graphUpdateTrigger = graphUpdateTrigger;
}
private ArrayList<PendingSectionUpload> getUploadQueue(TerrainRenderPass pass) {
return uploadsByFormat.computeIfAbsent(pass.vertexType().getVertexFormat(), $ -> new ArrayList<>());
}
private void processBuildResult(ChunkBuildOutput result) {
// Delete all existing data for the section in the region // Delete all existing data for the section in the region
region.removeMeshes(result.render.getSectionIndex()); region.removeMeshes(result.render.getSectionIndex());
// Add uploads for any new data // Add uploads for any new data
for (var entry : fastIterable(result.meshes)) { for (var entry : fastIterable(result.meshes)) {
var format = this.renderPassConfiguration.getVertexTypeForPass(entry.getKey()).getVertexFormat();
var uploads = uploadsByFormat.computeIfAbsent(format, $ -> new ArrayList<>());
BuiltSectionMeshParts mesh = Objects.requireNonNull(entry.getValue()); BuiltSectionMeshParts mesh = Objects.requireNonNull(entry.getValue());
needIndexBuffer |= mesh.getIndexData() != null; needIndexBuffer |= mesh.indexBuffer() != null;
uploads.add(new PendingSectionUpload(result.render, mesh, entry.getKey(), getUploadQueue(entry.getKey()).add(new PendingMeshRebuildUpload(result.render, mesh, entry.getKey(),
new PendingUpload(mesh.getVertexData()), mesh.getIndexData() != null ? new PendingUpload(mesh.getIndexData()) : null)); PendingUpload.of(mesh.vertexBuffer()), PendingUpload.of(mesh.indexBuffer())));
}
}
private void processSortResult(ChunkSortOutput result) {
needIndexBuffer = true;
for (var entry : fastIterable(result.meshes)) {
var pass = entry.getKey();
var mesh = entry.getValue();
var storage = region.getStorage(pass);
if (storage != null) {
storage.removeIndexBuffer(result.render.getSectionIndex());
}
getUploadQueue(entry.getKey()).add(new PendingMeshSortUpload(result.render, pass, PendingUpload.of(mesh.indexData())));
}
}
public void processResults(Collection<? extends ChunkTaskOutput> results) {
for (ChunkTaskOutput output : results) {
if (output instanceof ChunkBuildOutput result) {
processBuildResult(result);
} else if (output instanceof ChunkSortOutput result) {
processSortResult(result);
} else {
throw new IllegalStateException("Unexpected result type: " + output.getClass().getName());
} }
} }
@@ -99,11 +144,11 @@ public class RenderRegionManager {
var geometryArena = resources.getGeometryArena(); var geometryArena = resources.getGeometryArena();
bufferChanged |= geometryArena.upload(commandList, uploads.stream() bufferChanged |= geometryArena.upload(commandList, uploads.stream()
.map(upload -> upload.vertexUpload)); .map(PendingSectionUpload::vertexUpload).filter(Objects::nonNull));
if (needIndexBuffer) { if (needIndexBuffer) {
bufferChanged |= resources.getOrCreateIndexArena(commandList).upload(commandList, uploads.stream() bufferChanged |= resources.getOrCreateIndexArena(commandList).upload(commandList, uploads.stream()
.map(upload -> upload.indexUpload).filter(Objects::nonNull)); .map(PendingSectionUpload::indexUpload).filter(Objects::nonNull));
} }
} }
@@ -114,74 +159,39 @@ public class RenderRegionManager {
region.refresh(commandList); region.refresh(commandList);
} }
int previousPassCookie = region.getPassSetUpdateCount();
// Collect the upload results // Collect the upload results
for (var uploads : uploadsByFormat.values()) { for (var uploads : uploadsByFormat.values()) {
for (PendingSectionUpload upload : uploads) { for (PendingSectionUpload upload : uploads) {
var storage = region.createStorage(upload.pass, renderPassConfiguration); var storage = region.createStorage(upload.pass(), renderPassConfiguration);
storage.setMeshes(upload.section.getSectionIndex(), if (upload instanceof PendingMeshRebuildUpload meshUpload) {
upload.vertexUpload.getResult(), upload.indexUpload != null ? upload.indexUpload.getResult() : null, upload.meshData.getVertexRanges()); // Replace meshes
var indexResult = upload.indexUpload() != null ? upload.indexUpload().getResult() : null;
storage.setMeshes(upload.section().getSectionIndex(),
upload.vertexUpload().getResult(), indexResult, meshUpload.meshData().ranges());
} else if (upload instanceof PendingMeshSortUpload) {
// Replace index buffer
storage.replaceIndexBuffer(upload.section().getSectionIndex(), upload.indexUpload().getResult());
} else {
throw new IllegalStateException();
}
} }
} }
region.removeEmptyStorages(); region.removeEmptyStorages();
}
private void uploadResorts(CommandList commandList, RenderRegion region, Collection<ChunkBuildOutput> results) { if (region.getPassSetUpdateCount() != previousPassCookie) {
Map<GlVertexFormat, ArrayList<PendingResortUpload>> uploadsByFormat = new Object2ObjectOpenHashMap<>(2); graphUpdateTrigger.run();
for (ChunkBuildOutput result : results) {
for (var entry : fastIterable(result.meshes)) {
var format = this.renderPassConfiguration.getVertexTypeForPass(entry.getKey()).getVertexFormat();
var uploads = uploadsByFormat.computeIfAbsent(format, $ -> new ArrayList<>());
var pass = entry.getKey();
var mesh = entry.getValue();
var storage = region.getStorage(pass);
if (storage != null) {
storage.removeIndexBuffer(result.render.getSectionIndex());
}
Objects.requireNonNull(mesh.getIndexData());
uploads.add(new PendingResortUpload(result.render, mesh, pass, new PendingUpload(mesh.getIndexData())));
}
}
// If we have nothing to upload, abort!
if (uploadsByFormat.isEmpty()) {
return;
}
boolean bufferChanged = false;
for (var entry : uploadsByFormat.entrySet()) {
var resources = region.createResources(entry.getKey(), commandList);
var uploads = entry.getValue();
bufferChanged |= resources.getOrCreateIndexArena(commandList).upload(commandList, uploads.stream()
.map(upload -> upload.indexUpload).filter(Objects::nonNull));
}
// If any of the buffers changed, the tessellation will need to be updated
// Once invalidated the tessellation will be re-created on the next attempted use
if (bufferChanged) {
region.refresh(commandList);
}
// Collect the upload results
for (var uploads : uploadsByFormat.values()) {
for (PendingResortUpload upload : uploads) {
var storage = region.createStorage(upload.pass, renderPassConfiguration);
storage.replaceIndexBuffer(upload.section.getSectionIndex(), upload.indexUpload.getResult());
} }
} }
} }
private Reference2ReferenceMap.FastEntrySet<RenderRegion, List<ChunkBuildOutput>> createMeshUploadQueues(Collection<ChunkBuildOutput> results) { private Reference2ReferenceMap.FastEntrySet<RenderRegion, List<ChunkTaskOutput>> createMeshUploadQueues(Collection<ChunkJobResult.Success<? extends ChunkTaskOutput>> results) {
var map = new Reference2ReferenceOpenHashMap<RenderRegion, List<ChunkBuildOutput>>(); var map = new Reference2ReferenceOpenHashMap<RenderRegion, List<ChunkTaskOutput>>();
for (var result : results) { for (var holder : results) {
var result = holder.output();
var queue = map.computeIfAbsent(result.render.getRegion(), k -> new ArrayList<>()); var queue = map.computeIfAbsent(result.render.getRegion(), k -> new ArrayList<>());
queue.add(result); queue.add(result);
} }
@@ -212,26 +222,44 @@ public class RenderRegionManager {
chunkZ >> RenderRegion.REGION_LENGTH_SH); chunkZ >> RenderRegion.REGION_LENGTH_SH);
} }
private int getNextId() {
int id = this.nextFreeId;
this.nextFreeId = this.regionIds.nextClearBit(id + 1);
this.regionIds.set(id);
return id;
}
@NotNull @NotNull
private RenderRegion create(int x, int y, int z) { private RenderRegion create(int x, int y, int z) {
var key = RenderRegion.key(x, y, z); var key = RenderRegion.key(x, y, z);
var instance = this.regions.get(key); var instance = this.regions.get(key);
if (instance == null) { if (instance == null) {
this.regions.put(key, instance = new RenderRegion(x, y, z, this.stagingBuffer)); this.regions.put(key, instance = new RenderRegion(x, y, z, this.getNextId(), this.stagingBuffer));
} }
return instance; return instance;
} }
private record PendingSectionUpload(RenderSection section, BuiltSectionMeshParts meshData, TerrainRenderPass pass, PendingUpload vertexUpload, PendingUpload indexUpload) { public int getRegionIdsLength() {
private PendingSectionUpload(RenderSection section, BuiltSectionMeshParts meshData, TerrainRenderPass pass, PendingUpload vertexUpload) { return this.regionIds.length();
this(section, meshData, pass, vertexUpload, null);
}
} }
private record PendingResortUpload(RenderSection section, BuiltSectionMeshParts meshData, TerrainRenderPass pass, PendingUpload indexUpload) { private interface PendingSectionUpload {
RenderSection section();
TerrainRenderPass pass();
PendingUpload vertexUpload();
PendingUpload indexUpload();
}
private record PendingMeshRebuildUpload(RenderSection section, BuiltSectionMeshParts meshData, TerrainRenderPass pass,
PendingUpload vertexUpload, PendingUpload indexUpload) implements PendingSectionUpload {}
private record PendingMeshSortUpload(RenderSection section, TerrainRenderPass pass, PendingUpload indexUpload) implements PendingSectionUpload {
@Override
public PendingUpload vertexUpload() {
return null;
}
} }
@@ -12,4 +12,8 @@ public interface ChunkShaderInterface {
void setModelViewMatrix(Matrix4fc matrix); void setModelViewMatrix(Matrix4fc matrix);
void setRegionOffset(float x, float y, float z); void setRegionOffset(float x, float y, float z);
void setTextureSlot(ChunkShaderTextureSlot slot, int val); void setTextureSlot(ChunkShaderTextureSlot slot, int val);
default void setSectionAges(long timestamp, long[] loadTimes) {
}
} }
Loaded 100 of 489 files, more files were not shown because too many files have changed in this diff. Show more