Files
Iris/core/build.gradle
T
piexel 64658013fe Host the batch 4 IrisApi: api and host artifacts, ModuleLoadException
- Depend on com.volmit:iris-api and com.volmit:iris-host; the probe
  compiles against the api only.
- PackModuleSet catches ModuleLoadException.
- ObjectPlacerEdit implements set(x, y, z, state) without a PlacedBlock;
  block entities sit in their own map.
- BlockStateHunk implements width(), height(), depth().
2026-10-24 04:19:42 +02:00

510 lines
21 KiB
Groovy

import io.github.slimjar.resolver.data.Mirror
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
import org.gradle.jvm.toolchain.JavaLanguageVersion
import java.net.URI
import java.nio.charset.StandardCharsets
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2021 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
plugins {
id 'java'
id 'java-library'
alias(libs.plugins.shadow)
alias(libs.plugins.slimjar)
}
def lib = 'art.arcane.iris.util'
String volmLibCoordinate = providers.gradleProperty('volmLibCoordinate')
.orElse('com.github.VolmitSoftware:VolmLib:e6574cf814b3dd670385a4d632a63fde2038e186')
.get()
/**
* Dependencies.
*
* Provided or classpath dependencies are not shaded and are available on the runtime classpath
*
* Shaded dependencies are not available at runtime, nor are they available on mvn central so they
* need to be shaded into the jar (increasing binary size)
*
* Dynamically loaded dependencies are defined in the plugin.yml (updating these must be updated in the
* plugin.yml also, otherwise they wont be available). These do not increase binary size). Only declare
* these dependencies if they are available on mvn central.
*/
dependencies {
api(project(':spi'))
// IrisApi, from the sibling checkout (gradle/irisapi-resolution.settings.gradle). Shaded without
// relocation: pack modules compile against com.volmit and the pack loader exposes that package,
// except the host side (com.volmit.host), which loads and runs them.
implementation('com.volmit:iris-api')
implementation('com.volmit:iris-host')
// Provided or Classpath
compileOnly(libs.lombok)
annotationProcessor(libs.lombok)
compileOnly(libs.paper.api)
compileOnly(libs.log4j.api)
compileOnly(libs.log4j.core)
compileOnly(libs.guava)
// Third Party Integrations
compileOnly(libs.nexo)
compileOnly(libs.itemsadder)
compileOnly(libs.score)
compileOnly(libs.mmoitems)
compileOnly(libs.mythiclib)
compileOnly(libs.eco)
compileOnly(libs.mythic)
compileOnly(libs.mythicCrucible)
compileOnly(libs.kgenerators) {
transitive = false
}
compileOnly(libs.multiverseCore)
compileOnly(libs.craftengine.core)
compileOnly(libs.craftengine.bukkit)
// Shaded
implementation('de.crazydev22.slimjar.helper:spigot:2.1.9')
implementation(volmLibCoordinate) {
transitive = false
}
// Dynamically Loaded
slim(libs.gson)
slim(libs.lru)
slim(libs.caffeine)
slim(libs.paralithic)
slim(libs.paperlib)
slim(libs.adventure.api)
slim(libs.adventure.minimessage)
slim(libs.adventure.serializer.legacy)
slim(libs.adventure.serializer.plain)
slim(libs.bstats)
slim(libs.commons.io)
slim(libs.commons.lang3)
slim(libs.oshi)
slim(libs.lz4)
slim(libs.fastutil)
slim(libs.zip) {
exclude(group: 'org.slf4j', module: 'slf4j-api')
}
slim(libs.asm)
slim(libs.byteBuddy.core)
slim(libs.byteBuddy.agent)
slim(libs.dom4j)
slim(libs.jaxen)
testImplementation('com.volmit:iris-api')
testImplementation('com.volmit:iris-host')
testImplementation('junit:junit:4.13.2')
testImplementation('org.mockito:mockito-core:5.23.0')
testImplementation(libs.paper.api)
testRuntimeOnly(libs.paper.api)
testImplementation(libs.multiverseCore)
}
tasks.named('test').configure {
maxHeapSize = '1g'
systemProperty('iris.packBenchmarkingSource', file('src/main/java/art/arcane/iris/core/tools/IrisPackBenchmarking.java').absolutePath)
systemProperty('iris.irisToolbeltSource', file('src/main/java/art/arcane/iris/core/tools/IrisToolbelt.java').absolutePath)
systemProperty('iris.irisCreatorSource', file('src/main/java/art/arcane/iris/core/tools/IrisCreator.java').absolutePath)
systemProperty('iris.bukkitChunkGeneratorSource', file('src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath)
systemProperty('iris.builtinModulesList', rootProject.file('../IrisModule/builtin-modules.txt').absolutePath)
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
slimJar {
mirrors = [
new Mirror(
URI.create('https://maven-central.storage-download.googleapis.com/maven2').toURL(),
URI.create('https://repo.maven.apache.org/maven2/').toURL()
)
]
relocate('com.dfsek.paralithic', "${lib}.paralithic")
relocate('com.google.gson', "${lib}.gson")
relocate('com.googlecode.concurrentlinkedhashmap', "${lib}.lru")
relocate('io.papermc.lib', "${lib}.paper")
relocate('net.kyori', "${lib}.kyori")
relocate('org.bstats', "${lib}.metrics")
relocate('org.apache.maven', "${lib}.maven")
relocate('org.codehaus.plexus', "${lib}.plexus")
relocate('org.eclipse.sisu', "${lib}.sisu")
relocate('org.eclipse.aether', "${lib}.aether")
relocate('com.google.inject', "${lib}.guice")
relocate('org.dom4j', "${lib}.dom4j")
relocate('org.jaxen', "${lib}.jaxen")
relocate('com.github.benmanes.caffeine', "${lib}.caffeine")
}
def embeddedAgentJar = project(':core:agent').tasks.named('jar', Jar)
def templateSource = file('src/main/templates')
def templateDest = layout.buildDirectory.dir('generated/sources/templates')
def generateTemplates = tasks.register('generateTemplates', Copy) {
inputs.properties([
environment: providers.provider {
if (project.hasProperty('release')) {
return 'production'
}
if (project.hasProperty('argghh')) {
return 'Argghh!'
}
return 'development'
},
commit: providers.provider {
String commitId = null
Exception failure = null
try {
Process process = new ProcessBuilder('git', '-C', rootProject.projectDir.absolutePath, 'rev-parse', 'HEAD')
.redirectErrorStream(true)
.start()
String output = new String(process.inputStream.readAllBytes(), StandardCharsets.UTF_8).trim()
int exitCode = process.waitFor()
if (exitCode == 0) {
commitId = output
} else {
failure = new GradleException("git rev-parse exited with code ${exitCode}: ${output}")
}
} catch (Exception ex) {
failure = ex
}
if (commitId != null && commitId.length() == 40) {
return commitId
}
logger.error('Git commit hash not found', failure)
return 'unknown'
},
minecraftVersion: providers.gradleProperty('minecraftVersion'),
])
from(templateSource)
into(templateDest)
rename { String fileName -> "art/arcane/iris/${fileName}" }
expand(inputs.properties)
}
tasks.named('compileJava', JavaCompile).configure {
/**
* We need parameter meta for the decree command system
*/
options.compilerArgs.add('-parameters')
options.compilerArgs.addAll(['--add-modules', 'jdk.incubator.vector'])
options.encoding = 'UTF-8'
options.debugOptions.debugLevel = 'none'
// lombok.config decides how equals/hashCode/toString are generated (fields, never getters), so editing it
// changes this module's bytecode. Gradle does not know that on its own and would serve a stale up-to-date
// build until something else in the module changed.
inputs.file(rootProject.file('lombok.config'))
.withPropertyName('lombokConfig')
.withPathSensitivity(PathSensitivity.NONE)
}
tasks.named('test', Test).configure {
jvmArgs('--add-modules', 'jdk.incubator.vector')
classpath = files('src/main/resources') + classpath
}
configurations.matching { it.name.startsWith('slim') }.all { }
List<String> requestedTasks = gradle.startParameter.taskNames
boolean runningOnlyTestTasks = !requestedTasks.isEmpty()
&& requestedTasks.every { String taskName -> taskName.toLowerCase().contains('test') }
if (runningOnlyTestTasks) {
TaskProvider<Task> processResourcesTask = tasks.named('processResources')
tasks.named('classes').configure { Task classesTask ->
Set<Object> dependencies = new LinkedHashSet<Object>(classesTask.getDependsOn())
dependencies.removeIf { Object dependency ->
if (dependency instanceof TaskProvider) {
return ((TaskProvider<?>) dependency).name == processResourcesTask.name
}
if (dependency instanceof Task) {
return ((Task) dependency).name == processResourcesTask.name
}
String dependencyName = String.valueOf(dependency)
return dependencyName == 'processResources' || dependencyName.endsWith(':processResources')
}
classesTask.setDependsOn(dependencies)
}
processResourcesTask.configure { Task task ->
task.enabled = false
}
}
// Iris's own packages and classes the Bukkit jar leaves out: nothing shipped in the jar reaches them (the list's
// package-granularity reasoning is in the header of volmlib-left-out-of-bukkit-jar.txt). verifyBukkitArtifact re-derives
// the reference graph over the shipped jar and fails on any dangling reference, so an exclude that stops being dead is a
// build failure rather than a runtime crash.
List<String> irisPackagesLeftOut = [
'art/arcane/iris/core/report/**',
'art/arcane/iris/util/common/inventorygui/**',
'art/arcane/iris/util/common/board/**'
]
List<String> irisClassesLeftOut = [
'art/arcane/iris/core/pack/IrisPack',
'art/arcane/iris/core/pack/IrisPackRepository',
'art/arcane/iris/core/jobs/DownloadJob',
'art/arcane/iris/core/jobs/JobCollection',
'art/arcane/iris/core/jobs/ParallelQueueJob',
'art/arcane/iris/core/jobs/QueueJob',
'art/arcane/iris/engine/framework/placer/WorldObjectPlacer',
'art/arcane/iris/engine/object/placement/IPostBlockAccess',
'art/arcane/iris/engine/object/entity/IrisPotionEffect',
'art/arcane/iris/engine/platform/DummyChunkGenerator',
'art/arcane/iris/util/common/math/VectorMath',
'art/arcane/iris/util/common/parallel/GridLock',
'art/arcane/iris/util/common/reflect/W',
'art/arcane/iris/util/slimjar/BuildConstants',
'art/arcane/iris/util/slimjar/relocation/meta/AttributeMetaMediator',
'art/arcane/iris/util/slimjar/relocation/meta/AttributeMetaMediatorFactory'
]
// The VolmLib classes the jar leaves out are listed in a file the built-in modules jar check reads too (IrisModule), so a
// module cannot use a VolmLib class that is stripped from here. Format: see the file's header.
File volmLibLeftOutFile = file('volmlib-left-out-of-bukkit-jar.txt')
List<String> volmLibLeftOutEntries = volmLibLeftOutFile.readLines()
.collect { String line -> line.contains('#') ? line.substring(0, line.indexOf('#')).trim() : line.trim() }
.findAll { String line -> !line.isEmpty() }
.collectMany { String entry ->
entry.endsWith('.class') || entry.contains('*') ? [entry] : [entry + '.class', entry + '$*.class']
}
List<String> irisClassesLeftOutEntries = irisClassesLeftOut.collectMany { String classPath ->
[classPath + '.class', classPath + '$*.class']
}
// Annotation-only artifacts pulled in transitively by Gson and Caffeine. Their types appear solely
// in annotation attributes, which the JVM skips silently when the type is absent, so nothing loads
// or links against them at runtime.
List<String> annotationOnlyArtifacts = [
'com/google/errorprone/**',
'org/jspecify/**'
]
// Publisher metadata for the shaded dependencies. Nothing reads these at runtime.
List<String> dependencyBuildMetadata = [
'META-INF/maven/**',
'META-INF/proguard/**',
'META-INF/versions/*/OSGI-INF/**'
]
// The built-in modules as a pack module jar, iris-builtins.jar, packaged from these compiled classes so it always fits this
// build of Iris, checked as a pack load would check it, and bundled into the plugin (IrisModuleHost loads it with every pack).
// What goes in is listed in IrisModule/builtin-modules.txt: "module <class>" (an entry point) or "include <ant pattern>".
String builtinModulesJarName = 'iris-builtins.jar'
String builtinModuleEntryFile = 'com.volmit.IrisModule'
File builtinModulesFile = rootProject.file('../IrisModule/builtin-modules.txt')
// The packages pack modules may use besides the IrisApi; IrisModuleHost.EXPOSED_PACKAGES lists the same.
List<String> builtinExposedPackages = ['art.arcane.iris.builtin', 'art.arcane.volmlib', 'com.google.gson']
List<String> builtinModuleClasses = []
List<String> builtinClassPatterns = []
builtinModulesFile.readLines()
.collect { String line -> line.contains('#') ? line.substring(0, line.indexOf('#')).trim() : line.trim() }
.findAll { String line -> !line.isEmpty() }
.each { String line ->
List<String> parts = line.split(/\s+/, 2) as List<String>
if (parts.size() < 2 || parts[1].isBlank()) {
throw new GradleException("${builtinModulesFile.name}: '${line}' needs a value after '${parts[0]}'")
}
if (parts[0] == 'module') {
builtinModuleClasses.add(parts[1].trim())
} else if (parts[0] == 'include') {
builtinClassPatterns.add(parts[1].trim())
} else {
throw new GradleException("${builtinModulesFile.name}: unknown line '${line}'; start it with 'module' or 'include'")
}
}
List<String> builtinPackagedPatterns = builtinModuleClasses.collectMany { String moduleClass ->
String path = moduleClass.replace('.', '/')
[path + '.class', path + '$*.class']
} + builtinClassPatterns
Provider<Directory> builtinModulesBuild = layout.buildDirectory.dir('builtin-modules')
configurations {
// What the jar check sees besides Iris's classes: the IrisApi (its host side included, as in the plugin, where the
// check finds it hidden) and the libraries Iris shares with pack modules.
builtinModulesCheckClasspath {
canBeConsumed = false
transitive = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME))
}
}
}
dependencies {
builtinModulesCheckClasspath('com.volmit:iris-api')
builtinModulesCheckClasspath('com.volmit:iris-host')
builtinModulesCheckClasspath(volmLibCoordinate)
builtinModulesCheckClasspath(libs.gson)
}
def writeBuiltinModuleEntries = tasks.register('writeBuiltinModuleEntries') {
description = "Writes the built-ins jar's META-INF/services/${builtinModuleEntryFile}, one module class per line."
Provider<RegularFile> entries = builtinModulesBuild.map { it.file("services/${builtinModuleEntryFile}") }
inputs.file(builtinModulesFile)
outputs.file(entries)
doLast {
File entriesFile = entries.get().asFile
entriesFile.parentFile.mkdirs()
entriesFile.text = builtinModuleClasses.join('\n') + '\n'
}
}
def packageBuiltinModules = tasks.register('packageBuiltinModules', Jar) {
description = 'Packages the listed built-in modules and classes before they are checked.'
archiveFileName.set(builtinModulesJarName)
destinationDirectory.set(builtinModulesBuild.map { it.dir('unchecked') })
inputs.file(builtinModulesFile)
from(sourceSets.main.java.classesDirectory) {
include(builtinPackagedPatterns)
}
from(writeBuiltinModuleEntries) {
into('META-INF/services')
}
}
def builtinModulesJar = tasks.register('builtinModulesJar', JavaExec) {
group = 'build'
description = "Builds build/builtin-modules/${builtinModulesJarName}, the built-in modules as a pack module jar, checked with" +
" IrisApi's pack class and reference checks as a pack load would."
dependsOn(packageBuiltinModules)
Provider<RegularFile> unchecked = packageBuiltinModules.flatMap { it.archiveFile }
Provider<RegularFile> checked = builtinModulesBuild.map { it.file(builtinModulesJarName) }
classpath = configurations.builtinModulesCheckClasspath + files(sourceSets.main.java.classesDirectory)
mainClass.set('com.volmit.host.ModuleJarCheck')
inputs.file(unchecked)
inputs.file(volmLibLeftOutFile)
outputs.file(checked)
argumentProviders.add({
[unchecked.get().asFile.absolutePath, "--left-out=${volmLibLeftOutFile.absolutePath}".toString()] + builtinExposedPackages
} as CommandLineArgumentProvider)
ignoreExitValue = true
ByteArrayOutputStream problems = new ByteArrayOutputStream()
errorOutput = problems
doFirst {
// A jar from an earlier run that passed must not survive a run that fails.
checked.get().asFile.delete()
}
doLast {
if (executionResult.get().exitValue != 0) {
throw new GradleException("The built-in modules jar breaks the rules of a pack module jar:\n" + problems.toString().trim() +
"\nFix the classes listed in ${builtinModulesFile.name}, or move what they use into the jar or into art.arcane.iris.builtin.")
}
java.nio.file.Files.copy(unchecked.get().asFile.toPath(), checked.get().asFile.toPath())
}
}
// The jar's classes load from the bundled jar only, in each pack's class loader, so the plugin's own classes leave them out.
tasks.named('jar', Jar).configure {
exclude(builtinPackagedPatterns)
from(builtinModulesJar)
}
tasks.named('shadowJar', com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar).configure {
dependsOn(embeddedAgentJar)
exclude(builtinPackagedPatterns)
from(builtinModulesJar)
mergeServiceFiles()
// minimize() stays off. Caffeine reaches its 520 generated cache and node classes through
// MethodHandles.Lookup.findClass on a computed name, and the VolmLib command, GUI and hotload
// surfaces are only referenced from :adapters:bukkit:plugin, which is merged into the artifact
// after this task runs. Both would be stripped as unreachable. Excluding them from minimization
// leaves it reaching ~25KB of Gson internals, which is not worth a mode that fails silently.
relocate('com.dfsek.paralithic', "${lib}.paralithic")
relocate('io.github.slimjar', "${lib}.slimjar")
exclude('modules/loader-agent.isolated-jar')
exclude(irisPackagesLeftOut)
exclude(irisClassesLeftOutEntries)
exclude(volmLibLeftOutEntries)
exclude(annotationOnlyArtifacts)
exclude(dependencyBuildMetadata)
from(embeddedAgentJar.map { it.archiveFile }) {
rename { String ignored -> 'agent.jar' }
}
}
rootProject.tasks.matching {
it.name == 'prepareKotlinBuildScriptModel'
}.configureEach {
dependsOn(generateTemplates)
}
sourceSets {
main {
java {
srcDir(generateTemplates.map { it.outputs })
}
}
}
apply from: rootProject.file('gradle/default-module.gradle')
tasks.register('bukkitPurityRatchet') {
group = 'verification'
description = 'Checks host and default module Bukkit imports against the existing purity ceiling.'
File allowlistFile = project.file('purity-allowlist.txt')
File sourceRoot = project.file('src/main/java')
File defaultModuleSourceRoot = rootProject.file('../IrisModule/src/main/java')
inputs.file(allowlistFile)
inputs.dir(sourceRoot)
inputs.dir(defaultModuleSourceRoot)
doLast {
Set<String> allowed = allowlistFile.readLines().findAll { String line -> !line.isBlank() }.toSet()
List<String> offenders = new ArrayList<>()
List<String> coupled = new ArrayList<>()
[sourceRoot, defaultModuleSourceRoot].each { File root ->
root.eachFileRecurse { File f ->
if (!f.name.endsWith('.java')) {
return
}
if (f.text.contains('org.bukkit')) {
String rel = root.toPath().relativize(f.toPath()).toString()
coupled.add(rel)
if (!allowed.contains(rel)) {
offenders.add(rootProject.projectDir.toPath().relativize(f.toPath()).toString())
}
}
}
}
if (!offenders.isEmpty()) {
throw new GradleException("Bukkit purity ratchet violated - new org.bukkit coupling in:\n " + offenders.join('\n ') + "\nDecouple these files or (only with strong justification) add them to core/purity-allowlist.txt")
}
int shrunk = allowed.size() - coupled.size()
if (shrunk > 0) {
println("Purity ratchet: " + coupled.size() + " coupled files (" + shrunk + " fewer than allowlist - consider tightening core/purity-allowlist.txt)")
} else {
println("Purity ratchet: " + coupled.size() + " coupled files (at allowlist ceiling)")
}
}
}
tasks.named('check').configure {
dependsOn('bukkitPurityRatchet')
}