Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
# tools/shaders
|
||||
|
||||
- Build-time only; never referenced by code that ships. May use LWJGL and the game freely.
|
||||
- Keep the manifest format in `render-webgl2`'s `shaders` package, not here: both sides must agree.
|
||||
- A shader WebGL2 can't run is recorded as unsupported with a reason, never silently dropped.
|
||||
- Test: `./gradlew :tools:shaders:check`; run for real with `./gradlew :app-web:shaders`.
|
||||
@@ -0,0 +1,28 @@
|
||||
# tools/shaders: the game's shaders, translated for WebGL2
|
||||
|
||||
Translates every shader stage the game can compile into GLSL ES 3.00 at build time (ADR 0007), so
|
||||
the browser needs no shader compiler. `./gradlew :app-web:shaders` writes
|
||||
`app-web/build/web-shaders/shaders.json` (read by `render-webgl2`) and `shaders.txt` (what was
|
||||
translated and what WebGL2 can't run). Both hold translated Mojang shaders: never committed.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `GameShaderFiles` reads shader sources and post effects from the client jar.
|
||||
2. `PipelineCatalog` loads the game's pipeline registry on this JVM and lists every distinct stage.
|
||||
3. `Includes` expands includes, `SpirvCompiler` compiles with shaderc, `EsslTranslator` turns SPIR-V
|
||||
into GLSL ES with SPIRV-Cross, and `EsslRewrites` fills WebGL2's gaps (texel buffers become 2D
|
||||
textures; output arrays become separate outputs). Stages that depend on 0-to-1 depth get a
|
||||
second variant.
|
||||
4. `GlslangCheck` compiles and links each pipeline with `glslangValidator`.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Nothing here ships.**
|
||||
- **Vanilla shaders must translate.** Only missing WebGL2 features are allowed, each listed with why.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :tools:shaders:check
|
||||
./gradlew :app-web:shaders # the real run (needs ./incari setup)
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
// Translates the game's shaders to GLSL ES 3.00 for the browser build. Runs on a normal
|
||||
// JVM at build time, with LWJGL's shaderc and SPIRV-Cross natives, the way the desktop game does
|
||||
// at run time. Its output holds translated Mojang shaders: build output, never committed.
|
||||
|
||||
dependencies {
|
||||
// The manifest format the WebGL2 device reads, and through it the game (RenderPipelines).
|
||||
implementation(project(":render-webgl2"))
|
||||
implementation(project(":client"))
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
val repoRoot = rootProject.layout.projectDirectory
|
||||
val minecraftVersion: String = Properties().run {
|
||||
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
|
||||
getProperty("minecraft.version")
|
||||
}
|
||||
|
||||
/** This machine's LWJGL natives (shaderc and SPIRV-Cross among them), as `incari fetch` got them. */
|
||||
val nativeJars = run {
|
||||
val root = repoRoot.asFile
|
||||
providers.fileContents(repoRoot.file("work/cache/versions/$minecraftVersion/natives.txt")).asText.map { text ->
|
||||
text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) }
|
||||
}.orElse(emptyList())
|
||||
}
|
||||
|
||||
dependencies {
|
||||
runtimeOnly(files(nativeJars))
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-shaders"
|
||||
mainClass = "incari.tools.shaders.Main"
|
||||
applicationDefaultJvmArgs = listOf(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// Game classes loaded by tests write logs/ into the working directory; keep that in build/.
|
||||
val runDir = layout.buildDirectory.dir("test-run").get().asFile
|
||||
workingDir = runDir
|
||||
jvmArgs(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
doFirst { runDir.mkdirs() }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.Platforms;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* The platform the game sees while this tool lists its pipelines. Loading {@code RenderPipelines}
|
||||
* runs the game's static initializers, and {@code Util}'s asks the platform how many background
|
||||
* threads to make; nothing else is reached. Everything else fails loudly, so a future game version
|
||||
* that reaches further at class-load time shows up here rather than half-working.
|
||||
*/
|
||||
final class BuildPlatform {
|
||||
|
||||
private BuildPlatform() {}
|
||||
|
||||
static void install() {
|
||||
if (Platforms.isInstalled()) {
|
||||
return;
|
||||
}
|
||||
PlatformThreads inline = suggested -> 0;
|
||||
Platform platform = (Platform) Proxy.newProxyInstance(
|
||||
Platform.class.getClassLoader(),
|
||||
new Class<?>[] {Platform.class},
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "threads" -> inline;
|
||||
case "description" -> "Build-time shader translation (no game running)";
|
||||
case "nanoTime" -> System.nanoTime();
|
||||
case "toString" -> "BuildPlatform";
|
||||
default ->
|
||||
throw new UnsupportedOperationException("The shader tool's platform has no " + method.getName()
|
||||
+ "(); the game reached it while its pipelines were listed");
|
||||
});
|
||||
Platforms.install(platform);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import incari.render.webgl2.shaders.TexelBuffers;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites of SPIRV-Cross's GLSL ES output for what GLSL ES 3.00 lacks and desktop GLSL has.
|
||||
* Pure text transforms on the translated source, whose shape SPIRV-Cross fixes (one declaration per
|
||||
* line, {@code void main()} on a line of its own), so they're tested without the natives.
|
||||
*/
|
||||
final class EsslRewrites {
|
||||
|
||||
private static final String MAIN = "void main()";
|
||||
private static final String RENAMED_MAIN = "void incari_main()";
|
||||
|
||||
// SPIRV-Cross: "layout(location = 0) out highp vec4 coeff[2];"
|
||||
private static final Pattern OUTPUT_ARRAY =
|
||||
Pattern.compile("layout\\(location = (\\d+)\\) out ((?:highp |mediump |lowp )?\\w+) (\\w+)\\[(\\d+)\\];");
|
||||
|
||||
private EsslRewrites() {}
|
||||
|
||||
/**
|
||||
* Texel buffers as 2D textures ({@link TexelBuffers}): each {@code [iu]samplerBuffer} named
|
||||
* becomes a {@code [iu]sampler2D}, and each {@code texelFetch(name, i)} reads the texel at
|
||||
* {@code (i % WIDTH, i / WIDTH)}, level 0. Also drops the texture-buffer extension SPIRV-Cross
|
||||
* asks for.
|
||||
*/
|
||||
static String texelBuffers(String glsl, List<String> names) {
|
||||
if (names.isEmpty()) {
|
||||
return glsl;
|
||||
}
|
||||
String result = glsl.replaceAll("(?m)^#extension GL_(OES|EXT)_texture_buffer : (require|enable)\\n", "");
|
||||
for (String name : names) {
|
||||
Pattern declaration = Pattern.compile(
|
||||
"uniform ((?:highp |mediump |lowp )?)([iu]?)samplerBuffer " + Pattern.quote(name) + ";");
|
||||
Matcher matcher = declaration.matcher(result);
|
||||
if (!matcher.find()) {
|
||||
throw new IllegalStateException("No samplerBuffer declaration of " + name + " in:\n" + glsl);
|
||||
}
|
||||
result = matcher.replaceFirst(Matcher.quoteReplacement("uniform highp " + matcher.group(2) + "sampler2D "
|
||||
+ name + ";\nivec2 incari_texel_" + name + "(int i)\n{\n return ivec2(i & "
|
||||
+ (TexelBuffers.WIDTH - 1) + ", i >> " + TexelBuffers.WIDTH_SHIFT + ");\n}"));
|
||||
result = rewriteFetches(result, name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String rewriteFetches(String glsl, String name) {
|
||||
String call = "texelFetch(" + name + ", ";
|
||||
StringBuilder out = new StringBuilder();
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int start = glsl.indexOf(call, from);
|
||||
if (start < 0) {
|
||||
break;
|
||||
}
|
||||
int argument = start + call.length();
|
||||
int end = closingParenthesis(glsl, argument);
|
||||
out.append(glsl, from, start)
|
||||
.append("texelFetch(")
|
||||
.append(name)
|
||||
.append(", incari_texel_")
|
||||
.append(name)
|
||||
.append('(')
|
||||
.append(glsl, argument, end)
|
||||
.append("), 0)");
|
||||
from = end + 1;
|
||||
}
|
||||
return out.append(glsl, from, glsl.length()).toString();
|
||||
}
|
||||
|
||||
/** The index of the parenthesis that closes a call whose arguments start at {@code from}. */
|
||||
private static int closingParenthesis(String glsl, int from) {
|
||||
int depth = 0;
|
||||
for (int i = from; i < glsl.length(); i++) {
|
||||
char c = glsl.charAt(i);
|
||||
if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
if (depth == 0) {
|
||||
return i;
|
||||
}
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Unbalanced texelFetch call in translated shader");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment output arrays as separate outputs. GLSL ES 3.00 only lets a fragment shader index an
|
||||
* output array with a constant, and the game's order-independent transparency writes
|
||||
* {@code coeff[attachmentIndex]} in a loop. The array becomes a private global the shader writes
|
||||
* as before, and a new {@code main} copies each element to an output of its own at the element's
|
||||
* location after the game's {@code main} returns (a {@code discard} still discards).
|
||||
*/
|
||||
static String fragmentOutputArrays(String glsl) {
|
||||
Matcher matcher = OUTPUT_ARRAY.matcher(glsl);
|
||||
List<String> copies = new ArrayList<>();
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
int location = Integer.parseInt(matcher.group(1));
|
||||
String type = matcher.group(2);
|
||||
String name = matcher.group(3);
|
||||
int length = Integer.parseInt(matcher.group(4));
|
||||
StringBuilder replacement = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
String output = "incari_out_" + name + "_" + i;
|
||||
replacement
|
||||
.append("layout(location = ")
|
||||
.append(location + i)
|
||||
.append(") out ")
|
||||
.append(type)
|
||||
.append(' ')
|
||||
.append(output)
|
||||
.append(";\n");
|
||||
copies.add(" " + output + " = " + name + "[" + i + "];\n");
|
||||
}
|
||||
replacement
|
||||
.append(type)
|
||||
.append(' ')
|
||||
.append(name)
|
||||
.append('[')
|
||||
.append(length)
|
||||
.append("];");
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(replacement.toString()));
|
||||
}
|
||||
if (copies.isEmpty()) {
|
||||
return glsl;
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
String result = out.toString();
|
||||
if (!result.contains(MAIN + "\n")) {
|
||||
throw new IllegalStateException("No main() in translated shader:\n" + glsl);
|
||||
}
|
||||
result = result.replace(MAIN + "\n", RENAMED_MAIN + "\n");
|
||||
return result + "\n" + MAIN + "\n{\n incari_main();\n" + String.join("", copies) + "}\n\n";
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.lwjgl.util.spvc.Spvc;
|
||||
import org.lwjgl.util.spvc.SpvcReflectedResource;
|
||||
|
||||
/**
|
||||
* SPIR-V to GLSL ES 3.00 with SPIRV-Cross, plus the reflection the WebGL2 device needs.
|
||||
*
|
||||
* <p>WebGL2 changes three things about how a program is wired, and the translation follows them:
|
||||
* <ul>
|
||||
* <li>ES 3.00 has no {@code layout(binding)} and no locations on the varyings between stages,
|
||||
* which match by name there. The game's stages match by location, so both sides of each
|
||||
* varying are renamed after its location ({@code incari_io_3}).
|
||||
* <li>Uniform blocks and samplers keep the game's names, which are the pipeline's uniform
|
||||
* names: the device binds them by name when it links the program.
|
||||
* <li>Vertex inputs keep their names and locations; the device matches them to the vertex
|
||||
* format's elements by name, as the game's own pipeline builder does.
|
||||
* </ul>
|
||||
* WebGL2 has no storage buffers or push constants; a stage using one is reported unsupported
|
||||
* rather than translated wrongly. Texel buffers and fragment output arrays, which GLSL ES 3.00
|
||||
* lacks too, are rewritten ({@link EsslRewrites}).
|
||||
*/
|
||||
final class EsslTranslator {
|
||||
|
||||
// SPIR-V enum values (the SPIR-V specification's, as LWJGL passes them through).
|
||||
private static final int DECORATION_LOCATION = 30;
|
||||
private static final int DIM_2D = 1;
|
||||
private static final int DIM_CUBE = 3;
|
||||
private static final int DIM_BUFFER = 5;
|
||||
|
||||
/** The prefix of the varyings' shared names; the location follows. */
|
||||
static final String VARYING_PREFIX = "incari_io_";
|
||||
|
||||
/** The prefix of uniform block instance names; the block's name follows. */
|
||||
static final String BLOCK_PREFIX = "incari_ubo_";
|
||||
|
||||
private EsslTranslator() {}
|
||||
|
||||
static TranslatedStage translate(String key, String sourceHash, int[] spirv, ShaderType type)
|
||||
throws ShaderException {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer out = stack.mallocPointer(1);
|
||||
check(0, Spvc.spvc_context_create(out), "create a context");
|
||||
long context = out.get(0);
|
||||
try {
|
||||
IntBuffer words =
|
||||
MemoryUtil.memAllocInt(spirv.length).put(spirv).flip();
|
||||
try {
|
||||
check(context, Spvc.spvc_context_parse_spirv(context, words, spirv.length, out), "parse SPIR-V");
|
||||
} finally {
|
||||
MemoryUtil.memFree(words);
|
||||
}
|
||||
long ir = out.get(0);
|
||||
check(
|
||||
context,
|
||||
Spvc.spvc_context_create_compiler(
|
||||
context, Spvc.SPVC_BACKEND_GLSL, ir, Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, out),
|
||||
"create a GLSL compiler");
|
||||
long compiler = out.get(0);
|
||||
check(context, Spvc.spvc_compiler_create_shader_resources(compiler, out), "list resources");
|
||||
long resources = out.get(0);
|
||||
|
||||
String unsupported = unsupportedResources(compiler, resources, stack);
|
||||
if (unsupported != null) {
|
||||
return TranslatedStage.unsupported(key, sourceHash, unsupported);
|
||||
}
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
if (type == ShaderType.VERTEX) {
|
||||
for (SpvcReflectedResource input : list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, stack)) {
|
||||
long handle = Spvc.spvc_compiler_get_type_handle(compiler, input.type_id());
|
||||
int baseType = Spvc.spvc_type_get_basetype(handle);
|
||||
attributes.add(new TranslatedStage.Attribute(
|
||||
input.nameString(),
|
||||
Spvc.spvc_compiler_get_decoration(compiler, input.id(), DECORATION_LOCATION),
|
||||
baseType == Spvc.SPVC_BASETYPE_INT32 || baseType == Spvc.SPVC_BASETYPE_UINT32));
|
||||
}
|
||||
renameVaryings(compiler, list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, stack));
|
||||
} else {
|
||||
renameVaryings(compiler, list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, stack));
|
||||
}
|
||||
List<String> blocks = new ArrayList<>();
|
||||
for (SpvcReflectedResource block : list(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack)) {
|
||||
blocks.add(block.nameString());
|
||||
// The same block gets the same instance name in both stages; SPIRV-Cross would
|
||||
// number them per stage, which the linker only tolerates.
|
||||
Spvc.spvc_compiler_set_name(compiler, block.id(), BLOCK_PREFIX + block.nameString());
|
||||
}
|
||||
List<String> samplers = new ArrayList<>();
|
||||
List<String> texelBuffers = new ArrayList<>();
|
||||
for (SpvcReflectedResource sampler : list(resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, stack)) {
|
||||
samplers.add(sampler.nameString());
|
||||
long handle = Spvc.spvc_compiler_get_type_handle(compiler, sampler.type_id());
|
||||
if (Spvc.spvc_type_get_image_dimension(handle) == DIM_BUFFER) {
|
||||
texelBuffers.add(sampler.nameString());
|
||||
}
|
||||
}
|
||||
|
||||
check(context, Spvc.spvc_compiler_create_compiler_options(compiler, out), "create options");
|
||||
long options = out.get(0);
|
||||
Spvc.spvc_compiler_options_set_uint(options, Spvc.SPVC_COMPILER_OPTION_GLSL_VERSION, 300);
|
||||
Spvc.spvc_compiler_options_set_bool(options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES, true);
|
||||
// The game's shaders were written for desktop GLSL, where everything is highp.
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_FLOAT_PRECISION_HIGHP, true);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_INT_PRECISION_HIGHP, true);
|
||||
// WebGL2 can't draw from a base instance, and the device says so (nonZeroFirstInstance).
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_SUPPORT_NONZERO_BASE_INSTANCE, false);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_SEPARATE_SHADER_OBJECTS, false);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ENABLE_420PACK_EXTENSION, false);
|
||||
check(context, Spvc.spvc_compiler_install_compiler_options(compiler, options), "set options");
|
||||
check(context, Spvc.spvc_compiler_compile(compiler, out), "translate");
|
||||
String glsl = EsslRewrites.texelBuffers(MemoryUtil.memUTF8(out.get(0)), texelBuffers);
|
||||
if (type == ShaderType.FRAGMENT) {
|
||||
glsl = EsslRewrites.fragmentOutputArrays(glsl);
|
||||
}
|
||||
return new TranslatedStage(key, sourceHash, glsl, attributes, blocks, samplers, null);
|
||||
} finally {
|
||||
Spvc.spvc_context_destroy(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Why WebGL2 can't run the stage yet, or null if it can. */
|
||||
private static @Nullable String unsupportedResources(long compiler, long resources, MemoryStack stack)
|
||||
throws ShaderException {
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_PUSH_CONSTANT, stack).isEmpty()) {
|
||||
return "push constants (WebGL2 has none; emulating them is future work)";
|
||||
}
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, stack).isEmpty()) {
|
||||
return "storage buffers (not in WebGL2)";
|
||||
}
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, stack).isEmpty()
|
||||
|| !list(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, stack)
|
||||
.isEmpty()) {
|
||||
return "separate images and samplers (not in GLSL ES)";
|
||||
}
|
||||
for (SpvcReflectedResource sampler : list(resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, stack)) {
|
||||
int dimension =
|
||||
Spvc.spvc_type_get_image_dimension(Spvc.spvc_compiler_get_type_handle(compiler, sampler.type_id()));
|
||||
if (dimension != DIM_2D && dimension != DIM_CUBE && dimension != DIM_BUFFER) {
|
||||
return "sampler " + sampler.nameString() + " of SPIR-V dimension " + dimension;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void renameVaryings(long compiler, List<SpvcReflectedResource> varyings) {
|
||||
for (SpvcReflectedResource varying : varyings) {
|
||||
int location = Spvc.spvc_compiler_get_decoration(compiler, varying.id(), DECORATION_LOCATION);
|
||||
Spvc.spvc_compiler_set_name(compiler, varying.id(), VARYING_PREFIX + location);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<SpvcReflectedResource> list(long resources, int type, MemoryStack stack)
|
||||
throws ShaderException {
|
||||
PointerBuffer list = stack.mallocPointer(1);
|
||||
PointerBuffer count = stack.mallocPointer(1);
|
||||
check(0, Spvc.spvc_resources_get_resource_list_for_type(resources, type, list, count), "list resources");
|
||||
List<SpvcReflectedResource> result = new ArrayList<>();
|
||||
SpvcReflectedResource.Buffer buffer = SpvcReflectedResource.create(list.get(0), (int) count.get(0));
|
||||
for (int i = 0; i < count.get(0); i++) {
|
||||
result.add(buffer.get(i));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void check(long context, int result, String what) throws ShaderException {
|
||||
if (result != Spvc.SPVC_SUCCESS) {
|
||||
String detail = context == 0 ? "" : ": " + Spvc.spvc_context_get_last_error_string(context);
|
||||
throw new ShaderException("SPIRV-Cross couldn't " + what + " (error " + result + ")" + detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The shader files in the game's jar, named the way the game names them at run time: a stage by
|
||||
* the file's id without extension ({@code minecraft:core/gui}), an include by its file name under
|
||||
* {@code shaders/include} ({@code minecraft:globals.glsl}), a post effect by its file name under
|
||||
* {@code post_effect} ({@code minecraft:blur}).
|
||||
*/
|
||||
final class GameShaderFiles {
|
||||
|
||||
private final Map<String, String> vertex = new HashMap<>();
|
||||
private final Map<String, String> fragment = new HashMap<>();
|
||||
private final Map<String, String> includes = new HashMap<>();
|
||||
private final Map<String, String> postEffects = new TreeMap<>();
|
||||
|
||||
static GameShaderFiles read(Path clientJar) throws IOException {
|
||||
GameShaderFiles files = new GameShaderFiles();
|
||||
try (ZipFile jar = new ZipFile(clientJar.toFile())) {
|
||||
Enumeration<? extends ZipEntry> entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (!entry.isDirectory()) {
|
||||
files.add(entry.getName(), jar, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private void add(String name, ZipFile jar, ZipEntry entry) throws IOException {
|
||||
// assets/<namespace>/<path>
|
||||
String[] parts = name.split("/", 3);
|
||||
if (parts.length < 3 || !parts[0].equals("assets")) {
|
||||
return;
|
||||
}
|
||||
String namespace = parts[1];
|
||||
String path = parts[2];
|
||||
if (path.startsWith("shaders/include/") && path.endsWith(".glsl")) {
|
||||
includes.put(namespace + ":" + path.substring("shaders/include/".length()), text(jar, entry));
|
||||
} else if (path.startsWith("shaders/") && path.endsWith(".vsh")) {
|
||||
vertex.put(namespace + ":" + strip(path, "shaders/", ".vsh"), text(jar, entry));
|
||||
} else if (path.startsWith("shaders/") && path.endsWith(".fsh")) {
|
||||
fragment.put(namespace + ":" + strip(path, "shaders/", ".fsh"), text(jar, entry));
|
||||
} else if (path.startsWith("post_effect/") && path.endsWith(".json")) {
|
||||
postEffects.put(namespace + ":" + strip(path, "post_effect/", ".json"), text(jar, entry));
|
||||
}
|
||||
}
|
||||
|
||||
private static String strip(String path, String prefix, String suffix) {
|
||||
return path.substring(prefix.length(), path.length() - suffix.length());
|
||||
}
|
||||
|
||||
private static String text(ZipFile jar, ZipEntry entry) throws IOException {
|
||||
try (InputStream in = jar.getInputStream(entry)) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
String shader(ShaderType type, String id) {
|
||||
return (type == ShaderType.VERTEX ? vertex : fragment).get(id);
|
||||
}
|
||||
|
||||
Map<String, String> includes() {
|
||||
return includes;
|
||||
}
|
||||
|
||||
/** Post effect JSON by id, sorted. */
|
||||
Map<String, String> postEffects() {
|
||||
return postEffects;
|
||||
}
|
||||
|
||||
int shaderCount() {
|
||||
return vertex.size() + fragment.size();
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Checks translated GLSL ES with glslang ({@code glslangValidator}), the reference front end: each
|
||||
* vertex and fragment pair is compiled and linked as one ES 3.00 program, which also catches
|
||||
* varyings that don't line up between the stages. It checks the language only; what a particular
|
||||
* browser's compiler accepts is checked when the device links the programs in the page.
|
||||
*/
|
||||
final class GlslangCheck implements AutoCloseable {
|
||||
|
||||
private final Path validator;
|
||||
private final Path scratch;
|
||||
private int files;
|
||||
|
||||
GlslangCheck(Path validator) throws IOException {
|
||||
this.validator = validator;
|
||||
this.scratch = Files.createTempDirectory("incari-shaders");
|
||||
}
|
||||
|
||||
/** Compiles and links one program; returns glslang's complaint, or null if it's valid. */
|
||||
@Nullable
|
||||
String link(String vertexGlsl, String fragmentGlsl) throws IOException, InterruptedException {
|
||||
// glslang picks the stage from the extension.
|
||||
Path vertex = scratch.resolve("s" + files + ".vert");
|
||||
Path fragment = scratch.resolve("s" + files + ".frag");
|
||||
files++;
|
||||
Files.writeString(vertex, vertexGlsl, StandardCharsets.UTF_8);
|
||||
Files.writeString(fragment, fragmentGlsl, StandardCharsets.UTF_8);
|
||||
Process process = new ProcessBuilder(validator.toString(), "-l", vertex.toString(), fragment.toString())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
if (!process.waitFor(60, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
return "glslangValidator timed out";
|
||||
}
|
||||
Files.delete(vertex);
|
||||
Files.delete(fragment);
|
||||
if (process.exitValue() == 0) {
|
||||
return null;
|
||||
}
|
||||
return output.strip();
|
||||
}
|
||||
|
||||
/**
|
||||
* A GLSL ES restriction that desktop GLSL doesn't have, found in glslang's output.
|
||||
*
|
||||
* @param what the construct ES lacks, for the report
|
||||
* @param vertex whether the vertex stage (rather than the fragment stage) uses it
|
||||
*/
|
||||
record EsLimit(String what, boolean vertex) {}
|
||||
|
||||
// glslang: "ERROR: <file>.frag:113: 'variable indexing fragment shader output array' : not
|
||||
// supported with this profile: es"
|
||||
private static final Pattern ES_LIMIT =
|
||||
Pattern.compile("ERROR: \\S+\\.(vert|frag):\\d+: '([^']+)' : not supported with this profile: es");
|
||||
|
||||
/** The ES-only restriction that {@code problem} (glslang's output) reports, or null for any other error. */
|
||||
static @Nullable EsLimit esLimit(String problem) {
|
||||
Matcher matcher = ES_LIMIT.matcher(problem);
|
||||
return matcher.find() ? new EsLimit(matcher.group(2), matcher.group(1).equals("vert")) : null;
|
||||
}
|
||||
|
||||
/** glslangValidator from the path, or null if it isn't installed. */
|
||||
static @Nullable Path find() {
|
||||
for (String dir : System.getenv().getOrDefault("PATH", "").split(File.pathSeparator, -1)) {
|
||||
if (dir.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Path candidate = Path.of(dir, "glslangValidator");
|
||||
if (Files.isExecutable(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
Files.deleteIfExists(scratch);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Expands the game's {@code #include <namespace:file.glsl>} lines in place, as shaderc's include
|
||||
* callback does for the desktop game. Every include is inserted where it stands, even inside a
|
||||
* disabled {@code #if}: the preprocessor drops it afterwards, and the files carry their own
|
||||
* include guards, so the result compiles the same.
|
||||
*/
|
||||
final class Includes {
|
||||
|
||||
private static final Pattern INCLUDE = Pattern.compile("^\\s*#\\s*include\\s*[<\"]([^>\"]+)[>\"]\\s*$");
|
||||
|
||||
/** Deeper than any real chain; only a cycle gets here. */
|
||||
private static final int MAX_DEPTH = 32;
|
||||
|
||||
private Includes() {}
|
||||
|
||||
static String expand(String source, Map<String, String> includes) throws ShaderException {
|
||||
StringBuilder out = new StringBuilder(source.length() * 2);
|
||||
expand(source, includes, out, 0);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void expand(String source, Map<String, String> includes, StringBuilder out, int depth)
|
||||
throws ShaderException {
|
||||
if (depth > MAX_DEPTH) {
|
||||
throw new ShaderException("Includes nest deeper than " + MAX_DEPTH + "; is there a cycle?");
|
||||
}
|
||||
for (String line : source.split("\n", -1)) {
|
||||
Matcher include = INCLUDE.matcher(line);
|
||||
if (!include.matches()) {
|
||||
out.append(line).append('\n');
|
||||
continue;
|
||||
}
|
||||
String id = include.group(1);
|
||||
String name = id.indexOf(':') >= 0 ? id : "minecraft:" + id;
|
||||
String included = includes.get(name);
|
||||
if (included == null) {
|
||||
throw new ShaderException("Include not found: " + id);
|
||||
}
|
||||
expand(included, includes, out, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.ShaderManifest;
|
||||
import incari.render.webgl2.shaders.ShaderStageKey;
|
||||
import incari.render.webgl2.shaders.SourceHash;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Translates every shader stage the game can compile to GLSL ES 3.00 and writes the manifest the
|
||||
* WebGL2 device reads ({@code shaders.json}), with a report of what it did beside it
|
||||
* ({@code shaders.txt}).
|
||||
*
|
||||
* <pre>
|
||||
* incari-shaders --client-jar <jar> --minecraft <version> --out <shaders.json>
|
||||
* [--require-glslang]
|
||||
* </pre>
|
||||
*
|
||||
* Fails if a vanilla shader doesn't compile or translate, or if glslang rejects a translated
|
||||
* program. A stage WebGL2 can't run yet (a texel buffer, say) isn't a failure: it's written as
|
||||
* unsupported, listed in the report, and the device skips that pipeline's draws.
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(args));
|
||||
} catch (UsageException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
static int run(String[] args) throws IOException, InterruptedException, UsageException {
|
||||
@Nullable Path clientJar = null;
|
||||
@Nullable Path out = null;
|
||||
String minecraft = "";
|
||||
boolean requireGlslang = false;
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case "--client-jar" -> clientJar = Path.of(value(args, ++i));
|
||||
case "--out" -> out = Path.of(value(args, ++i));
|
||||
case "--minecraft" -> minecraft = value(args, ++i);
|
||||
case "--require-glslang" -> requireGlslang = true;
|
||||
default -> throw new UsageException("Unknown option '" + args[i] + "'");
|
||||
}
|
||||
}
|
||||
if (clientJar == null || out == null || minecraft.isEmpty()) {
|
||||
throw new UsageException("Usage: incari-shaders --client-jar <jar> --minecraft <version> --out <file>"
|
||||
+ " [--require-glslang]");
|
||||
}
|
||||
|
||||
GameShaderFiles files = GameShaderFiles.read(clientJar);
|
||||
List<PipelineCatalog.Pipeline> pipelines;
|
||||
try {
|
||||
pipelines = PipelineCatalog.collect(files);
|
||||
} catch (ShaderException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
return 1;
|
||||
}
|
||||
|
||||
Map<String, TranslatedStage> stages = new TreeMap<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
try (SpirvCompiler compiler = new SpirvCompiler()) {
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
for (ShaderStageKey key : List.of(pipeline.vertex(), pipeline.fragment())) {
|
||||
if (stages.containsKey(key.asString())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
TranslatedStage plain = translate(files, compiler, key, pipeline.defines(), false);
|
||||
stages.put(key.asString(), plain);
|
||||
// A device with clip control (0-to-1 depth, as the game's desktop backends
|
||||
// set up) compiles the game's shaders with one more define; a stage it
|
||||
// changes gets a second translation (ADR 0012). Only the order-independent
|
||||
// transparency passes read it, but every stage that includes their file
|
||||
// mentions it, so the translations are compared rather than the sources.
|
||||
if (readsZeroToOne(files, key)) {
|
||||
TranslatedStage zeroToOne = translate(files, compiler, key, pipeline.defines(), true);
|
||||
if (!zeroToOne.glsl().equals(plain.glsl())) {
|
||||
stages.put(zeroToOne.key(), zeroToOne);
|
||||
}
|
||||
}
|
||||
} catch (ShaderException e) {
|
||||
errors.add(key + " (first used by " + pipeline.name() + "): " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Path glslang = GlslangCheck.find();
|
||||
int linked = 0;
|
||||
Map<String, String> unsupportedPipelines = new LinkedHashMap<>();
|
||||
if (glslang == null && requireGlslang) {
|
||||
errors.add("glslangValidator isn't installed (package: glslang), and --require-glslang was given");
|
||||
}
|
||||
try (GlslangCheck check = glslang == null ? null : new GlslangCheck(glslang)) {
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
String vertexVariant = pipeline.vertex()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString();
|
||||
String fragmentVariant = pipeline.fragment()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString();
|
||||
boolean hasVariant = stages.containsKey(vertexVariant) || stages.containsKey(fragmentVariant);
|
||||
for (boolean zeroToOne : hasVariant ? new boolean[] {false, true} : new boolean[] {false}) {
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (zeroToOne) {
|
||||
vertex = stages.getOrDefault(vertexVariant, vertex);
|
||||
fragment = stages.getOrDefault(fragmentVariant, fragment);
|
||||
}
|
||||
if (vertex == null || fragment == null) {
|
||||
continue; // Already an error.
|
||||
}
|
||||
if (check != null && vertex.isSupported() && fragment.isSupported()) {
|
||||
linked += check(check, pipeline, vertex, fragment, stages, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (vertex == null || fragment == null) {
|
||||
continue; // Already an error.
|
||||
}
|
||||
String unsupported = vertex.unsupported() != null ? vertex.unsupported() : fragment.unsupported();
|
||||
if (unsupported != null) {
|
||||
unsupportedPipelines.put(pipeline.name(), unsupported);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder report = new StringBuilder();
|
||||
report.append("Shaders for WebGL2 (GLSL ES 3.00), translated from Minecraft ")
|
||||
.append(minecraft)
|
||||
.append('\n');
|
||||
report.append(pipelines.size())
|
||||
.append(" pipelines, ")
|
||||
.append(stages.size())
|
||||
.append(" distinct stages, ")
|
||||
.append(files.shaderCount())
|
||||
.append(" shader files in the jar\n");
|
||||
report.append(
|
||||
glslang == null
|
||||
? "Not checked with glslang (glslangValidator isn't installed)\n"
|
||||
: linked + " programs compiled and linked by glslang (with the 0-to-1 depth variants)\n");
|
||||
report.append('\n')
|
||||
.append(unsupportedPipelines.size())
|
||||
.append(" pipelines WebGL2 can't run yet (their draws are skipped):\n");
|
||||
unsupportedPipelines.forEach((name, reason) ->
|
||||
report.append(" ").append(name).append(": ").append(reason).append('\n'));
|
||||
StringBuilder every = new StringBuilder();
|
||||
every.append("\nEvery pipeline, and what WebGL2 needs for it (ADR 0012):\n");
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
every.append(" ")
|
||||
.append(pipeline.name())
|
||||
.append(": ")
|
||||
.append(needs(pipeline, stages))
|
||||
.append('\n');
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
report.append('\n').append(errors.size()).append(" errors:\n");
|
||||
errors.forEach(error ->
|
||||
report.append(" ").append(error.replace("\n", "\n ")).append('\n'));
|
||||
}
|
||||
System.out.print(report);
|
||||
|
||||
Path parent = out.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
String reportName = out.getFileName().toString().replaceFirst("\\.json$", "") + ".txt";
|
||||
// The full list goes to the file only: over two hundred lines.
|
||||
Files.writeString(out.resolveSibling(reportName), report.toString() + every, StandardCharsets.UTF_8);
|
||||
if (!errors.isEmpty()) {
|
||||
Files.deleteIfExists(out);
|
||||
return 1;
|
||||
}
|
||||
Files.writeString(out, new ShaderManifest(minecraft, stages.values()).toJson(), StandardCharsets.UTF_8);
|
||||
System.out.println("Wrote " + out + " (" + Files.size(out) / 1024 + " KiB)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** What a pipeline needs of WebGL2 beyond the basics, for the report's full list. */
|
||||
private static String needs(PipelineCatalog.Pipeline pipeline, Map<String, TranslatedStage> stages) {
|
||||
List<String> notes = new ArrayList<>();
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (vertex == null || fragment == null) {
|
||||
return "not translated (see the errors)";
|
||||
}
|
||||
String unsupported = vertex.unsupported() != null ? vertex.unsupported() : fragment.unsupported();
|
||||
if (unsupported != null) {
|
||||
return "can't run yet: " + unsupported;
|
||||
}
|
||||
String glsl = vertex.glsl() + fragment.glsl();
|
||||
if (glsl.contains("incari_texel_")) {
|
||||
notes.add("texel buffer as a 2D texture");
|
||||
}
|
||||
if (glsl.contains("incari_out_")) {
|
||||
notes.add("fragment output array as separate outputs");
|
||||
}
|
||||
if (stages.containsKey(pipeline.vertex()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString())
|
||||
|| stages.containsKey(pipeline.fragment()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString())) {
|
||||
notes.add("a 0-to-1 depth variant");
|
||||
}
|
||||
if (pipeline.wireframe()) {
|
||||
notes.add("WEBGL_polygon_mode (skipped without it)");
|
||||
}
|
||||
return notes.isEmpty() ? "runs as translated" : String.join(", ", notes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles and translates one stage.
|
||||
*
|
||||
* @param zeroToOne compile with the game's define for a 0-to-1 depth range, and file the
|
||||
* result under the key with that flag
|
||||
*/
|
||||
private static TranslatedStage translate(
|
||||
GameShaderFiles files, SpirvCompiler compiler, ShaderStageKey key, ShaderDefines defines, boolean zeroToOne)
|
||||
throws ShaderException {
|
||||
String source = source(files, key);
|
||||
String expanded = Includes.expand(source, files.includes());
|
||||
Map<String, String> macros = new LinkedHashMap<>(defines.values());
|
||||
for (String flag : defines.flags()) {
|
||||
macros.put(flag, "");
|
||||
}
|
||||
if (zeroToOne) {
|
||||
macros.put(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE, "");
|
||||
}
|
||||
String extension = key.type() == ShaderType.VERTEX ? ".vsh" : ".fsh";
|
||||
int[] spirv = compiler.compile(key.id() + extension, expanded, key.type(), macros);
|
||||
String filed =
|
||||
zeroToOne ? key.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE).asString() : key.asString();
|
||||
return EsslTranslator.translate(filed, SourceHash.of(source), spirv, key.type());
|
||||
}
|
||||
|
||||
/** Whether the stage's source, with its includes, reads the 0-to-1 depth define. */
|
||||
private static boolean readsZeroToOne(GameShaderFiles files, ShaderStageKey key) throws ShaderException {
|
||||
return Includes.expand(source(files, key), files.includes()).contains(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE);
|
||||
}
|
||||
|
||||
private static String source(GameShaderFiles files, ShaderStageKey key) throws ShaderException {
|
||||
String source = files.shader(key.type(), key.id().toString());
|
||||
if (source == null) {
|
||||
throw new ShaderException("No " + key.type().getName() + " shader " + key.id() + " in the jar");
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Links one program with glslang: 1 if it links, 0 if it can't (then either the stage is marked
|
||||
* unsupported, for a construct GLSL ES lacks, or the problem is added to {@code errors}).
|
||||
*/
|
||||
private static int check(
|
||||
GlslangCheck check,
|
||||
PipelineCatalog.Pipeline pipeline,
|
||||
TranslatedStage vertex,
|
||||
TranslatedStage fragment,
|
||||
Map<String, TranslatedStage> stages,
|
||||
List<String> errors)
|
||||
throws IOException, InterruptedException {
|
||||
String problem = check.link(vertex.glsl(), fragment.glsl());
|
||||
GlslangCheck.EsLimit limit = problem == null ? null : GlslangCheck.esLimit(problem);
|
||||
if (limit != null) {
|
||||
// A construct GLSL ES can't express (desktop GLSL can): the stage waits for a WebGL2
|
||||
// rewrite rather than failing the build.
|
||||
TranslatedStage stage = limit.vertex() ? vertex : fragment;
|
||||
stages.put(
|
||||
stage.key(),
|
||||
TranslatedStage.unsupported(
|
||||
stage.key(), stage.sourceHash(), "GLSL ES 3.00 has no " + limit.what()));
|
||||
return 0;
|
||||
}
|
||||
if (problem != null) {
|
||||
errors.add(pipeline.name() + " (" + vertex.key() + " + " + fragment.key()
|
||||
+ ") doesn't link as GLSL ES 3.00:\n" + problem);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static String value(String[] args, int index) throws UsageException {
|
||||
if (index >= args.length) {
|
||||
throw new UsageException(args[index - 1] + " needs a value");
|
||||
}
|
||||
return args[index];
|
||||
}
|
||||
|
||||
/** Bad command-line arguments. */
|
||||
static final class UsageException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
UsageException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.renderpearl.api.pipeline.PolygonMode;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.ShaderStageKey;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import net.minecraft.client.renderer.RenderPipelines;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.client.renderer.oit.OitPipelineSet;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Every pipeline the game can compile, as pairs of shader stages. The game's own pipelines come
|
||||
* from {@link RenderPipelines}, which registers them all in its static initializer; post effects
|
||||
* are built from their JSON files at run time, on {@link RenderPipelines#POST_PROCESSING_SNIPPET},
|
||||
* so each pass of each file in the jar is one more pipeline here.
|
||||
*/
|
||||
final class PipelineCatalog {
|
||||
|
||||
/**
|
||||
* One pipeline's two stages, and the defines both are compiled with.
|
||||
*
|
||||
* @param wireframe whether it draws outlines (a debug view; WebGL2 needs WEBGL_polygon_mode)
|
||||
*/
|
||||
record Pipeline(
|
||||
String name, ShaderStageKey vertex, ShaderStageKey fragment, ShaderDefines defines, boolean wireframe) {}
|
||||
|
||||
private PipelineCatalog() {}
|
||||
|
||||
static List<Pipeline> collect(GameShaderFiles files) throws ShaderException {
|
||||
BuildPlatform.install();
|
||||
// The registry keeps one pipeline per location, and some pipelines share one (the item
|
||||
// pipelines with and without glint), so the ones it drops are found among its fields.
|
||||
Set<RenderPipeline> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
List<RenderPipeline> all = new ArrayList<>();
|
||||
all.addAll(RenderPipelines.requiredPipelines());
|
||||
all.addAll(RenderPipelines.optionalPipelines());
|
||||
all.addAll(declaredPipelines());
|
||||
List<Pipeline> pipelines = new ArrayList<>();
|
||||
for (RenderPipeline pipeline : all) {
|
||||
if (seen.add(pipeline)) {
|
||||
pipelines.add(of(pipeline));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, String> effect : files.postEffects().entrySet()) {
|
||||
pipelines.addAll(postEffect(effect.getKey(), effect.getValue()));
|
||||
}
|
||||
return pipelines;
|
||||
}
|
||||
|
||||
/** Every pipeline {@link RenderPipelines} holds in a static field, directly or in an OIT set. */
|
||||
private static List<RenderPipeline> declaredPipelines() throws ShaderException {
|
||||
List<RenderPipeline> pipelines = new ArrayList<>();
|
||||
for (Field field : RenderPipelines.class.getDeclaredFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
Object value;
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
value = field.get(null);
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
throw new ShaderException("Can't read RenderPipelines." + field.getName() + ": " + e);
|
||||
}
|
||||
if (value instanceof RenderPipeline pipeline) {
|
||||
pipelines.add(pipeline);
|
||||
} else if (value instanceof OitPipelineSet set) {
|
||||
pipelines.add(set.depthBoundsPipeline());
|
||||
pipelines.add(set.transmittancePipeline());
|
||||
pipelines.add(set.accumulatePipeline());
|
||||
}
|
||||
}
|
||||
return pipelines;
|
||||
}
|
||||
|
||||
private static Pipeline of(RenderPipeline pipeline) {
|
||||
Map<ShaderType, Identifier> shaders = pipeline.getShaders();
|
||||
// RenderPipeline.Builder refuses to build a pipeline without both stages.
|
||||
Identifier vertex = Objects.requireNonNull(shaders.get(ShaderType.VERTEX));
|
||||
Identifier fragment = Objects.requireNonNull(shaders.get(ShaderType.FRAGMENT));
|
||||
return new Pipeline(
|
||||
pipeline.getLocation().toString(),
|
||||
ShaderStageKey.of(ShaderType.VERTEX, vertex, pipeline.getShaderDefines()),
|
||||
ShaderStageKey.of(ShaderType.FRAGMENT, fragment, pipeline.getShaderDefines()),
|
||||
pipeline.getShaderDefines(),
|
||||
pipeline.getPolygonMode() == PolygonMode.WIREFRAME);
|
||||
}
|
||||
|
||||
/** The passes of one post effect, built the way the game builds them (only the shaders matter). */
|
||||
private static List<Pipeline> postEffect(String id, String json) throws ShaderException {
|
||||
List<Pipeline> passes = new ArrayList<>();
|
||||
JsonElement passList = JsonParser.parseString(json).getAsJsonObject().get("passes");
|
||||
if (passList == null) {
|
||||
return passes;
|
||||
}
|
||||
int index = 0;
|
||||
for (JsonElement element : passList.getAsJsonArray()) {
|
||||
JsonObject pass = element.getAsJsonObject();
|
||||
Identifier vertex = parse(id, pass, "vertex_shader");
|
||||
Identifier fragment = parse(id, pass, "fragment_shader");
|
||||
RenderPipeline pipeline = RenderPipeline.builder(RenderPipelines.POST_PROCESSING_SNIPPET)
|
||||
.withVertexShader(vertex)
|
||||
.withFragmentShader(fragment)
|
||||
.withLocation(Identifier.parse(id).withSuffix("/" + index))
|
||||
.build();
|
||||
passes.add(of(pipeline));
|
||||
index++;
|
||||
}
|
||||
return passes;
|
||||
}
|
||||
|
||||
private static Identifier parse(String effect, JsonObject pass, String field) throws ShaderException {
|
||||
JsonElement value = pass.get(field);
|
||||
if (value == null) {
|
||||
throw new ShaderException("Post effect " + effect + " has a pass without " + field);
|
||||
}
|
||||
return Identifier.parse(value.getAsString());
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
/** A shader that couldn't be compiled, translated or validated; the message says which and why. */
|
||||
final class ShaderException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
ShaderException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import org.lwjgl.util.shaderc.Shaderc;
|
||||
|
||||
/**
|
||||
* GLSL to SPIR-V with shaderc, set up as the game sets it up for its own devices: Vulkan 1.2
|
||||
* semantics, uniforms bound automatically, debug info kept (SPIRV-Cross needs the names back), no
|
||||
* optimization. The browser's device reports depth as -1 to 1 and no draw parameters, so none of
|
||||
* the game's device-dependent macros are defined; only the pipeline's own defines are.
|
||||
*
|
||||
* <p>One compiler for the whole run; not thread-safe.
|
||||
*/
|
||||
final class SpirvCompiler implements AutoCloseable {
|
||||
|
||||
private final long compiler = Shaderc.shaderc_compiler_initialize();
|
||||
|
||||
/** Compiles an include-expanded source; the SPIR-V words are copied out of shaderc's result. */
|
||||
int[] compile(String name, String source, ShaderType type, Map<String, String> defines) throws ShaderException {
|
||||
long options = Shaderc.shaderc_compile_options_initialize();
|
||||
try {
|
||||
Shaderc.shaderc_compile_options_set_source_language(options, Shaderc.shaderc_source_language_glsl);
|
||||
Shaderc.shaderc_compile_options_set_target_env(
|
||||
options, Shaderc.shaderc_target_env_vulkan, Shaderc.shaderc_env_version_vulkan_1_2);
|
||||
Shaderc.shaderc_compile_options_set_auto_bind_uniforms(options, true);
|
||||
Shaderc.shaderc_compile_options_set_generate_debug_info(options);
|
||||
Shaderc.shaderc_compile_options_set_optimization_level(options, Shaderc.shaderc_optimization_level_zero);
|
||||
for (Map.Entry<String, String> define : defines.entrySet()) {
|
||||
Shaderc.shaderc_compile_options_add_macro_definition(options, define.getKey(), define.getValue());
|
||||
}
|
||||
int kind = type == ShaderType.VERTEX ? Shaderc.shaderc_vertex_shader : Shaderc.shaderc_fragment_shader;
|
||||
long result = Shaderc.shaderc_compile_into_spv(compiler, source, kind, name, "main", options);
|
||||
try {
|
||||
if (Shaderc.shaderc_result_get_compilation_status(result)
|
||||
!= Shaderc.shaderc_compilation_status_success) {
|
||||
throw new ShaderException("shaderc: "
|
||||
+ String.valueOf(Shaderc.shaderc_result_get_error_message(result))
|
||||
.trim());
|
||||
}
|
||||
ByteBuffer bytes = Shaderc.shaderc_result_get_bytes(result);
|
||||
if (bytes == null) {
|
||||
throw new ShaderException("shaderc returned no SPIR-V");
|
||||
}
|
||||
int[] words = new int[bytes.remaining() / 4];
|
||||
bytes.order(java.nio.ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(words);
|
||||
return words;
|
||||
} finally {
|
||||
Shaderc.shaderc_result_release(result);
|
||||
}
|
||||
} finally {
|
||||
Shaderc.shaderc_compile_options_release(options);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
Shaderc.shaderc_compiler_release(compiler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** The build-time shader translation for the browser build: GLSL to SPIR-V to GLSL ES 3.00. */
|
||||
@NullMarked
|
||||
package incari.tools.shaders;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EsslRewritesTest {
|
||||
|
||||
@Test
|
||||
void texelFetchesReadTheTwoDimensionalLayout() {
|
||||
String glsl = """
|
||||
#version 300 es
|
||||
#extension GL_OES_texture_buffer : require
|
||||
uniform highp isamplerBuffer CloudFaces;
|
||||
void main()
|
||||
{
|
||||
int a = texelFetch(CloudFaces, (idx * 3) + 1).x;
|
||||
int b = texelFetch(CloudFaces, f(idx, g(2))).x;
|
||||
}
|
||||
""";
|
||||
|
||||
String rewritten = EsslRewrites.texelBuffers(glsl, List.of("CloudFaces"));
|
||||
|
||||
assertThat(rewritten)
|
||||
.doesNotContain("#extension")
|
||||
.contains("uniform highp isampler2D CloudFaces;")
|
||||
.contains("return ivec2(i & 2047, i >> 11);")
|
||||
.contains("texelFetch(CloudFaces, incari_texel_CloudFaces((idx * 3) + 1), 0).x")
|
||||
.contains("texelFetch(CloudFaces, incari_texel_CloudFaces(f(idx, g(2))), 0).x");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadersWithoutTexelBuffersAreUntouched() {
|
||||
String glsl = "#version 300 es\nvoid main()\n{\n}\n";
|
||||
assertThat(EsslRewrites.texelBuffers(glsl, List.of())).isSameAs(glsl);
|
||||
assertThat(EsslRewrites.fragmentOutputArrays(glsl)).isSameAs(glsl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputArraysAreCopiedToOutputsAfterMain() {
|
||||
String glsl = """
|
||||
#version 300 es
|
||||
layout(location = 0) out highp vec4 coeff[2];
|
||||
void main()
|
||||
{
|
||||
coeff[i] = vec4(1.0);
|
||||
}
|
||||
""";
|
||||
|
||||
String rewritten = EsslRewrites.fragmentOutputArrays(glsl);
|
||||
|
||||
assertThat(rewritten)
|
||||
.contains("""
|
||||
layout(location = 0) out highp vec4 incari_out_coeff_0;
|
||||
layout(location = 1) out highp vec4 incari_out_coeff_1;
|
||||
highp vec4 coeff[2];""")
|
||||
.contains("void incari_main()\n{\n coeff[i] = vec4(1.0);\n}")
|
||||
.endsWith("""
|
||||
void main()
|
||||
{
|
||||
incari_main();
|
||||
incari_out_coeff_0 = coeff[0];
|
||||
incari_out_coeff_1 = coeff[1];
|
||||
}
|
||||
|
||||
""");
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class IncludesTest {
|
||||
|
||||
@Test
|
||||
void expandsNestedIncludesInPlace() throws Exception {
|
||||
Map<String, String> includes = Map.of(
|
||||
"minecraft:a.glsl", "float a;\n#include <minecraft:b.glsl>\n",
|
||||
"minecraft:b.glsl", "float b;\n");
|
||||
|
||||
String expanded = Includes.expand("#version 330\n #include <minecraft:a.glsl>\nvoid main() {}", includes);
|
||||
|
||||
assertThat(expanded).isEqualTo("#version 330\nfloat a;\nfloat b;\n\n\nvoid main() {}\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNamespaceDefaultsToMinecraft() throws Exception {
|
||||
assertThat(Includes.expand("#include \"globals.glsl\"", Map.of("minecraft:globals.glsl", "float g;")))
|
||||
.isEqualTo("float g;\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingIncludeIsAnError() {
|
||||
assertThatThrownBy(() -> Includes.expand("#include <minecraft:gone.glsl>", Map.of()))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("minecraft:gone.glsl");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCycleIsAnError() {
|
||||
Map<String, String> includes = Map.of("minecraft:self.glsl", "#include <minecraft:self.glsl>");
|
||||
assertThatThrownBy(() -> Includes.expand("#include <minecraft:self.glsl>", includes))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("cycle");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recognizesGlslangsEsOnlyLimits() {
|
||||
String output = """
|
||||
ERROR: /tmp/x/s111.frag:113: 'variable indexing fragment shader output array' : not supported with this profile: es
|
||||
ERROR: /tmp/x/s111.frag:113: '' : compilation terminated
|
||||
""";
|
||||
|
||||
assertThat(GlslangCheck.esLimit(output))
|
||||
.isEqualTo(new GlslangCheck.EsLimit("variable indexing fragment shader output array", false));
|
||||
assertThat(GlslangCheck.esLimit("ERROR: /tmp/x/s1.vert:3: 'foo' : undeclared identifier"))
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Runs shaderc and SPIRV-Cross (LWJGL's natives) on small shaders written for the test. */
|
||||
class TranslationTest {
|
||||
|
||||
private static final String VERTEX = """
|
||||
#version 330
|
||||
#extension GL_ARB_separate_shader_objects : require
|
||||
layout(std140) uniform Projection {
|
||||
mat4 ProjMat;
|
||||
};
|
||||
layout(location = 0) in vec3 Position;
|
||||
layout(location = 1) in ivec2 Id;
|
||||
layout(location = 2) out vec4 tint;
|
||||
void main() {
|
||||
gl_Position = ProjMat * vec4(Position, 1.0);
|
||||
tint = vec4(float(Id.x));
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String FRAGMENT = """
|
||||
#version 330
|
||||
#extension GL_ARB_separate_shader_objects : require
|
||||
layout(std140) uniform Projection {
|
||||
mat4 ProjMat;
|
||||
};
|
||||
uniform sampler2D Sampler0;
|
||||
layout(location = 2) in vec4 color;
|
||||
layout(location = 0) out vec4 fragColor;
|
||||
void main() {
|
||||
fragColor = texture(Sampler0, color.xy) * ProjMat[0][0];
|
||||
}
|
||||
""";
|
||||
|
||||
private static SpirvCompiler compiler;
|
||||
|
||||
@BeforeAll
|
||||
static void start() {
|
||||
compiler = new SpirvCompiler();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stop() {
|
||||
compiler.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void translatesToEsWithWebGlsNaming() throws Exception {
|
||||
TranslatedStage vertex = translate("vertex test:v", VERTEX, ShaderType.VERTEX);
|
||||
TranslatedStage fragment = translate("fragment test:f", FRAGMENT, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(vertex.glsl()).startsWith("#version 300 es");
|
||||
// Varyings meet by name in ES 3.00, so both sides are named after the location they share,
|
||||
// even though the game's two stages call it tint and color.
|
||||
assertThat(vertex.glsl()).contains("out vec4 incari_io_2;").doesNotContain("tint");
|
||||
assertThat(fragment.glsl()).contains("in vec4 incari_io_2;").doesNotContain(" color;");
|
||||
// Blocks keep their names (the pipeline binds by them), with one instance name in both stages.
|
||||
assertThat(vertex.glsl()).contains("uniform Projection").contains("} incari_ubo_Projection;");
|
||||
assertThat(fragment.glsl()).contains("} incari_ubo_Projection;");
|
||||
assertThat(vertex.uniformBlocks()).containsExactly("Projection");
|
||||
assertThat(fragment.samplers()).containsExactly("Sampler0");
|
||||
assertThat(vertex.attributes())
|
||||
.containsExactlyInAnyOrder(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Id", 1, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void texelBuffersBecomeTwoDimensionalTextures() throws Exception {
|
||||
String source = """
|
||||
#version 330
|
||||
uniform isamplerBuffer Faces;
|
||||
layout(location = 0) out vec4 fragColor;
|
||||
void main() {
|
||||
int index = int(gl_FragCoord.x) * 3;
|
||||
fragColor = vec4(texelFetch(Faces, index + 1).r);
|
||||
}
|
||||
""";
|
||||
|
||||
TranslatedStage stage = translate("fragment test:clouds", source, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(stage.isSupported()).isTrue();
|
||||
assertThat(stage.glsl()).contains("uniform highp isampler2D Faces;").doesNotContain("samplerBuffer");
|
||||
assertThat(stage.glsl()).containsPattern("texelFetch\\(Faces, incari_texel_Faces\\(.*\\), 0\\)");
|
||||
assertThat(stage.samplers()).containsExactly("Faces");
|
||||
assertValidEs(stage.glsl(), "frag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fragmentOutputArraysBecomeOutputs() throws Exception {
|
||||
String source = """
|
||||
#version 330
|
||||
layout(location = 0) out vec4 coeff[2];
|
||||
void main() {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
coeff[i][j] = float(i * 4 + j);
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
TranslatedStage stage = translate("fragment test:oit", source, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(stage.glsl())
|
||||
.contains("layout(location = 0) out vec4 incari_out_coeff_0;")
|
||||
.contains("layout(location = 1) out vec4 incari_out_coeff_1;");
|
||||
assertValidEs(stage.glsl(), "frag");
|
||||
}
|
||||
|
||||
/** Compiles {@code glsl} with glslang as GLSL ES, where it's installed (CI requires it). */
|
||||
private static void assertValidEs(String glsl, String stage) throws Exception {
|
||||
java.nio.file.Path validator = GlslangCheck.find();
|
||||
if (validator == null) {
|
||||
return;
|
||||
}
|
||||
java.nio.file.Path file = java.nio.file.Files.createTempFile("incari-test", "." + stage);
|
||||
try {
|
||||
java.nio.file.Files.writeString(file, glsl);
|
||||
Process process = new ProcessBuilder(validator.toString(), file.toString())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String output =
|
||||
new String(process.getInputStream().readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
assertThat(process.waitFor()).as(output + "\n" + glsl).isZero();
|
||||
} finally {
|
||||
java.nio.file.Files.delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void compileErrorsNameTheShader() {
|
||||
assertThatThrownBy(() ->
|
||||
translate("vertex test:broken", "#version 330\nvoid main() { nope(); }\n", ShaderType.VERTEX))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("shaderc")
|
||||
.hasMessageContaining("nope");
|
||||
}
|
||||
|
||||
private static TranslatedStage translate(String key, String source, ShaderType type) throws ShaderException {
|
||||
int[] spirv = compiler.compile(key, source, type, Map.of());
|
||||
return EsslTranslator.translate(key, "0000000000000000", spirv, type);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user