reformat all code

This commit is contained in:
dfsek 2022-07-06 19:28:07 -07:00
parent dc5e71e3de
commit b3a8f375bc
111 changed files with 706 additions and 653 deletions

View File

@ -72,15 +72,19 @@
- [ ] Bug Fix <!-- Anything which fixes an issue in Terra. --> - [ ] Bug Fix <!-- Anything which fixes an issue in Terra. -->
- [ ] Build system <!-- Anything which pretain to the build system. --> - [ ] Build system <!-- Anything which pretain to the build system. -->
- [ ] Documentation <!-- Anything which adds or improves documentation for existing features. --> - [ ]
Documentation <!-- Anything which adds or improves documentation for existing features. -->
- [ ] New Feature <!-- Anything which adds new functionality to Terra. --> - [ ] New Feature <!-- Anything which adds new functionality to Terra. -->
- [ ] Performance <!-- Anything which is imrpoves the performance of Terra. --> - [ ] Performance <!-- Anything which is imrpoves the performance of Terra. -->
- [ ] Refactoring <!-- Anything which does not add any new code, only moves code around. --> - [ ]
- [ ] Repository <!-- Anything which affects the repository. Eg. changes to the `README.md` file. --> Refactoring <!-- Anything which does not add any new code, only moves code around. -->
- [ ]
Repository <!-- Anything which affects the repository. Eg. changes to the `README.md` file. -->
- [ ] Revert <!-- Anything which reverts previous commits. --> - [ ] Revert <!-- Anything which reverts previous commits. -->
- [ ] Style <!-- Anything which updates style. --> - [ ] Style <!-- Anything which updates style. -->
- [ ] Tests <!-- Anything which adds or updates tests. --> - [ ] Tests <!-- Anything which adds or updates tests. -->
- [ ] Translation <!-- Anything which is internationalizing the Terra program to other languages. --> - [ ]
Translation <!-- Anything which is internationalizing the Terra program to other languages. -->
#### Compatiblity #### Compatiblity

View File

@ -63,7 +63,8 @@ to [Terra global moderation team](CODE_OF_CONDUCT.md#Reporting).
## I don't want to read this whole thing I just have a question!!! ## I don't want to read this whole thing I just have a question!!!
> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below. > **Note:** Please don't file an issue to ask a question. You'll get faster
> results by using the resources below.
We have an official discord server where you can request help from various users We have an official discord server where you can request help from various users
@ -103,7 +104,9 @@ you don't need to create one. When you are creating a bug report,
please [include as many details as possible](#how-do-i-submit-a-good-bug-report) please [include as many details as possible](#how-do-i-submit-a-good-bug-report)
. .
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. > **Note:** If you find a **Closed** issue that seems like it is the same thing
> that you're experiencing, open a new issue and include a link to the original
> issue in the body of your new one.
#### Before Submitting A Bug Report #### Before Submitting A Bug Report

View File

@ -12,30 +12,30 @@ import kotlin.streams.asStream
*/ */
fun Project.addonDir(dir: File, task: Task) { fun Project.addonDir(dir: File, task: Task) {
val moveAddons = tasks.register("moveAddons" + task.name) { val moveAddons = tasks.register("moveAddons" + task.name) {
dependsOn("compileAddons") dependsOn("compileAddons")
doLast { doLast {
dir.parentFile.mkdirs() dir.parentFile.mkdirs()
matchingAddons(dir) { matchingAddons(dir) {
it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon. it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon.
}.forEach { }.forEach {
println("Deleting old addon: " + it.absolutePath) println("Deleting old addon: " + it.absolutePath)
it.delete() it.delete()
} }
forSubProjects(":common:addons") { forSubProjects(":common:addons") {
val jar = tasks.named("shadowJar").get() as ShadowJar val jar = tasks.named("shadowJar").get() as ShadowJar
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else "" val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val target = File(dir, boot + jar.archiveFileName.get()) val target = File(dir, boot + jar.archiveFileName.get())
val base = "${jar.archiveBaseName.get()}-${version}" val base = "${jar.archiveBaseName.get()}-${version}"
println("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base") println("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base")
jar.archiveFile.orNull?.asFile?.copyTo(target) jar.archiveFile.orNull?.asFile?.copyTo(target)
}
} }
} }
}
task.dependsOn(moveAddons) task.dependsOn(moveAddons)
} }

View File

@ -39,10 +39,10 @@ fun Project.configureDependencies() {
maven("https://papermc.io/repo/repository/maven-public/") { maven("https://papermc.io/repo/repository/maven-public/") {
name = "PaperMC" name = "PaperMC"
} }
maven ( "https://files.minecraftforge.net/maven/" ) { maven("https://files.minecraftforge.net/maven/") {
name = "Forge" name = "Forge"
} }
maven ("https://maven.quiltmc.org/repository/release/") { maven("https://maven.quiltmc.org/repository/release/") {
name = "Quilt" name = "Quilt"
} }
maven("https://jitpack.io") { maven("https://jitpack.io") {

View File

@ -53,7 +53,7 @@ fun Project.configureDistribution() {
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else "" val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val addonPath = fs.getPath("/addons/$boot${jar.archiveFileName.get()}") val addonPath = fs.getPath("/addons/$boot${jar.archiveFileName.get()}")
if (!Files.exists(addonPath)) { if (!Files.exists(addonPath)) {
Files.createDirectories(addonPath.parent) Files.createDirectories(addonPath.parent)
Files.createFile(addonPath) Files.createFile(addonPath)

View File

@ -33,10 +33,10 @@ object Versions {
const val minecraft = "1.19" const val minecraft = "1.19"
const val yarn = "$minecraft+build.1" const val yarn = "$minecraft+build.1"
const val fabricLoader = "0.14.2" const val fabricLoader = "0.14.2"
const val architecuryLoom = "0.12.0-SNAPSHOT" const val architecuryLoom = "0.12.0-SNAPSHOT"
const val architecturyPlugin = "3.4-SNAPSHOT" const val architecturyPlugin = "3.4-SNAPSHOT"
const val loomQuiltflower = "1.7.1" const val loomQuiltflower = "1.7.1"
const val lazyDfu = "0.1.2" const val lazyDfu = "0.1.2"

View File

@ -28,7 +28,7 @@ public class BiomeExtrusionProvider implements BiomeProvider {
@Override @Override
public Biome getBiome(int x, int y, int z, long seed) { public Biome getBiome(int x, int y, int z, long seed) {
Biome delegated = delegate.getBiome(x, y, z, seed); Biome delegated = delegate.getBiome(x, y, z, seed);
return extrude(delegated, x, y, z, seed); return extrude(delegated, x, y, z, seed);
} }
@ -42,8 +42,8 @@ public class BiomeExtrusionProvider implements BiomeProvider {
@Override @Override
public Column<Biome> getColumn(int x, int z, long seed, int min, int max) { public Column<Biome> getColumn(int x, int z, long seed, int min, int max) {
return delegate.getBaseBiome(x, z, seed) return delegate.getBaseBiome(x, z, seed)
.map(base -> (Column<Biome>) new BaseBiomeColumn(this, base, min, max, x, z, seed)) .map(base -> (Column<Biome>) new BaseBiomeColumn(this, base, min, max, x, z, seed))
.orElseGet(() -> BiomeProvider.super.getColumn(x, z, seed, min, max)); .orElseGet(() -> BiomeProvider.super.getColumn(x, z, seed, min, max));
} }
@Override @Override

View File

@ -10,6 +10,14 @@ import com.dfsek.terra.api.world.biome.Biome;
* Basically just a specialised implementation of {@link Optional} for biomes where a biome may be a "self" reference. * Basically just a specialised implementation of {@link Optional} for biomes where a biome may be a "self" reference.
*/ */
public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome { public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome {
static ReplaceableBiome of(Biome biome) {
return new PresentBiome(biome);
}
static ReplaceableBiome self() {
return SelfBiome.INSTANCE;
}
Biome get(Biome existing); Biome get(Biome existing);
default Biome get() { default Biome get() {
@ -20,12 +28,4 @@ public sealed interface ReplaceableBiome permits PresentBiome, SelfBiome {
} }
boolean isSelf(); boolean isSelf();
static ReplaceableBiome of(Biome biome) {
return new PresentBiome(biome);
}
static ReplaceableBiome self() {
return SelfBiome.INSTANCE;
}
} }

View File

@ -81,11 +81,11 @@ public class BiomePipelineProvider implements BiomeProvider {
public Biome getBiome(int x, int z, long seed) { public Biome getBiome(int x, int z, long seed) {
x += mutator.noise(seed + 1, x, z) * noiseAmp; x += mutator.noise(seed + 1, x, z) * noiseAmp;
z += mutator.noise(seed + 2, x, z) * noiseAmp; z += mutator.noise(seed + 2, x, z) * noiseAmp;
x /= resolution; x /= resolution;
z /= resolution; z /= resolution;
int fdX = FastMath.floorDiv(x, pipeline.getSize()); int fdX = FastMath.floorDiv(x, pipeline.getSize());
int fdZ = FastMath.floorDiv(z, pipeline.getSize()); int fdZ = FastMath.floorDiv(z, pipeline.getSize());
return holderCache.get(new SeededVector(fdX, fdZ, seed)).getBiome(x - fdX * pipeline.getSize(), return holderCache.get(new SeededVector(fdX, fdZ, seed)).getBiome(x - fdX * pipeline.getSize(),
@ -120,7 +120,7 @@ public class BiomePipelineProvider implements BiomeProvider {
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int code = x; int code = x;

View File

@ -22,7 +22,7 @@ public abstract class BiomeProviderTemplate implements ObjectTemplate<BiomeProvi
@Default @Default
@Description(""" @Description("""
The resolution at which to sample biomes. The resolution at which to sample biomes.
Larger values are quadratically faster, but produce lower quality results. Larger values are quadratically faster, but produce lower quality results.
For example, a value of 3 would sample every 3 blocks.""") For example, a value of 3 would sample every 3 blocks.""")
protected @Meta int resolution = 1; protected @Meta int resolution = 1;

View File

@ -16,14 +16,12 @@ import com.dfsek.terra.api.world.biome.Biome;
public class BiomeQueryAPIAddon implements AddonInitializer { public class BiomeQueryAPIAddon implements AddonInitializer {
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Inject @Inject
private Platform platform; private Platform platform;
@Inject @Inject
private BaseAddon addon; private BaseAddon addon;
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Override @Override
public void initialize() { public void initialize() {

View File

@ -8,7 +8,7 @@ import com.dfsek.terra.api.world.biome.Biome;
public final class BiomeQueries { public final class BiomeQueries {
private BiomeQueries() { private BiomeQueries() {
} }
public static Predicate<Biome> has(String tag) { public static Predicate<Biome> has(String tag) {

View File

@ -7,8 +7,8 @@ import com.dfsek.terra.api.world.biome.Biome;
public class SingleTagQuery implements Predicate<Biome> { public class SingleTagQuery implements Predicate<Biome> {
private int tagIndex = -1;
private final String tag; private final String tag;
private int tagIndex = -1;
public SingleTagQuery(String tag) { public SingleTagQuery(String tag) {
this.tag = tag; this.tag = tag;

View File

@ -49,9 +49,9 @@ public class NoiseChunkGenerator3DAddon implements AddonInitializer {
.getOrCreateRegistry(ChunkGeneratorProvider.class) .getOrCreateRegistry(ChunkGeneratorProvider.class)
.register(addon.key("NOISE_3D"), .register(addon.key("NOISE_3D"),
pack -> new NoiseChunkGenerator3D(pack, platform, config.getElevationBlend(), pack -> new NoiseChunkGenerator3D(pack, platform, config.getElevationBlend(),
config.getHorizontalRes(), config.getHorizontalRes(),
config.getVerticalRes(), noisePropertiesPropertyKey, config.getVerticalRes(), noisePropertiesPropertyKey,
paletteInfoPropertyKey)); paletteInfoPropertyKey));
event.getPack() event.getPack()
.applyLoader(SlantLayer.class, SlantLayer::new); .applyLoader(SlantLayer.class, SlantLayer::new);
}) })
@ -62,8 +62,10 @@ public class NoiseChunkGenerator3DAddon implements AddonInitializer {
.register(addon, ConfigurationLoadEvent.class) .register(addon, ConfigurationLoadEvent.class)
.then(event -> { .then(event -> {
if(event.is(Biome.class)) { if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey, event.load(new BiomePaletteTemplate(platform)).get()); event.getLoadedObject(Biome.class).getContext().put(paletteInfoPropertyKey,
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey, event.load(new BiomeNoiseConfigTemplate()).get()); event.load(new BiomePaletteTemplate(platform)).get());
event.getLoadedObject(Biome.class).getContext().put(noisePropertiesPropertyKey,
event.load(new BiomeNoiseConfigTemplate()).get());
} }
}) })
.failThrough(); .failThrough();

View File

@ -12,7 +12,7 @@ public class ThreadLocalNoiseHolder {
if(holder.init && holder.y == y && holder.z == z && holder.x == x && holder.seed == seed) { if(holder.init && holder.y == y && holder.z == z && holder.x == x && holder.seed == seed) {
return holder.noise; return holder.noise;
} }
double noise = sampler.noise(seed, x, y, z); double noise = sampler.noise(seed, x, y, z);
holder.noise = noise; holder.noise = noise;
holder.x = x; holder.x = x;

View File

@ -83,6 +83,7 @@ public class BiomePaletteTemplate implements ObjectTemplate<PaletteInfo> {
slantLayers.put(threshold, layer.getPalette()); slantLayers.put(threshold, layer.getPalette());
} }
return new PaletteInfo(builder.build(), SlantHolder.of(slantLayers, minThreshold), oceanPalette, seaLevel, slantDepth, updatePalette); return new PaletteInfo(builder.build(), SlantHolder.of(slantLayers, minThreshold), oceanPalette, seaLevel, slantDepth,
updatePalette);
} }
} }

View File

@ -87,10 +87,10 @@ public class ChunkInterpolator {
for(int zi = -blend; zi <= blend; zi++) { for(int zi = -blend; zi <= blend; zi++) {
int blendX = (xi * step); int blendX = (xi * step);
int blendZ = (zi * step); int blendZ = (zi * step);
int localIndex = (scaledX + maxBlend + blendX) + maxBlendAndChunk * (scaledZ + maxBlend + blendZ); int localIndex = (scaledX + maxBlend + blendX) + maxBlendAndChunk * (scaledZ + maxBlend + blendZ);
Column<Biome> column = columns[localIndex]; Column<Biome> column = columns[localIndex];
if(column == null) { if(column == null) {
column = provider.getColumn(absoluteX + blendX, absoluteZ + blendZ, seed, min, max); column = provider.getColumn(absoluteX + blendX, absoluteZ + blendZ, seed, min, max);
columns[localIndex] = column; columns[localIndex] = column;

View File

@ -25,6 +25,7 @@ public class LazilyEvaluatedInterpolator {
private final int min, max; private final int min, max;
private final int zMul, yMul; private final int zMul, yMul;
public LazilyEvaluatedInterpolator(BiomeProvider biomeProvider, int cx, int cz, int max, public LazilyEvaluatedInterpolator(BiomeProvider biomeProvider, int cx, int cz, int max,
PropertyKey<BiomeNoiseProperties> noisePropertiesKey, int min, int horizontalRes, int verticalRes, PropertyKey<BiomeNoiseProperties> noisePropertiesKey, int min, int horizontalRes, int verticalRes,
long seed) { long seed) {

View File

@ -53,7 +53,7 @@ public class SamplerProvider {
public Sampler3D getChunk(int cx, int cz, WorldProperties world, BiomeProvider provider) { public Sampler3D getChunk(int cx, int cz, WorldProperties world, BiomeProvider provider) {
WorldContext context = new WorldContext(cx, cz, world.getSeed(), world.getMinHeight(), world.getMaxHeight()); WorldContext context = new WorldContext(cx, cz, world.getSeed(), world.getMinHeight(), world.getMaxHeight());
return cache.get(context, c -> new Sampler3D(c.cx, c.cz, c.seed, c.minHeight, c.maxHeight, provider, return cache.get(context, c -> new Sampler3D(c.cx, c.cz, c.seed, c.minHeight, c.maxHeight, provider,
elevationSmooth, noisePropertiesKey, maxBlend)); elevationSmooth, noisePropertiesKey, maxBlend));
} }
private record WorldContext(int cx, int cz, long seed, int minHeight, int maxHeight) { private record WorldContext(int cx, int cz, long seed, int minHeight, int maxHeight) {

View File

@ -23,6 +23,19 @@ public class SamplerLocator implements Locator {
this.samplers = samplers; this.samplers = samplers;
} }
private static int floorToInt(double value) {
int valueInt = (int) value;
if(value < 0.0) {
if(value == (double) valueInt) {
return valueInt;
} else {
return valueInt == Integer.MIN_VALUE ? valueInt : valueInt - 1;
}
} else {
return valueInt;
}
}
@Override @Override
public BinaryColumn getSuitableCoordinates(Column<?> column) { public BinaryColumn getSuitableCoordinates(Column<?> column) {
BinaryColumnBuilder results = column.newBinaryColumn(); BinaryColumnBuilder results = column.newBinaryColumn();
@ -36,17 +49,4 @@ public class SamplerLocator implements Locator {
return results.build(); return results.build();
} }
private static int floorToInt(double value) {
int valueInt = (int)value;
if (value < 0.0) {
if (value == (double)valueInt) {
return valueInt;
} else {
return valueInt == Integer.MIN_VALUE ? valueInt : valueInt - 1;
}
} else {
return valueInt;
}
}
} }

View File

@ -23,11 +23,10 @@ import com.dfsek.terra.addons.noise.config.templates.FunctionTemplate;
public class UserDefinedFunction implements DynamicFunction { public class UserDefinedFunction implements DynamicFunction {
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
private final Expression expression; private final Expression expression;
private final int args; private final int args;
private static final Map<FunctionTemplate, UserDefinedFunction> CACHE = new HashMap<>();
protected UserDefinedFunction(Expression expression, int args) { protected UserDefinedFunction(Expression expression, int args) {
this.expression = expression; this.expression = expression;
this.args = args; this.args = args;
@ -38,17 +37,17 @@ public class UserDefinedFunction implements DynamicFunction {
if(function == null) { if(function == null) {
Parser parser = new Parser(); Parser parser = new Parser();
Scope parent = new Scope(); Scope parent = new Scope();
Scope functionScope = new Scope().withParent(parent); Scope functionScope = new Scope().withParent(parent);
template.getArgs().forEach(functionScope::addInvocationVariable); template.getArgs().forEach(functionScope::addInvocationVariable);
for(Entry<String, FunctionTemplate> entry : template.getFunctions().entrySet()) { for(Entry<String, FunctionTemplate> entry : template.getFunctions().entrySet()) {
String id = entry.getKey(); String id = entry.getKey();
FunctionTemplate nest = entry.getValue(); FunctionTemplate nest = entry.getValue();
parser.registerFunction(id, newInstance(nest)); parser.registerFunction(id, newInstance(nest));
} }
function = new UserDefinedFunction(parser.parse(template.getFunction(), functionScope), template.getArgs().size()); function = new UserDefinedFunction(parser.parse(template.getFunction(), functionScope), template.getArgs().size());
CACHE.put(template, function); CACHE.put(template, function);
} }

View File

@ -338,9 +338,9 @@ public class Parser {
Returnable<?> value = parseExpression(tokens, true, scopeBuilder); Returnable<?> value = parseExpression(tokens, true, scopeBuilder);
ParserUtil.checkReturnType(value, returnType); ParserUtil.checkReturnType(value, returnType);
String id = identifier.getContent(); String id = identifier.getContent();
return switch(value.returnType()) { return switch(value.returnType()) {
case NUMBER -> new NumAssignmentNode((Returnable<Number>) value, identifier.getPosition(), scopeBuilder.num(id)); case NUMBER -> new NumAssignmentNode((Returnable<Number>) value, identifier.getPosition(), scopeBuilder.num(id));
case STRING -> new StrAssignmentNode((Returnable<String>) value, identifier.getPosition(), scopeBuilder.str(id)); case STRING -> new StrAssignmentNode((Returnable<String>) value, identifier.getPosition(), scopeBuilder.str(id));

View File

@ -46,9 +46,8 @@ public class Scope {
} }
public static final class ScopeBuilder { public static final class ScopeBuilder {
private int numSize, boolSize, strSize = 0;
private final Map<String, Pair<Integer, ReturnType>> indices; private final Map<String, Pair<Integer, ReturnType>> indices;
private int numSize, boolSize, strSize = 0;
private ScopeBuilder parent; private ScopeBuilder parent;
public ScopeBuilder() { public ScopeBuilder() {
@ -77,6 +76,7 @@ public class Scope {
} }
return id; return id;
} }
public int num(String id) { public int num(String id) {
int num = numSize; int num = numSize;
indices.put(check(id), Pair.of(num, ReturnType.NUMBER)); indices.put(check(id), Pair.of(num, ReturnType.NUMBER));
@ -107,14 +107,14 @@ public class Scope {
parent.updateBoolSize(size); parent.updateBoolSize(size);
} }
} }
private void updateNumSize(int size) { private void updateNumSize(int size) {
this.numSize = FastMath.max(numSize, size); this.numSize = FastMath.max(numSize, size);
if(parent != null) { if(parent != null) {
parent.updateNumSize(size); parent.updateNumSize(size);
} }
} }
private void updateStrSize(int size) { private void updateStrSize(int size) {
this.strSize = FastMath.max(strSize, size); this.strSize = FastMath.max(strSize, size);
if(parent != null) { if(parent != null) {

View File

@ -14,6 +14,7 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class BooleanConstant extends ConstantExpression<Boolean> { public class BooleanConstant extends ConstantExpression<Boolean> {
private final boolean constant; private final boolean constant;
public BooleanConstant(Boolean constant, Position position) { public BooleanConstant(Boolean constant, Position position) {
super(constant, position); super(constant, position);
this.constant = constant; this.constant = constant;

View File

@ -15,6 +15,7 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class NumericConstant extends ConstantExpression<Number> { public class NumericConstant extends ConstantExpression<Number> {
private final double constant; private final double constant;
public NumericConstant(Number constant, Position position) { public NumericConstant(Number constant, Position position) {
super(constant, position); super(constant, position);
this.constant = constant.doubleValue(); this.constant = constant.doubleValue();

View File

@ -14,6 +14,23 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public interface Function<T> extends Returnable<T> { public interface Function<T> extends Returnable<T> {
Function<?> NULL = new Function<>() {
@Override
public ReturnType returnType() {
return null;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return null;
}
@Override
public Position getPosition() {
return null;
}
};
@Override @Override
default double applyDouble(ImplementationArguments implementationArguments, Scope scope) { default double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return ((Number) apply(implementationArguments, scope)).doubleValue(); return ((Number) apply(implementationArguments, scope)).doubleValue();
@ -23,21 +40,4 @@ public interface Function<T> extends Returnable<T> {
default boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { default boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return (Boolean) apply(implementationArguments, scope); return (Boolean) apply(implementationArguments, scope);
} }
Function<?> NULL = new Function<>() {
@Override
public ReturnType returnType() {
return null;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return null;
}
@Override
public Position getPosition() {
return null;
}
};
} }

View File

@ -27,6 +27,7 @@ public class BooleanOrOperation extends BinaryOperation<Boolean, Boolean> {
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyBoolean(implementationArguments, scope) || right.applyBoolean(implementationArguments, scope); return left.applyBoolean(implementationArguments, scope) || right.applyBoolean(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.BOOLEAN; return ReturnType.BOOLEAN;

View File

@ -18,16 +18,6 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
super(left, right, position); super(left, right, position);
} }
@Override
public Returnable.ReturnType returnType() {
return Returnable.ReturnType.STRING;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return toString(left.apply(implementationArguments, scope)) + toString(right.apply(implementationArguments, scope));
}
private static String toString(Object object) { private static String toString(Object object) {
String s = object.toString(); String s = object.toString();
if(object instanceof Double) { if(object instanceof Double) {
@ -38,4 +28,14 @@ public class ConcatenationOperation extends BinaryOperation<Object, Object> {
} }
return s; return s;
} }
@Override
public Returnable.ReturnType returnType() {
return Returnable.ReturnType.STRING;
}
@Override
public Object apply(ImplementationArguments implementationArguments, Scope scope) {
return toString(left.apply(implementationArguments, scope)) + toString(right.apply(implementationArguments, scope));
}
} }

View File

@ -27,6 +27,7 @@ public class ModuloOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) % right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) % right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@ -27,6 +27,7 @@ public class MultiplicationOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) * right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) * right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@ -27,6 +27,7 @@ public class NumberAdditionOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) + right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) + right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@ -27,6 +27,7 @@ public class SubtractionOperation extends BinaryOperation<Number, Number> {
public double applyDouble(ImplementationArguments implementationArguments, Scope scope) { public double applyDouble(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) - right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) - right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public ReturnType returnType() { public ReturnType returnType() {
return ReturnType.NUMBER; return ReturnType.NUMBER;

View File

@ -42,7 +42,7 @@ public class EqualsStatement extends BinaryOperation<Object, Boolean> {
if(leftValue instanceof Number l && rightValue instanceof Number r) { if(leftValue instanceof Number l && rightValue instanceof Number r) {
return FastMath.abs(l.doubleValue() - r.doubleValue()) <= EPSILON; return FastMath.abs(l.doubleValue() - r.doubleValue()) <= EPSILON;
} }
return leftValue.equals(rightValue); return leftValue.equals(rightValue);
} }
} }

View File

@ -29,6 +29,7 @@ public class LessThanOrEqualsStatement extends BinaryOperation<Number, Boolean>
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) <= right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) <= right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public Returnable.ReturnType returnType() { public Returnable.ReturnType returnType() {
return Returnable.ReturnType.BOOLEAN; return Returnable.ReturnType.BOOLEAN;

View File

@ -29,6 +29,7 @@ public class LessThanStatement extends BinaryOperation<Number, Boolean> {
public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) { public boolean applyBoolean(ImplementationArguments implementationArguments, Scope scope) {
return left.applyDouble(implementationArguments, scope) < right.applyDouble(implementationArguments, scope); return left.applyDouble(implementationArguments, scope) < right.applyDouble(implementationArguments, scope);
} }
@Override @Override
public Returnable.ReturnType returnType() { public Returnable.ReturnType returnType() {
return Returnable.ReturnType.BOOLEAN; return Returnable.ReturnType.BOOLEAN;

View File

@ -14,9 +14,8 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public abstract class VariableAssignmentNode<T> implements Item<T> { public abstract class VariableAssignmentNode<T> implements Item<T> {
protected final Returnable<T> value; protected final Returnable<T> value;
private final Position position;
protected final int index; protected final int index;
private final Position position;
public VariableAssignmentNode(Returnable<T> value, Position position, int index) { public VariableAssignmentNode(Returnable<T> value, Position position, int index) {

View File

@ -12,9 +12,9 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public abstract class VariableReferenceNode<T> implements Returnable<T> { public abstract class VariableReferenceNode<T> implements Returnable<T> {
protected final int index;
private final Position position; private final Position position;
private final ReturnType type; private final ReturnType type;
protected final int index;
public VariableReferenceNode(Position position, ReturnType type, int index) { public VariableReferenceNode(Position position, ReturnType type, int index) {
this.position = position; this.position = position;

View File

@ -30,7 +30,8 @@ import com.dfsek.terra.addons.terrascript.tokenizer.Position;
public class ParserTest { public class ParserTest {
@Test @Test
public void parse() throws IOException, ParseException { public void parse() throws IOException, ParseException {
Parser parser = new Parser(IOUtils.toString(Objects.requireNonNull(getClass().getResourceAsStream("/test.tesf")), Charset.defaultCharset())); Parser parser = new Parser(
IOUtils.toString(Objects.requireNonNull(getClass().getResourceAsStream("/test.tesf")), Charset.defaultCharset()));
parser.registerFunction("test", new FunctionBuilder<Test1>() { parser.registerFunction("test", new FunctionBuilder<Test1>() {
@Override @Override

View File

@ -14,10 +14,15 @@ import java.util.concurrent.atomic.AtomicReference;
public class Context { public class Context {
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
private static final AtomicInteger size = new AtomicInteger(0); private static final AtomicInteger size = new AtomicInteger(0);
private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>(); private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>();
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Properties> T get(Class<T> clazz) { public <T extends Properties> T get(Class<T> clazz) {
@ -33,11 +38,6 @@ public class Context {
return this; return this;
} }
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
public <T extends Properties> Context put(PropertyKey<T> key, T properties) { public <T extends Properties> Context put(PropertyKey<T> key, T properties) {
list.updateAndGet(p -> { list.updateAndGet(p -> {
if(p.length == size.get()) return p; if(p.length == size.get()) return p;

View File

@ -7,7 +7,7 @@ import com.dfsek.terra.api.util.vector.Vector3Int;
public final class GeometryUtil { public final class GeometryUtil {
private GeometryUtil() { private GeometryUtil() {
} }
public static void sphere(Vector3Int origin, int radius, Consumer<Vector3Int> action) { public static void sphere(Vector3Int origin, int radius, Consumer<Vector3Int> action) {

View File

@ -22,6 +22,11 @@ public final class Pair<L, R> {
private final L left; private final L left;
private final R right; private final R right;
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
public static <L, R, T> Function<Pair<L, R>, Pair<T, R>> mapLeft(Function<L, T> function) { public static <L, R, T> Function<Pair<L, R>, Pair<T, R>> mapLeft(Function<L, T> function) {
return pair -> of(function.apply(pair.left), pair.right); return pair -> of(function.apply(pair.left), pair.right);
} }
@ -54,11 +59,6 @@ public final class Pair<L, R> {
return pair -> pair.left; return pair -> pair.left;
} }
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
@Contract("_, _ -> new") @Contract("_, _ -> new")
public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) { public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) {
return new Pair<>(left, right); return new Pair<>(left, right);
@ -96,55 +96,6 @@ public final class Pair<L, R> {
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right); return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
} }
public static class Mutable<L, R> {
private L left;
private R right;
private Mutable(L left, R right) {
this.left = left;
this.right = right;
}
@NotNull
@Contract("_, _ -> new")
public static <L1, R1> Pair.Mutable<L1, R1> of(L1 left, R1 right) {
return new Mutable<>(left, right);
}
@Contract("-> new")
public Pair<L, R> immutable() {
return Pair.of(left, right);
}
public L getLeft() {
return left;
}
public void setLeft(L left) {
this.left = left;
}
public R getRight() {
return right;
}
public void setRight(R right) {
this.right = right;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Mutable<?, ?> that)) return false;
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
}
}
public Pair<L, R> apply(BiConsumer<L, R> consumer) { public Pair<L, R> apply(BiConsumer<L, R> consumer) {
consumer.accept(this.left, this.right); consumer.accept(this.left, this.right);
return this; return this;
@ -154,4 +105,54 @@ public final class Pair<L, R> {
public String toString() { public String toString() {
return String.format("{%s,%s}", left, right); return String.format("{%s,%s}", left, right);
} }
public static class Mutable<L, R> {
private L left;
private R right;
private Mutable(L left, R right) {
this.left = left;
this.right = right;
}
@NotNull
@Contract("_, _ -> new")
public static <L1, R1> Pair.Mutable<L1, R1> of(L1 left, R1 right) {
return new Mutable<>(left, right);
}
@Contract("-> new")
public Pair<L, R> immutable() {
return Pair.of(left, right);
}
public L getLeft() {
return left;
}
public void setLeft(L left) {
this.left = left;
}
public R getRight() {
return right;
}
public void setRight(R right) {
this.right = right;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Mutable<?, ?> that)) return false;
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
}
}
} }

View File

@ -97,7 +97,7 @@ public interface BiomeProvider {
} }
return new CachingBiomeProvider(this); return new CachingBiomeProvider(this);
} }
default int resolution() { default int resolution() {
return 1; return 1;

View File

@ -30,12 +30,12 @@ public class CachingBiomeProvider implements BiomeProvider, Handle {
.initialCapacity(98304) .initialCapacity(98304)
.maximumSize(98304) // 1 full chunk (high res) .maximumSize(98304) // 1 full chunk (high res)
.build(vec -> delegate.getBiome(vec.x * res, vec.y * res, vec.z * res, vec.seed)); .build(vec -> delegate.getBiome(vec.x * res, vec.y * res, vec.z * res, vec.seed));
this.baseCache = Caffeine this.baseCache = Caffeine
.newBuilder() .newBuilder()
.maximumSize(256) // 1 full chunk (high res) .maximumSize(256) // 1 full chunk (high res)
.build(vec -> delegate.getBaseBiome(vec.x * res, vec.z * res, vec.seed)); .build(vec -> delegate.getBaseBiome(vec.x * res, vec.z * res, vec.seed));
} }
@Override @Override
@ -80,6 +80,8 @@ public class CachingBiomeProvider implements BiomeProvider, Handle {
return 31 * code + ((int) (seed ^ (seed >>> 32))); return 31 * code + ((int) (seed ^ (seed >>> 32)));
} }
} }
private record SeededVector2(int x, int z, long seed) { private record SeededVector2(int x, int z, long seed) {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {

View File

@ -38,7 +38,7 @@ public class Column<T extends WritableWorld> {
this.max = max; this.max = max;
this.min = min; this.min = min;
} }
public int getX() { public int getX() {
return x; return x;

View File

@ -4,9 +4,9 @@ public final class Interceptors {
private static final ReadInterceptor READ_THROUGH = ((x, y, z, world) -> world.getBlockState(x, y, z)); private static final ReadInterceptor READ_THROUGH = ((x, y, z, world) -> world.getBlockState(x, y, z));
private static final WriteInterceptor WRITE_THROUGH = ((x, y, z, block, world, physics) -> world.setBlockState(x, y, z, block, private static final WriteInterceptor WRITE_THROUGH = ((x, y, z, block, world, physics) -> world.setBlockState(x, y, z, block,
physics)); physics));
private Interceptors() { private Interceptors() {
} }
public static ReadInterceptor readThrough() { public static ReadInterceptor readThrough() {

View File

@ -86,17 +86,17 @@ public class ColumnTest {
public int getMaxY() { public int getMaxY() {
return max; return max;
} }
@Override @Override
public int getX() { public int getX() {
return 0; return 0;
} }
@Override @Override
public int getZ() { public int getZ() {
return 0; return 0;
} }
@Override @Override
public T get(int y) { public T get(int y) {
return p.apply(y); return p.apply(y);

View File

@ -231,7 +231,8 @@ public class ConfigPackImpl implements ConfigPack {
ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate(); ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate();
selfLoader.load(packPostTemplate, packManifest); selfLoader.load(packPostTemplate, packManifest);
seededBiomeProvider = template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching() : packPostTemplate.getProviderBuilder(); seededBiomeProvider =
template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching() : packPostTemplate.getProviderBuilder();
checkDeadEntries(); checkDeadEntries();
} }

View File

@ -50,7 +50,7 @@ public class RegistryTest {
test.registerChecked(RegistryKey.parse("test:test"), "bazinga2"); test.registerChecked(RegistryKey.parse("test:test"), "bazinga2");
fail("Shouldn't be able to re-register with #registerChecked!"); fail("Shouldn't be able to re-register with #registerChecked!");
} catch(DuplicateEntryException ignore) { } catch(DuplicateEntryException ignore) {
} }
} }
@ -66,7 +66,7 @@ public class RegistryTest {
test.register(RegistryKey.parse("test:test"), "bazinga2"); test.register(RegistryKey.parse("test:test"), "bazinga2");
fail("Shouldn't be able to re-register in CheckedRegistry!"); fail("Shouldn't be able to re-register in CheckedRegistry!");
} catch(DuplicateEntryException ignore) { } catch(DuplicateEntryException ignore) {
} }
} }
@ -90,7 +90,7 @@ public class RegistryTest {
test.getByID("test"); test.getByID("test");
fail("Shouldn't be able to get with ambiguous ID!"); fail("Shouldn't be able to get with ambiguous ID!");
} catch(IllegalArgumentException ignore) { } catch(IllegalArgumentException ignore) {
} }
} }
} }

View File

@ -84,7 +84,7 @@ public class BootstrapAddonLoader implements BootstrapBaseAddon<BootstrapBaseAdd
Path bootstrapFolder = addonsFolder.resolve("bootstrap"); Path bootstrapFolder = addonsFolder.resolve("bootstrap");
Files.createDirectories(bootstrapFolder); Files.createDirectories(bootstrapFolder);
logger.debug("Loading bootstrap addons from {}", bootstrapFolder); logger.debug("Loading bootstrap addons from {}", bootstrapFolder);
try(Stream<Path> bootstrapAddons = Files.walk(bootstrapFolder, 1, FileVisitOption.FOLLOW_LINKS)) { try(Stream<Path> bootstrapAddons = Files.walk(bootstrapFolder, 1, FileVisitOption.FOLLOW_LINKS)) {
return bootstrapAddons.filter(path -> path.toFile().isFile()) return bootstrapAddons.filter(path -> path.toFile().isFile())
.filter(path -> path.toFile().canRead()) .filter(path -> path.toFile().canRead())
@ -96,6 +96,7 @@ public class BootstrapAddonLoader implements BootstrapBaseAddon<BootstrapBaseAdd
throw new UncheckedIOException(e); throw new UncheckedIOException(e);
} }
} }
@Override @Override
public String getID() { public String getID() {
return "BOOTSTRAP"; return "BOOTSTRAP";

View File

@ -4,7 +4,6 @@ terra.source=https://github.com/PolyhedralDev/Terra
terra.issues=https://github.com/PolyhedralDev/Terra/issues terra.issues=https://github.com/PolyhedralDev/Terra/issues
terra.wiki=https://github.com/PolyhedralDev/Terra/wiki terra.wiki=https://github.com/PolyhedralDev/Terra/wiki
terra.license=MIT terra.license=MIT
# Gradle options # Gradle options
org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC
org.gradle.vfs.watch=true org.gradle.vfs.watch=true

View File

@ -91,7 +91,7 @@ public class TerraBukkitPlugin extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new CommonListener(), this); // Register master event listener Bukkit.getPluginManager().registerEvents(new CommonListener(), this); // Register master event listener
PaperUtil.checkPaper(this); PaperUtil.checkPaper(this);
Initializer.init(platform); Initializer.init(platform);
} }

View File

@ -46,23 +46,7 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
private ChunkGenerator delegate; private ChunkGenerator delegate;
private ConfigPack pack; private ConfigPack pack;
private record SeededVector(int x, int z, WorldProperties worldProperties) {
@Override
public boolean equals(Object obj) {
if(obj instanceof SeededVector that) {
return this.z == that.z && this.x == that.x && this.worldProperties.equals(that.worldProperties);
}
return false;
}
@Override
public int hashCode() {
int code = x;
code = 31 * code + z;
return 31 * code + worldProperties.hashCode();
}
}
public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) { public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) {
this.delegate = delegate; this.delegate = delegate;
this.pack = pack; this.pack = pack;
@ -108,13 +92,12 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public boolean shouldGenerateDecorations() { public boolean shouldGenerateDecorations() {
return true; return true;
} }
@Override @Override
public boolean shouldGenerateMobs() { public boolean shouldGenerateMobs() {
return true; return true;
} }
@Override @Override
public boolean shouldGenerateStructures() { public boolean shouldGenerateStructures() {
return true; return true;
@ -133,4 +116,22 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public ChunkGenerator getHandle() { public ChunkGenerator getHandle() {
return delegate; return delegate;
} }
private record SeededVector(int x, int z, WorldProperties worldProperties) {
@Override
public boolean equals(Object obj) {
if(obj instanceof SeededVector that) {
return this.z == that.z && this.x == that.x && this.worldProperties.equals(that.worldProperties);
}
return false;
}
@Override
public int hashCode() {
int code = x;
code = 31 * code + z;
return 31 * code + worldProperties.hashCode();
}
}
} }

View File

@ -11,8 +11,6 @@ public interface Initializer {
String NMS = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; String NMS = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
String TERRA_PACKAGE = Initializer.class.getPackageName(); String TERRA_PACKAGE = Initializer.class.getPackageName();
void initialize(PlatformImpl plugin);
static void init(PlatformImpl platform) { static void init(PlatformImpl platform) {
Logger logger = LoggerFactory.getLogger(Initializer.class); Logger logger = LoggerFactory.getLogger(Initializer.class);
try { try {
@ -37,4 +35,6 @@ public interface Initializer {
logger.error("This is usually due to running Terra on an unsupported Minecraft version."); logger.error("This is usually due to running Terra on an unsupported Minecraft version.");
} }
} }
void initialize(PlatformImpl plugin);
} }

View File

@ -17,8 +17,6 @@
package com.dfsek.terra.bukkit.world.inventory.meta; package com.dfsek.terra.bukkit.world.inventory.meta;
import org.bukkit.inventory.meta.ItemMeta;
import com.dfsek.terra.api.inventory.item.Damageable; import com.dfsek.terra.api.inventory.item.Damageable;
import com.dfsek.terra.bukkit.world.inventory.BukkitItemMeta; import com.dfsek.terra.bukkit.world.inventory.BukkitItemMeta;

View File

@ -1,8 +1,5 @@
package com.dfsek.terra.bukkit.nms.v1_18_R2; package com.dfsek.terra.bukkit.nms.v1_18_R2;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
@ -23,6 +20,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks { public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSBiomeInjector.class); private static final Logger LOGGER = LoggerFactory.getLogger(NMSBiomeInjector.class);
@ -44,9 +44,11 @@ public class AwfulBukkitHacks {
Biome platform = NMSBiomeInjector.createBiome( Biome platform = NMSBiomeInjector.createBiome(
biome, biome,
biomeRegistry.get(vanillaMinecraftKey) // get biomeRegistry.get(vanillaMinecraftKey) // get
); );
ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, new ResourceLocation("terra", NMSBiomeInjector.createBiomeID(pack, key))); ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, new ResourceLocation("terra",
NMSBiomeInjector.createBiomeID(
pack, key)));
BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform); BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable()); biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@ -73,28 +75,35 @@ public class AwfulBukkitHacks {
terraBiomeMap terraBiomeMap
.forEach((vb, terraBiomes) -> .forEach((vb, terraBiomes) ->
NMSBiomeInjector.getEntry(biomeRegistry, vb) NMSBiomeInjector.getEntry(biomeRegistry, vb)
.ifPresentOrElse( .ifPresentOrElse(
vanilla -> terraBiomes vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb) .forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() + LOGGER.debug(
" (vanilla for " + vanilla.unwrapKey()
terra.unwrapKey().orElseThrow().location() + .orElseThrow()
": " + .location() +
vanilla.tags().toList()); " (vanilla for " +
terra.unwrapKey()
vanilla.tags() .orElseThrow()
.forEach( .location() +
tag -> collect ": " +
.computeIfAbsent(tag, vanilla.tags()
t -> new ArrayList<>()) .toList());
.add(terra));
}, vanilla.tags()
() -> LOGGER.error( .forEach(
"No such biome: {}", tag -> collect
tb))), .computeIfAbsent(
() -> LOGGER.error("No vanilla biome: {}", vb))); tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
biomeRegistry.resetTags(); // clearTags biomeRegistry.resetTags(); // clearTags
biomeRegistry.bindTags(ImmutableMap.copyOf(collect)); // populateTags biomeRegistry.bindTags(ImmutableMap.copyOf(collect)); // populateTags

View File

@ -1,33 +1,17 @@
package com.dfsek.terra.bukkit.nms.v1_18_R2; package com.dfsek.terra.bukkit.nms.v1_18_R2;
import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.BiomeSpecialEffects;
import org.bukkit.NamespacedKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector { public class NMSBiomeInjector {
@ -45,33 +29,32 @@ public class NMSBiomeInjector {
builder.biomeCategory(Reflection.BIOME.getBiomeCategory(vanilla)) builder.biomeCategory(Reflection.BIOME.getBiomeCategory(vanilla))
.precipitation(vanilla.getPrecipitation()) // getPrecipitation .precipitation(vanilla.getPrecipitation()) // getPrecipitation
.mobSpawnSettings(vanilla.getMobSettings()) .mobSpawnSettings(vanilla.getMobSettings())
.generationSettings(vanilla.getGenerationSettings()) .generationSettings(vanilla.getGenerationSettings())
.temperature(vanilla.getBaseTemperature()) .temperature(vanilla.getBaseTemperature())
.downfall(vanilla.getDownfall()); .downfall(vanilla.getDownfall());
BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder();
effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier()); effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier());
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) .waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()))
.waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())); .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()));
if(vanillaBiomeProperties.getFoliageColor() == null) { if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride); vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride);
} else { } else {
effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor());
} }
if(vanillaBiomeProperties.getGrassColor() == null) { if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride); vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride);
} else { } else {
@ -83,7 +66,7 @@ public class NMSBiomeInjector {
vanilla.getAmbientMood().ifPresent(effects::ambientMoodSound); vanilla.getAmbientMood().ifPresent(effects::ambientMoodSound);
vanilla.getBackgroundMusic().ifPresent(effects::backgroundMusic); vanilla.getBackgroundMusic().ifPresent(effects::backgroundMusic);
vanilla.getAmbientParticle().ifPresent(effects::ambientParticle); vanilla.getAmbientParticle().ifPresent(effects::ambientParticle);
builder.specialEffects(effects.build()); builder.specialEffects(effects.build());
return builder.build(); // build() return builder.build(); // build()

View File

@ -49,17 +49,14 @@ import com.dfsek.terra.api.world.info.WorldProperties;
public class NMSChunkGeneratorDelegate extends ChunkGenerator { public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(NMSChunkGeneratorDelegate.class); private static final Logger LOGGER = LoggerFactory.getLogger(NMSChunkGeneratorDelegate.class);
private static final Lazy<List<ChunkPos>> EMPTY = Lazy.lazy(List::of);
private final NMSBiomeProvider biomeSource; private final NMSBiomeProvider biomeSource;
private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate; private final com.dfsek.terra.api.world.chunk.generation.ChunkGenerator delegate;
private final ChunkGenerator vanilla; private final ChunkGenerator vanilla;
private final ConfigPack pack; private final ConfigPack pack;
private final long seed; private final long seed;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>(); private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
private static final Lazy<List<ChunkPos>> EMPTY = Lazy.lazy(List::of); private volatile boolean rings = false;
public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) { public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) {
super(Registries.structureSet(), Optional.empty(), biomeProvider, biomeProvider, seed); super(Registries.structureSet(), Optional.empty(), biomeProvider, biomeProvider, seed);
@ -71,13 +68,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull BiomeManager biomeAccess, @NotNull StructureFeatureManager structureAccessor, public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull BiomeManager biomeAccess,
@NotNull StructureFeatureManager structureAccessor,
@NotNull ChunkAccess chunk, GenerationStep.@NotNull Carving generationStep) { @NotNull ChunkAccess chunk, GenerationStep.@NotNull Carving generationStep) {
// no-op // no-op
} }
@Override @Override
public void applyBiomeDecoration(@NotNull WorldGenLevel world, @NotNull ChunkAccess chunk, @NotNull StructureFeatureManager structureAccessor) { public void applyBiomeDecoration(@NotNull WorldGenLevel world, @NotNull ChunkAccess chunk,
@NotNull StructureFeatureManager structureAccessor) {
vanilla.applyBiomeDecoration(world, chunk, structureAccessor); vanilla.applyBiomeDecoration(world, chunk, structureAccessor);
} }
@ -87,7 +86,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public @NotNull CompletableFuture<ChunkAccess> fillFromNoise(@NotNull Executor executor, @NotNull Blender blender, @NotNull StructureFeatureManager structureAccessor, public @NotNull CompletableFuture<ChunkAccess> fillFromNoise(@NotNull Executor executor, @NotNull Blender blender,
@NotNull StructureFeatureManager structureAccessor,
@NotNull ChunkAccess chunk) { @NotNull ChunkAccess chunk) {
return vanilla.fillFromNoise(executor, blender, structureAccessor, chunk); return vanilla.fillFromNoise(executor, blender, structureAccessor, chunk);
} }
@ -161,8 +161,6 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
return ringPositions.getOrDefault(concentricringsstructureplacement, EMPTY).value(); return ringPositions.getOrDefault(concentricringsstructureplacement, EMPTY).value();
} }
private volatile boolean rings = false;
@Override @Override
public synchronized void ensureStructuresGenerated() { public synchronized void ensureStructuresGenerated() {
if(!this.rings) { if(!this.rings) {

View File

@ -25,15 +25,16 @@ public class NMSInjectListener implements Listener {
@EventHandler @EventHandler
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
if (!INJECTED.contains(event.getWorld()) && event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) { if(!INJECTED.contains(event.getWorld()) &&
event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) {
INJECT_LOCK.lock(); INJECT_LOCK.lock();
INJECTED.add(event.getWorld()); INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());
CraftWorld craftWorld = (CraftWorld) event.getWorld(); CraftWorld craftWorld = (CraftWorld) event.getWorld();
ServerLevel serverWorld = craftWorld.getHandle(); ServerLevel serverWorld = craftWorld.getHandle();
ConfigPack pack = bukkitChunkGeneratorWrapper.getPack(); ConfigPack pack = bukkitChunkGeneratorWrapper.getPack();
ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator(); ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator();
NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), vanilla.getBiomeSource(), craftWorld.getSeed()); NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), vanilla.getBiomeSource(), craftWorld.getSeed());
NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed()); NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed());

View File

@ -15,18 +15,21 @@ public class Reflection {
static { static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, Reflection.class.getClassLoader()); ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
Reflection.class.getClassLoader());
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class); BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class);
} }
@Proxies(MappedRegistry.class) @Proxies(MappedRegistry.class)
public interface MappedRegistryProxy { public interface MappedRegistryProxy {
@FieldSetter("frozen") @FieldSetter("frozen")
void setFrozen(MappedRegistry<?> instance, boolean frozen); void setFrozen(MappedRegistry<?> instance, boolean frozen);
} }
@Proxies(Biome.class) @Proxies(Biome.class)
public interface BiomeProxy { public interface BiomeProxy {
@FieldGetter("biomeCategory") @FieldGetter("biomeCategory")

View File

@ -1,7 +1,5 @@
package com.dfsek.terra.bukkit.nms.v1_19_R1; package com.dfsek.terra.bukkit.nms.v1_19_R1;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
@ -17,7 +15,15 @@ import org.bukkit.NamespacedKey;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class AwfulBukkitHacks { public class AwfulBukkitHacks {
private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class); private static final Logger LOGGER = LoggerFactory.getLogger(AwfulBukkitHacks.class);
@ -39,10 +45,11 @@ public class AwfulBukkitHacks {
Biome platform = NMSBiomeInjector.createBiome( Biome platform = NMSBiomeInjector.createBiome(
biome, biome,
Objects.requireNonNull(biomeRegistry.get(vanillaMinecraftKey)) // get Objects.requireNonNull(biomeRegistry.get(vanillaMinecraftKey)) // get
); );
ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY, ResourceKey<Biome> delegateKey = ResourceKey.create(Registry.BIOME_REGISTRY,
new ResourceLocation("terra", NMSBiomeInjector.createBiomeID(pack, key))); new ResourceLocation("terra",
NMSBiomeInjector.createBiomeID(pack, key)));
BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform); BuiltinRegistries.register(BuiltinRegistries.BIOME, delegateKey, platform);
biomeRegistry.register(delegateKey, platform, Lifecycle.stable()); biomeRegistry.register(delegateKey, platform, Lifecycle.stable());
@ -62,35 +69,42 @@ public class AwfulBukkitHacks {
Map<TagKey<Biome>, List<Holder<Biome>>> collect = biomeRegistry Map<TagKey<Biome>, List<Holder<Biome>>> collect = biomeRegistry
.getTags() // streamKeysAndEntries .getTags() // streamKeysAndEntries
.collect(HashMap::new, .collect(HashMap::new,
(map, pair) -> (map, pair) ->
map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())), map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())),
HashMap::putAll); HashMap::putAll);
terraBiomeMap terraBiomeMap
.forEach((vb, terraBiomes) -> .forEach((vb, terraBiomes) ->
NMSBiomeInjector.getEntry(biomeRegistry, vb) NMSBiomeInjector.getEntry(biomeRegistry, vb)
.ifPresentOrElse( .ifPresentOrElse(
vanilla -> terraBiomes vanilla -> terraBiomes
.forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb) .forEach(tb -> NMSBiomeInjector.getEntry(biomeRegistry, tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
LOGGER.debug(vanilla.unwrapKey().orElseThrow().location() + LOGGER.debug(
" (vanilla for " + vanilla.unwrapKey()
terra.unwrapKey().orElseThrow().location() + .orElseThrow()
": " + .location() +
vanilla.tags().toList()); " (vanilla for " +
terra.unwrapKey()
vanilla.tags() .orElseThrow()
.forEach( .location() +
tag -> collect ": " +
.computeIfAbsent(tag, vanilla.tags()
t -> new ArrayList<>()) .toList());
.add(terra));
}, vanilla.tags()
() -> LOGGER.error( .forEach(
"No such biome: {}", tag -> collect
tb))), .computeIfAbsent(
() -> LOGGER.error("No vanilla biome: {}", vb))); tag,
t -> new ArrayList<>())
.add(terra));
},
() -> LOGGER.error(
"No such biome: {}",
tb))),
() -> LOGGER.error("No vanilla biome: {}", vb)));
biomeRegistry.resetTags(); biomeRegistry.resetTags();
biomeRegistry.bindTags(ImmutableMap.copyOf(collect)); biomeRegistry.bindTags(ImmutableMap.copyOf(collect));

View File

@ -1,33 +1,17 @@
package com.dfsek.terra.bukkit.nms.v1_19_R1; package com.dfsek.terra.bukkit.nms.v1_19_R1;
import com.google.common.collect.ImmutableMap;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.BiomeSpecialEffects;
import org.bukkit.NamespacedKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry;
public class NMSBiomeInjector { public class NMSBiomeInjector {

View File

@ -18,7 +18,11 @@ public class NMSBiomeProvider extends BiomeSource {
private final Registry<Biome> biomeRegistry = Registries.biomeRegistry(); private final Registry<Biome> biomeRegistry = Registries.biomeRegistry();
public NMSBiomeProvider(BiomeProvider delegate, long seed) { public NMSBiomeProvider(BiomeProvider delegate, long seed) {
super(delegate.stream().map(biome -> Registries.biomeRegistry().getHolderOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext().get(NMSBiomeInfo.class).biomeKey()))); super(delegate.stream()
.map(biome -> Registries.biomeRegistry()
.getHolderOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey())));
this.delegate = delegate; this.delegate = delegate;
this.seed = seed; this.seed = seed;
} }
@ -30,6 +34,9 @@ public class NMSBiomeProvider extends BiomeSource {
@Override @Override
public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) { public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) {
return biomeRegistry.getHolderOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed).getPlatformBiome()).getContext().get(NMSBiomeInfo.class).biomeKey()); return biomeRegistry.getHolderOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed)
.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class)
.biomeKey());
} }
} }

View File

@ -55,6 +55,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
private final ConfigPack pack; private final ConfigPack pack;
private final long seed; private final long seed;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
private volatile boolean rings = false;
public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) { public NMSChunkGeneratorDelegate(ChunkGenerator vanilla, ConfigPack pack, NMSBiomeProvider biomeProvider, long seed) {
super(Registries.structureSet(), Optional.empty(), biomeProvider); super(Registries.structureSet(), Optional.empty(), biomeProvider);
@ -137,19 +139,16 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
.getHandle()).getState(); .getHandle()).getState();
} }
return new NoiseColumn(getMinY(), array); return new NoiseColumn(getMinY(), array);
*/ */
return vanilla.getBaseColumn(x, z, world, noiseConfig); return vanilla.getBaseColumn(x, z, world, noiseConfig);
} }
@Override @Override
public void addDebugScreenInfo(@NotNull List<String> text, @NotNull RandomState noiseConfig, @NotNull BlockPos pos) { public void addDebugScreenInfo(@NotNull List<String> text, @NotNull RandomState noiseConfig, @NotNull BlockPos pos) {
} }
private volatile boolean rings = false;
private final Map<ConcentricRingsStructurePlacement, Lazy<List<ChunkPos>>> ringPositions = new Object2ObjectArrayMap<>();
@Override @Override
public void ensureStructuresGenerated(@NotNull RandomState noiseConfig) { public void ensureStructuresGenerated(@NotNull RandomState noiseConfig) {
if(!this.rings) { if(!this.rings) {
@ -161,7 +160,8 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
@Override @Override
public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement, @NotNull RandomState noiseConfig) { public List<ChunkPos> getRingPositionsFor(@NotNull ConcentricRingsStructurePlacement structurePlacement,
@NotNull RandomState noiseConfig) {
ensureStructuresGenerated(noiseConfig); ensureStructuresGenerated(noiseConfig);
return ringPositions.get(structurePlacement).value(); return ringPositions.get(structurePlacement).value();
} }
@ -179,13 +179,15 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
} }
} }
if (match) { if(match) {
if (holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) { if(holder.placement() instanceof ConcentricRingsStructurePlacement concentricringsstructureplacement) {
this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement))); this.ringPositions.put(concentricringsstructureplacement, Lazy.lazy(
() -> this.generateRingPositions(holder, noiseConfig, concentricringsstructureplacement)));
} }
} }
}); });
} }
private List<ChunkPos> generateRingPositions(StructureSet holder, RandomState randomstate, private List<ChunkPos> generateRingPositions(StructureSet holder, RandomState randomstate,
ConcentricRingsStructurePlacement concentricringsstructureplacement) { // Spigot ConcentricRingsStructurePlacement concentricringsstructureplacement) { // Spigot
if(concentricringsstructureplacement.count() == 0) { if(concentricringsstructureplacement.count() == 0) {

View File

@ -25,15 +25,16 @@ public class NMSInjectListener implements Listener {
@EventHandler @EventHandler
public void onWorldInit(WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
if (!INJECTED.contains(event.getWorld()) && event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) { if(!INJECTED.contains(event.getWorld()) &&
event.getWorld().getGenerator() instanceof BukkitChunkGeneratorWrapper bukkitChunkGeneratorWrapper) {
INJECT_LOCK.lock(); INJECT_LOCK.lock();
INJECTED.add(event.getWorld()); INJECTED.add(event.getWorld());
LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName()); LOGGER.info("Preparing to take over the world: {}", event.getWorld().getName());
CraftWorld craftWorld = (CraftWorld) event.getWorld(); CraftWorld craftWorld = (CraftWorld) event.getWorld();
ServerLevel serverWorld = craftWorld.getHandle(); ServerLevel serverWorld = craftWorld.getHandle();
ConfigPack pack = bukkitChunkGeneratorWrapper.getPack(); ConfigPack pack = bukkitChunkGeneratorWrapper.getPack();
ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator(); ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator();
NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed()); NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed());
NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed()); NMSChunkGeneratorDelegate custom = new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed());

View File

@ -12,11 +12,13 @@ public class Reflection {
static { static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, Reflection.class.getClassLoader()); ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
Reflection.class.getClassLoader());
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
} }
@Proxies(MappedRegistry.class) @Proxies(MappedRegistry.class)
public interface MappedRegistryProxy { public interface MappedRegistryProxy {
@FieldSetter("frozen") @FieldSetter("frozen")

View File

@ -16,8 +16,8 @@ public class Registries {
return dedicatedserver return dedicatedserver
.registryAccess() .registryAccess()
.registryOrThrow( // getRegistry .registryOrThrow( // getRegistry
key key
); );
} }
public static Registry<Biome> biomeRegistry() { public static Registry<Biome> biomeRegistry() {

View File

@ -16,9 +16,9 @@ public class CLIBlockState implements BlockState {
public CLIBlockState(String value) { public CLIBlockState(String value) {
this.value = value; this.value = value;
if(value.contains("[")) { if(value.contains("[")) {
} else { } else {
} }
this.isAir = value.startsWith("minecraft:air"); this.isAir = value.startsWith("minecraft:air");
this.nbt = new CompoundTag(); this.nbt = new CompoundTag();

View File

@ -25,7 +25,13 @@ dependencies {
modImplementation("net.fabricmc:fabric-loader:${Versions.Fabric.fabricLoader}") modImplementation("net.fabricmc:fabric-loader:${Versions.Fabric.fabricLoader}")
setOf("fabric-lifecycle-events-v1", "fabric-resource-loader-v0", "fabric-api-base", "fabric-command-api-v2", "fabric-networking-api-v1").forEach { apiModule -> setOf(
"fabric-lifecycle-events-v1",
"fabric-resource-loader-v0",
"fabric-api-base",
"fabric-command-api-v2",
"fabric-networking-api-v1"
).forEach { apiModule ->
val module = fabricApi.module(apiModule, Versions.Fabric.fabricAPI) val module = fabricApi.module(apiModule, Versions.Fabric.fabricAPI)
modImplementation(module) modImplementation(module)
include(module) include(module)

View File

@ -3,12 +3,13 @@ package com.dfsek.terra.fabric;
import com.dfsek.terra.mod.MinecraftAddon; import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.ModPlatform;
public class FabricAddon extends MinecraftAddon {
public class FabricAddon extends MinecraftAddon {
public FabricAddon(ModPlatform modPlatform) { public FabricAddon(ModPlatform modPlatform) {
super(modPlatform); super(modPlatform);
} }
@Override @Override
public String getID() { public String getID() {
return "terra-fabric"; return "terra-fabric";

View File

@ -32,7 +32,7 @@ public class FabricEntryPoint implements ModInitializer {
private static final Logger logger = LoggerFactory.getLogger(FabricEntryPoint.class); private static final Logger logger = LoggerFactory.getLogger(FabricEntryPoint.class);
private static final FabricPlatform TERRA_PLUGIN = new FabricPlatform(); private static final FabricPlatform TERRA_PLUGIN = new FabricPlatform();
@Override @Override
public void onInitialize() { public void onInitialize() {
logger.info("Initializing Terra Fabric mod..."); logger.info("Initializing Terra Fabric mod...");

View File

@ -20,9 +20,6 @@ package com.dfsek.terra.fabric;
import ca.solostudios.strata.Versions; import ca.solostudios.strata.Versions;
import ca.solostudios.strata.parser.tokenizer.ParseException; import ca.solostudios.strata.parser.tokenizer.ParseException;
import ca.solostudios.strata.version.Version; import ca.solostudios.strata.version.Version;
import com.dfsek.terra.lifecycle.LifecyclePlatform;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -35,8 +32,7 @@ import java.util.stream.Stream;
import com.dfsek.terra.addon.EphemeralAddon; import com.dfsek.terra.addon.EphemeralAddon;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.util.generic.Lazy; import com.dfsek.terra.lifecycle.LifecyclePlatform;
import com.dfsek.terra.mod.CommonPlatform;
public class FabricPlatform extends LifecyclePlatform { public class FabricPlatform extends LifecyclePlatform {
@ -59,6 +55,7 @@ public class FabricPlatform extends LifecyclePlatform {
return Stream.empty(); return Stream.empty();
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
@Override @Override
public @NotNull String platformName() { public @NotNull String platformName() {
return "Fabric"; return "Fabric";
@ -68,7 +65,7 @@ public class FabricPlatform extends LifecyclePlatform {
public @NotNull File getDataFolder() { public @NotNull File getDataFolder() {
return new File(FabricLoader.getInstance().getConfigDir().toFile(), "Terra"); return new File(FabricLoader.getInstance().getConfigDir().toFile(), "Terra");
} }
@Override @Override
public BaseAddon getPlatformAddon() { public BaseAddon getPlatformAddon() {
return new FabricAddon(this); return new FabricAddon(this);

View File

@ -70,7 +70,7 @@ tasks {
) )
} }
} }
remapJar { remapJar {
inputFile.set(shadowJar.get().archiveFile) inputFile.set(shadowJar.get().archiveFile)
archiveFileName.set("${rootProject.name.capitalize()}-${project.version}.jar") archiveFileName.set("${rootProject.name.capitalize()}-${project.version}.jar")

View File

@ -1,32 +1,22 @@
package com.dfsek.terra.forge; package com.dfsek.terra.forge;
import com.dfsek.terra.AbstractPlatform;
import cpw.mods.cl.ModuleClassLoader;
import net.minecraftforge.fml.loading.FMLLoader; import net.minecraftforge.fml.loading.FMLLoader;
import org.burningwave.core.classes.Classes; import org.burningwave.core.classes.Classes;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.file.FileVisitOption; import java.nio.file.FileVisitOption;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.stream.Stream; import java.util.stream.Stream;
import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader; import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader;
@ -73,7 +63,7 @@ public final class AwfulForgeHacks {
} }
public static void loadAllTerraClasses() { public static void loadAllTerraClasses() {
if (FMLLoader.isProduction()) { if(FMLLoader.isProduction()) {
try(JarFile jar = getTerraJar()) { try(JarFile jar = getTerraJar()) {
jar.stream() jar.stream()
.forEach(jarEntry -> { .forEach(jarEntry -> {
@ -96,45 +86,52 @@ public final class AwfulForgeHacks {
} }
} else { } else {
// Forgive me for what I'm about to do... // Forgive me for what I'm about to do...
LOGGER.warn("I felt a great disturbance in the JVM, as if millions of class not found exceptions suddenly cried out in terror and were suddenly silenced."); LOGGER.warn(
"I felt a great disturbance in the JVM, as if millions of class not found exceptions suddenly cried out in terror and" +
" were suddenly silenced.");
ArrayList<Path> pathsToLoad = new ArrayList<>(); ArrayList<Path> pathsToLoad = new ArrayList<>();
Path terraRoot = Path.of(System.getProperty("user.dir")).getParent().getParent().getParent(); Path terraRoot = Path.of(System.getProperty("user.dir")).getParent().getParent().getParent();
Path commonRoot = terraRoot.resolve("common"); Path commonRoot = terraRoot.resolve("common");
Path implementationRoot = commonRoot.resolve("implementation"); Path implementationRoot = commonRoot.resolve("implementation");
pathsToLoad.add(commonRoot.resolve("api")); pathsToLoad.add(commonRoot.resolve("api"));
pathsToLoad.add(implementationRoot.resolve("base")); pathsToLoad.add(implementationRoot.resolve("base"));
pathsToLoad.add(implementationRoot.resolve("bootstrap-addon-loader")); pathsToLoad.add(implementationRoot.resolve("bootstrap-addon-loader"));
for (Path path : pathsToLoad) { for(Path path : pathsToLoad) {
try { try {
Path target = path.resolve("build").resolve("classes").resolve("java").resolve("main"); Path target = path.resolve("build").resolve("classes").resolve("java").resolve("main");
BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[] { path.toUri().toURL()}); BootstrapAddonClassLoader cl = new BootstrapAddonClassLoader(new URL[]{ path.toUri().toURL() });
Classes.Loaders omegaCL = Classes.Loaders.create(); Classes.Loaders omegaCL = Classes.Loaders.create();
Files.walk(target, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS) Files.walk(target, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
.filter(it -> it.getFileName().toString().endsWith(".class")) .filter(it -> it.getFileName().toString().endsWith(".class"))
.map(Path::toFile) .map(Path::toFile)
.forEach(it -> { .forEach(it -> {
String name = it.getAbsolutePath().replace(target + "/", "").replace('\\', '.').replace('/', '.'); String name = it.getAbsolutePath().replace(target + "/", "").replace('\\', '.').replace('/', '.');
name = name.substring(0, name.length() - 6); name = name.substring(0, name.length() - 6);
LOGGER.info("Loading class {}", name); LOGGER.info("Loading class {}", name);
try { try {
Class.forName(name); Class.forName(name);
} catch(ClassNotFoundException e) { } catch(ClassNotFoundException e) {
try { try {
String pathToJar = cl.loadClass(name).getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); String pathToJar = cl.loadClass(name)
.getProtectionDomain()
cl.addURL(new URL("jar:file:" + pathToJar + "!/")); .getCodeSource()
Class newClassLoad = Class.forName(name, true, cl); .getLocation()
omegaCL.loadOrDefine(newClassLoad, AbstractPlatform.class.getClassLoader()); .toURI()
} catch(ClassNotFoundException | URISyntaxException | IOException ex) { .getPath();
throw new RuntimeException(ex);
} cl.addURL(new URL("jar:file:" + pathToJar + "!/"));
Class newClassLoad = Class.forName(name, true, cl);
} omegaCL.loadOrDefine(newClassLoad, AbstractPlatform.class.getClassLoader());
}); } catch(ClassNotFoundException | URISyntaxException | IOException ex) {
throw new RuntimeException(ex);
}
}
});
} catch(IOException e) { } catch(IOException e) {
throw new IllegalStateException("Could not load all Terra classes", e); throw new IllegalStateException("Could not load all Terra classes", e);
} }

View File

@ -3,12 +3,13 @@ package com.dfsek.terra.forge;
import com.dfsek.terra.mod.MinecraftAddon; import com.dfsek.terra.mod.MinecraftAddon;
import com.dfsek.terra.mod.ModPlatform; import com.dfsek.terra.mod.ModPlatform;
public class ForgeAddon extends MinecraftAddon {
public class ForgeAddon extends MinecraftAddon {
public ForgeAddon(ModPlatform modPlatform) { public ForgeAddon(ModPlatform modPlatform) {
super(modPlatform); super(modPlatform);
} }
@Override @Override
public String getID() { public String getID() {
return "terra-forge"; return "terra-forge";

View File

@ -43,28 +43,24 @@ import com.dfsek.terra.mod.data.Codecs;
@Mod("terra") @Mod("terra")
@EventBusSubscriber(bus = Bus.MOD) @EventBusSubscriber(bus = Bus.MOD)
public class ForgeEntryPoint { public class ForgeEntryPoint {
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck(); public static final String MODID = "terra";
private static final Logger logger = LoggerFactory.getLogger(ForgeEntryPoint.class);
private static final ForgePlatform TERRA_PLUGIN;
static { static {
AwfulForgeHacks.loadAllTerraClasses(); AwfulForgeHacks.loadAllTerraClasses();
TERRA_PLUGIN = new ForgePlatform(); TERRA_PLUGIN = new ForgePlatform();
} }
private final RegistrySanityCheck sanityCheck = new RegistrySanityCheck();
public static final String MODID = "terra";
private static final Logger logger = LoggerFactory.getLogger(ForgeEntryPoint.class);
private static final ForgePlatform TERRA_PLUGIN;
public static ForgePlatform getPlatform() {
return TERRA_PLUGIN;
}
public ForgeEntryPoint() { public ForgeEntryPoint() {
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
modEventBus.register(this); modEventBus.register(this);
} }
public static ForgePlatform getPlatform() {
return TERRA_PLUGIN;
}
public static void initialize(RegisterHelper<Biome> helper) { public static void initialize(RegisterHelper<Biome> helper) {
getPlatform().getEventManager().callEvent( getPlatform().getEventManager().callEvent(
new PlatformInitializationEvent()); new PlatformInitializationEvent());
@ -75,10 +71,12 @@ public class ForgeEntryPoint {
public void registerBiomes(RegisterEvent event) { public void registerBiomes(RegisterEvent event) {
event.register(Keys.BLOCKS, helper -> sanityCheck.progress(RegistryStep.BLOCK, () -> logger.debug("Block registration detected."))); event.register(Keys.BLOCKS, helper -> sanityCheck.progress(RegistryStep.BLOCK, () -> logger.debug("Block registration detected.")));
event.register(Keys.BIOMES, helper -> sanityCheck.progress(RegistryStep.BIOME, () -> initialize(helper))); event.register(Keys.BIOMES, helper -> sanityCheck.progress(RegistryStep.BIOME, () -> initialize(helper)));
event.register(Registry.WORLD_PRESET_KEY, helper -> sanityCheck.progress(RegistryStep.WORLD_TYPE, () -> TERRA_PLUGIN.registerWorldTypes(helper::register))); event.register(Registry.WORLD_PRESET_KEY,
helper -> sanityCheck.progress(RegistryStep.WORLD_TYPE, () -> TERRA_PLUGIN.registerWorldTypes(helper::register)));
event.register(Registry.CHUNK_GENERATOR_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER)); event.register(Registry.CHUNK_GENERATOR_KEY,
helper -> helper.register(new Identifier("terra:terra"), Codecs.MINECRAFT_CHUNK_GENERATOR_WRAPPER));
event.register(Registry.BIOME_SOURCE_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.TERRA_BIOME_SOURCE)); event.register(Registry.BIOME_SOURCE_KEY, helper -> helper.register(new Identifier("terra:terra"), Codecs.TERRA_BIOME_SOURCE));
} }
} }

View File

@ -43,33 +43,33 @@ import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
public class ForgePlatform extends ModPlatform { public class ForgePlatform extends ModPlatform {
private static final Logger LOGGER = LoggerFactory.getLogger(ForgePlatform.class); private static final Logger LOGGER = LoggerFactory.getLogger(ForgePlatform.class);
private final Lazy<File> dataFolder = Lazy.lazy(() -> new File("./config/Terra")); private final Lazy<File> dataFolder = Lazy.lazy(() -> new File("./config/Terra"));
public ForgePlatform() { public ForgePlatform() {
CommonPlatform.initialize(this); CommonPlatform.initialize(this);
load(); load();
} }
@Override @Override
public MinecraftServer getServer() { public MinecraftServer getServer() {
return ServerLifecycleHooks.getCurrentServer(); return ServerLifecycleHooks.getCurrentServer();
} }
@Override @Override
public boolean reload() { public boolean reload() {
getTerraConfig().load(this); getTerraConfig().load(this);
getRawConfigRegistry().clear(); getRawConfigRegistry().clear();
boolean succeed = getRawConfigRegistry().loadAll(this); boolean succeed = getRawConfigRegistry().loadAll(this);
MinecraftServer server = getServer(); MinecraftServer server = getServer();
if (server != null) { if(server != null) {
server.reloadResources(server.getDataPackManager().getNames()).exceptionally(throwable -> { server.reloadResources(server.getDataPackManager().getNames()).exceptionally(throwable -> {
LOGGER.warn("Failed to execute reload", throwable); LOGGER.warn("Failed to execute reload", throwable);
return null; return null;
}).join(); }).join();
//BiomeUtil.registerBiomes(); //BiomeUtil.registerBiomes();
server.getWorlds().forEach(world -> { server.getWorlds().forEach(world -> {
if (world.getChunkManager().getChunkGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) { if(world.getChunkManager().getChunkGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) {
getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> { getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> {
chunkGeneratorWrapper.setPack(pack); chunkGeneratorWrapper.setPack(pack);
LOGGER.info("Replaced pack in chunk generator for world {}", world); LOGGER.info("Replaced pack in chunk generator for world {}", world);
@ -79,34 +79,35 @@ public class ForgePlatform extends ModPlatform {
} }
return succeed; return succeed;
} }
@Override @Override
protected Iterable<BaseAddon> platformAddon() { protected Iterable<BaseAddon> platformAddon() {
List<BaseAddon> addons = new ArrayList<>(); List<BaseAddon> addons = new ArrayList<>();
super.platformAddon().forEach(addons::add); super.platformAddon().forEach(addons::add);
String mcVersion = MinecraftVersion.CURRENT.getReleaseTarget(); String mcVersion = MinecraftVersion.CURRENT.getReleaseTarget();
try { try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft")); addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion), "minecraft"));
} catch (ParseException e) { } catch(ParseException e) {
try { try {
addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion + ".0"), "minecraft")); addons.add(new EphemeralAddon(Versions.parseVersion(mcVersion + ".0"), "minecraft"));
} catch (ParseException ex) { } catch(ParseException ex) {
LOGGER.warn("Failed to parse Minecraft version", e); LOGGER.warn("Failed to parse Minecraft version", e);
} }
} }
FMLLoader.getLoadingModList().getMods().forEach(mod -> { FMLLoader.getLoadingModList().getMods().forEach(mod -> {
String id = mod.getModId(); String id = mod.getModId();
if (id.equals("terra") || id.equals("minecraft") || id.equals("java")) return; if(id.equals("terra") || id.equals("minecraft") || id.equals("java")) return;
Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(), mod.getVersion().getIncrementalVersion()); Version version = Versions.getVersion(mod.getVersion().getMajorVersion(), mod.getVersion().getMinorVersion(),
mod.getVersion().getIncrementalVersion());
addons.add(new EphemeralAddon(version, "forge:" + id)); addons.add(new EphemeralAddon(version, "forge:" + id));
}); });
return addons; return addons;
} }
@Override @Override
public @NotNull String platformName() { public @NotNull String platformName() {
return "Forge"; return "Forge";
@ -116,7 +117,7 @@ public class ForgePlatform extends ModPlatform {
public @NotNull File getDataFolder() { public @NotNull File getDataFolder() {
return dataFolder.value(); return dataFolder.value();
} }
@Override @Override
public BaseAddon getPlatformAddon() { public BaseAddon getPlatformAddon() {
return new ForgeAddon(this); return new ForgeAddon(this);

View File

@ -24,7 +24,15 @@ public class NoiseConfigMixin {
@Final @Final
private long legacyWorldSeed; private long legacyWorldSeed;
@Redirect(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V", at = @At(value = "NEW", target = "(Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Lnet/minecraft/world/gen/densityfunction/DensityFunction;Ljava/util/List;)Lnet/minecraft/world/biome/source/util/MultiNoiseUtil$MultiNoiseSampler;")) @Redirect(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V",
at = @At(value = "NEW",
target = "(Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;" +
"Lnet/minecraft/world/gen/densityfunction/DensityFunction;Ljava/util/List;)" +
"Lnet/minecraft/world/biome/source/util/MultiNoiseUtil$MultiNoiseSampler;"))
private MultiNoiseSampler t(DensityFunction densityFunction, DensityFunction densityFunction2, DensityFunction densityFunction3, private MultiNoiseSampler t(DensityFunction densityFunction, DensityFunction densityFunction2, DensityFunction densityFunction3,
DensityFunction densityFunction4, DensityFunction densityFunction5, DensityFunction densityFunction6, DensityFunction densityFunction4, DensityFunction densityFunction5, DensityFunction densityFunction6,
List<NoiseHypercube> list) { List<NoiseHypercube> list) {

View File

@ -1,8 +1,5 @@
package com.dfsek.terra.forge.util; package com.dfsek.terra.forge.util;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries; import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
@ -22,6 +19,8 @@ import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.forge.ForgeEntryPoint; import com.dfsek.terra.forge.ForgeEntryPoint;
import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.config.ProtoPlatformBiome;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import com.dfsek.terra.mod.util.MinecraftUtil; import com.dfsek.terra.mod.util.MinecraftUtil;
@ -32,7 +31,7 @@ public final class BiomeUtil {
private BiomeUtil() { private BiomeUtil() {
} }
public static void registerBiomes(RegisterHelper<net.minecraft.world.biome.Biome> helper) { public static void registerBiomes(RegisterHelper<net.minecraft.world.biome.Biome> helper) {
logger.info("Registering biomes..."); logger.info("Registering biomes...");
@ -51,29 +50,41 @@ public final class BiomeUtil {
* @param pack The ConfigPack this biome belongs to. * @param pack The ConfigPack this biome belongs to.
*/ */
private static void registerBiome(Biome biome, ConfigPack pack, private static void registerBiome(Biome biome, ConfigPack pack,
com.dfsek.terra.api.registry.key.RegistryKey id, RegisterHelper<net.minecraft.world.biome.Biome> helper) { com.dfsek.terra.api.registry.key.RegistryKey id,
RegistryKey<net.minecraft.world.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()) .get(BuiltinRegistries.BIOME); RegisterHelper<net.minecraft.world.biome.Biome> helper) {
RegistryKey<net.minecraft.world.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(BuiltinRegistries.BIOME);
if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) { if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(vanilla); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(vanilla);
} else { } else {
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome, ForgeRegistries.BIOMES.getDelegateOrThrow(vanilla).value(), vanillaBiomeProperties); net.minecraft.world.biome.Biome minecraftBiome = MinecraftUtil.createBiome(biome,
ForgeRegistries.BIOMES.getDelegateOrThrow(vanilla)
.value(),
vanillaBiomeProperties);
Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id)); Identifier identifier = new Identifier("terra", MinecraftUtil.createBiomeID(pack, id));
if(ForgeRegistries.BIOMES.containsKey(identifier)) { if(ForgeRegistries.BIOMES.containsKey(identifier)) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier).orElseThrow().getKey().orElseThrow()); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier)
.orElseThrow()
.getKey()
.orElseThrow());
} else { } else {
helper.register(MinecraftUtil.registerKey(identifier).getValue(), minecraftBiome); helper.register(MinecraftUtil.registerKey(identifier).getValue(), minecraftBiome);
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier).orElseThrow().getKey().orElseThrow()); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(ForgeRegistries.BIOMES.getHolder(identifier)
.orElseThrow()
.getKey()
.orElseThrow());
} }
Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap(); Map villagerMap = VillagerTypeAccessor.getBiomeTypeToIdMap();
villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier), Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(), villagerMap.getOrDefault(vanilla, VillagerType.PLAINS))); villagerMap.put(RegistryKey.of(Registry.BIOME_KEY, identifier),
Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(),
villagerMap.getOrDefault(vanilla, VillagerType.PLAINS)));
MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier); MinecraftUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.getValue(), i -> new ArrayList<>()).add(identifier);
} }

View File

@ -1,7 +1,7 @@
modLoader = "javafml" modLoader = "javafml"
loaderVersion = "[41,)" loaderVersion = "[41,)"
license = "GNU General Public License, v3.0" license = "GNU General Public License, v3.0"
issueTrackerURL="https://github.com/PolyhedralDev/Terra/issues" issueTrackerURL = "https://github.com/PolyhedralDev/Terra/issues"
[[mods]] [[mods]]
modId = "terra" modId = "terra"

View File

@ -1,6 +1,6 @@
{ {
"pack": { "pack": {
"description": "Terra Resources", "description": "Terra Resources",
"pack_format": 9 "pack_format": 9
} }
} }

View File

@ -4,7 +4,7 @@
"package": "com.dfsek.terra.forge.mixin", "package": "com.dfsek.terra.forge.mixin",
"compatibilityLevel": "JAVA_17", "compatibilityLevel": "JAVA_17",
"mixins": [ "mixins": [
"lifecycle.NoiseConfigMixin" "lifecycle.NoiseConfigMixin"
], ],
"client": [ "client": [
], ],

View File

@ -61,10 +61,10 @@ public abstract class MinecraftAddon implements BaseAddon {
.getHandler(FunctionalEventHandler.class) .getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class) .register(this, ConfigurationLoadEvent.class)
.then(event -> { .then(event -> {
if(event.is(Biome.class)) { if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties())); event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
} }
}) })
.global(); .global();
} }

View File

@ -3,17 +3,6 @@ package com.dfsek.terra.mod;
import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.TypeRegistry;
import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.mod.config.SpawnSettingsTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.config.VillagerTypeTemplate;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.entity.SpawnGroup; import net.minecraft.entity.SpawnGroup;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -31,6 +20,7 @@ import net.minecraft.world.biome.BiomeParticleConfig;
import net.minecraft.world.biome.SpawnSettings; import net.minecraft.world.biome.SpawnSettings;
import net.minecraft.world.biome.SpawnSettings.SpawnEntry; import net.minecraft.world.biome.SpawnSettings.SpawnEntry;
import net.minecraft.world.gen.WorldPreset; import net.minecraft.world.gen.WorldPreset;
import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -38,6 +28,8 @@ import java.util.function.BiConsumer;
import com.dfsek.terra.AbstractPlatform; import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.api.world.biome.PlatformBiome; import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate; import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate; import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate;
@ -49,17 +41,19 @@ import com.dfsek.terra.mod.config.SoundEventTemplate;
import com.dfsek.terra.mod.config.SpawnCostConfig; import com.dfsek.terra.mod.config.SpawnCostConfig;
import com.dfsek.terra.mod.config.SpawnEntryTemplate; import com.dfsek.terra.mod.config.SpawnEntryTemplate;
import com.dfsek.terra.mod.config.SpawnGroupTemplate; import com.dfsek.terra.mod.config.SpawnGroupTemplate;
import com.dfsek.terra.mod.config.SpawnSettingsTemplate;
import com.dfsek.terra.mod.config.SpawnTypeConfig; import com.dfsek.terra.mod.config.SpawnTypeConfig;
import com.dfsek.terra.mod.config.VillagerTypeTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.util.PresetUtil; import com.dfsek.terra.mod.util.PresetUtil;
import org.jetbrains.annotations.NotNull;
public abstract class ModPlatform extends AbstractPlatform { public abstract class ModPlatform extends AbstractPlatform {
public abstract MinecraftServer getServer();
private final ItemHandle itemHandle = new MinecraftItemHandle(); private final ItemHandle itemHandle = new MinecraftItemHandle();
private final WorldHandle worldHandle = new MinecraftWorldHandle(); private final WorldHandle worldHandle = new MinecraftWorldHandle();
public abstract MinecraftServer getServer();
public void registerWorldTypes(BiConsumer<Identifier, WorldPreset> registerFunction) { public void registerWorldTypes(BiConsumer<Identifier, WorldPreset> registerFunction) {
getRawConfigRegistry() getRawConfigRegistry()
@ -78,10 +72,12 @@ public abstract class ModPlatform extends AbstractPlatform {
}) })
.registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase( .registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase(
Locale.ROOT))) Locale.ROOT)))
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase( .registerLoader(GrassColorModifier.class,
Locale.ROOT))) (type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
.registerLoader(GrassColorModifier.class, (type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase( Locale.ROOT)))
Locale.ROOT))) .registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new) .registerLoader(BiomeParticleConfig.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new) .registerLoader(SoundEvent.class, SoundEventTemplate::new)
.registerLoader(BiomeMoodSound.class, BiomeMoodSoundTemplate::new) .registerLoader(BiomeMoodSound.class, BiomeMoodSoundTemplate::new)
@ -101,12 +97,12 @@ public abstract class ModPlatform extends AbstractPlatform {
if(BuiltinRegistries.BIOME.get(identifier) == null) throw new LoadException("Invalid Biome ID: " + identifier, tracker); // failure. if(BuiltinRegistries.BIOME.get(identifier) == null) throw new LoadException("Invalid Biome ID: " + identifier, tracker); // failure.
return new ProtoPlatformBiome(identifier); return new ProtoPlatformBiome(identifier);
} }
@Override @Override
protected Iterable<BaseAddon> platformAddon() { protected Iterable<BaseAddon> platformAddon() {
return List.of(getPlatformAddon()); return List.of(getPlatformAddon());
} }
protected abstract BaseAddon getPlatformAddon(); protected abstract BaseAddon getPlatformAddon();
@Override @Override

View File

@ -18,7 +18,7 @@ public class BiomeAdditionsSoundTemplate implements ObjectTemplate<BiomeAddition
@Override @Override
public BiomeAdditionsSound get() { public BiomeAdditionsSound get() {
if (sound == null || soundChance == null) { if(sound == null || soundChance == null) {
return null; return null;
} else { } else {
return new BiomeAdditionsSound(sound, soundChance); return new BiomeAdditionsSound(sound, soundChance);

View File

@ -26,7 +26,7 @@ public class BiomeMoodSoundTemplate implements ObjectTemplate<BiomeMoodSound> {
@Override @Override
public BiomeMoodSound get() { public BiomeMoodSound get() {
if (sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) { if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) {
return null; return null;
} else { } else {
return new BiomeMoodSound(sound, soundCultivationTicks, soundSpawnRange, soundExtraDistance); return new BiomeMoodSound(sound, soundCultivationTicks, soundSpawnRange, soundExtraDistance);

View File

@ -17,10 +17,10 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate<BiomeParticle
@Value("probability") @Value("probability")
@Default @Default
private Integer probability = null; private Integer probability = null;
@Override @Override
public BiomeParticleConfig get() { public BiomeParticleConfig get() {
if (particle == null || probability == null) { if(particle == null || probability == null) {
return null; return null;
} }

View File

@ -26,7 +26,7 @@ public class MusicSoundTemplate implements ObjectTemplate<MusicSound> {
@Override @Override
public MusicSound get() { public MusicSound get() {
if (sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) { if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) {
return null; return null;
} else { } else {
return new MusicSound(sound, minDelay, maxDelay, replaceCurrentMusic); return new MusicSound(sound, minDelay, maxDelay, replaceCurrentMusic);

View File

@ -18,9 +18,9 @@ public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
@Override @Override
public SoundEvent get() { public SoundEvent get() {
if (id == null) { if(id == null) {
return null; return null;
} else if (distanceToTravel == null) { } else if(distanceToTravel == null) {
return new SoundEvent(id); return new SoundEvent(id);
} else { } else {
return new SoundEvent(id, distanceToTravel); return new SoundEvent(id, distanceToTravel);

View File

@ -24,13 +24,13 @@ public class SpawnSettingsTemplate implements ObjectTemplate<SpawnSettings> {
@Override @Override
public SpawnSettings get() { public SpawnSettings get() {
SpawnSettings.Builder builder = new SpawnSettings.Builder(); SpawnSettings.Builder builder = new SpawnSettings.Builder();
for (SpawnTypeConfig spawn : spawns) { for(SpawnTypeConfig spawn : spawns) {
builder.spawn(spawn.getGroup(), spawn.getEntry()); builder.spawn(spawn.getGroup(), spawn.getEntry());
} }
for (SpawnCostConfig cost: costs) { for(SpawnCostConfig cost : costs) {
builder.spawnCost(cost.getType(), cost.getMass(), cost.getGravity()); builder.spawnCost(cost.getType(), cost.getMass(), cost.getGravity());
} }
if (probability != null) { if(probability != null) {
builder.creatureSpawnProbability(probability); builder.creatureSpawnProbability(probability);
} }

View File

@ -93,7 +93,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
public Integer getGrassColor() { public Integer getGrassColor() {
return grassColor; return grassColor;
} }
public Integer getFogColor() { public Integer getFogColor() {
return fogColor; return fogColor;
} }

View File

@ -3,7 +3,6 @@ package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default; import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value; import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate; import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.entity.EntityType;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.village.VillagerType; import net.minecraft.village.VillagerType;

View File

@ -31,8 +31,8 @@ public final class Codecs {
.getConfigRegistry() .getConfigRegistry()
.get(id) .get(id)
.orElseThrow(() -> new IllegalArgumentException( .orElseThrow(() -> new IllegalArgumentException(
"No such config pack " + "No such config pack " +
id))))); id)))));
public static final Codec<TerraBiomeSource> TERRA_BIOME_SOURCE = RecordCodecBuilder public static final Codec<TerraBiomeSource> TERRA_BIOME_SOURCE = RecordCodecBuilder
.create(instance -> instance.group(RegistryOps.createRegistryCodec(Registry.BIOME_KEY) .create(instance -> instance.group(RegistryOps.createRegistryCodec(Registry.BIOME_KEY)

View File

@ -8,6 +8,7 @@ import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map; import java.util.Map;
@Mixin(VillagerType.class) @Mixin(VillagerType.class)
public interface VillagerTypeAccessor { public interface VillagerTypeAccessor {
@Accessor("BIOME_TO_TYPE") @Accessor("BIOME_TO_TYPE")

View File

@ -20,7 +20,8 @@ import com.dfsek.terra.mod.CommonPlatform;
MoveToFlowerGoal.class MoveToFlowerGoal.class
}) })
public class BeeMoveGoalsUnsynchronizedRandomAccessFix { public class BeeMoveGoalsUnsynchronizedRandomAccessFix {
@Redirect(method = "<init>", at = @At(value = "FIELD", target = "Lnet/minecraft/world/World;random:Lnet/minecraft/util/math/random/Random;")) @Redirect(method = "<init>",
at = @At(value = "FIELD", target = "Lnet/minecraft/world/World;random:Lnet/minecraft/util/math/random/Random;"))
public Random redirectRandomAccess(World instance) { public Random redirectRandomAccess(World instance) {
return new CheckedRandom(CommonPlatform.get().getServer().getTicks()); // replace with new random seeded by tick time. return new CheckedRandom(CommonPlatform.get().getServer().getTicks()); // replace with new random seeded by tick time.
} }

View File

@ -15,8 +15,9 @@ import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
/** /**
* Disable fossil generation in Terra worlds, as they are very expensive due to consistently triggering cache misses. * Disable fossil generation in Terra worlds, as they are very expensive due to consistently triggering cache misses.
* * <p>
* Currently, on Fabric, Terra cannot be specified as a Nether generator. TODO: logic to turn fossils back on if chunk generator is in nether. * Currently, on Fabric, Terra cannot be specified as a Nether generator. TODO: logic to turn fossils back on if chunk generator is in
* nether.
*/ */
@Mixin(NetherFossilStructure.class) @Mixin(NetherFossilStructure.class)
public class NetherFossilOptimization { public class NetherFossilOptimization {

View File

@ -1,7 +1,5 @@
package com.dfsek.terra.mod.util; package com.dfsek.terra.mod.util;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.block.entity.MobSpawnerBlockEntity; import net.minecraft.block.entity.MobSpawnerBlockEntity;
import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.block.entity.SignBlockEntity;
@ -10,7 +8,6 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry; import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryEntry; import net.minecraft.util.registry.RegistryEntry;
import net.minecraft.util.registry.RegistryKey; import net.minecraft.util.registry.RegistryKey;
import net.minecraft.village.VillagerType;
import net.minecraft.world.WorldAccess; import net.minecraft.world.WorldAccess;
import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biome.Builder; import net.minecraft.world.biome.Biome.Builder;
@ -69,18 +66,23 @@ public final class MinecraftUtil {
TERRA_BIOME_MAP TERRA_BIOME_MAP
.forEach((vb, terraBiomes) -> .forEach((vb, terraBiomes) ->
biomes.getOrEmpty(vb) biomes.getOrEmpty(vb)
.ifPresentOrElse(vanilla -> terraBiomes .ifPresentOrElse(vanilla -> terraBiomes
.forEach(tb -> biomes.getOrEmpty(tb) .forEach(tb -> biomes.getOrEmpty(tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(vanilla.getGenerationSettings().getFlowerFeatures()); List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(
logger.debug("Injecting flora into biome {} : {}", tb, flowerFeatures); vanilla.getGenerationSettings()
((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(flowerFeatures); .getFlowerFeatures());
}, logger.debug("Injecting flora into biome" +
() -> logger.error( " {} : {}", tb,
"No such biome: {}", flowerFeatures);
tb))), ((FloraFeatureHolder) terra.getGenerationSettings()).setFloraFeatures(
() -> logger.error("No vanilla biome: {}", vb))); flowerFeatures);
},
() -> logger.error(
"No such biome: {}",
tb))),
() -> logger.error("No vanilla biome: {}", vb)));
} }
@ -92,70 +94,73 @@ public final class MinecraftUtil {
return RegistryKey.of(Registry.BIOME_KEY, identifier); return RegistryKey.of(Registry.BIOME_KEY, identifier);
} }
public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) { public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla,
VanillaBiomeProperties vanillaBiomeProperties) {
GenerationSettings.Builder generationSettings = new GenerationSettings.Builder(); GenerationSettings.Builder generationSettings = new GenerationSettings.Builder();
BiomeEffects.Builder effects = new BiomeEffects.Builder(); BiomeEffects.Builder effects = new BiomeEffects.Builder();
net.minecraft.world.biome.Biome.Builder builder = new Builder(); net.minecraft.world.biome.Biome.Builder builder = new Builder();
effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) effects.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()))
.waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor()))
.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) .fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())) .skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()))
.grassColorModifier( .grassColorModifier(
Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getEffects().getGrassColorModifier())); Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(),
vanilla.getEffects().getGrassColorModifier()));
if (vanillaBiomeProperties.getFoliageColor() == null) {
if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor); vanilla.getEffects().getFoliageColor().ifPresent(effects::foliageColor);
} else { } else {
effects.foliageColor(vanillaBiomeProperties.getFoliageColor()); effects.foliageColor(vanillaBiomeProperties.getFoliageColor());
} }
if (vanillaBiomeProperties.getGrassColor() == null) { if(vanillaBiomeProperties.getGrassColor() == null) {
vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor); vanilla.getEffects().getGrassColor().ifPresent(effects::grassColor);
} else { } else {
effects.grassColor(vanillaBiomeProperties.getGrassColor()); effects.grassColor(vanillaBiomeProperties.getGrassColor());
} }
if (vanillaBiomeProperties.getParticleConfig() == null) { if(vanillaBiomeProperties.getParticleConfig() == null) {
vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig); vanilla.getEffects().getParticleConfig().ifPresent(effects::particleConfig);
} else { } else {
effects.particleConfig(vanillaBiomeProperties.getParticleConfig()); effects.particleConfig(vanillaBiomeProperties.getParticleConfig());
} }
if (vanillaBiomeProperties.getLoopSound() == null) { if(vanillaBiomeProperties.getLoopSound() == null) {
vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound); vanilla.getEffects().getLoopSound().ifPresent(effects::loopSound);
} else { } else {
effects.loopSound(vanillaBiomeProperties.getLoopSound()); effects.loopSound(vanillaBiomeProperties.getLoopSound());
} }
if (vanillaBiomeProperties.getMoodSound() == null) { if(vanillaBiomeProperties.getMoodSound() == null) {
vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound); vanilla.getEffects().getMoodSound().ifPresent(effects::moodSound);
} else { } else {
effects.moodSound(vanillaBiomeProperties.getMoodSound()); effects.moodSound(vanillaBiomeProperties.getMoodSound());
} }
if (vanillaBiomeProperties.getAdditionsSound() == null) { if(vanillaBiomeProperties.getAdditionsSound() == null) {
vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound); vanilla.getEffects().getAdditionsSound().ifPresent(effects::additionsSound);
} else { } else {
effects.additionsSound(vanillaBiomeProperties.getAdditionsSound()); effects.additionsSound(vanillaBiomeProperties.getAdditionsSound());
} }
if (vanillaBiomeProperties.getMusic() == null) { if(vanillaBiomeProperties.getMusic() == null) {
vanilla.getEffects().getMusic().ifPresent(effects::music); vanilla.getEffects().getMusic().ifPresent(effects::music);
} else { } else {
effects.music(vanillaBiomeProperties.getMusic()); effects.music(vanillaBiomeProperties.getMusic());
} }
builder.precipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.getPrecipitation())); builder.precipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.getPrecipitation()));
builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getTemperature())); builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getTemperature()));
builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.getDownfall())); builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.getDownfall()));
builder.temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), ((BiomeAccessor)((Object)vanilla)).getWeather().temperatureModifier())); builder.temperatureModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(),
((BiomeAccessor) ((Object) vanilla)).getWeather().temperatureModifier()));
builder.spawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getSpawnSettings())); builder.spawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getSpawnSettings()));
return builder return builder

View File

@ -40,7 +40,7 @@ public class PresetUtil {
Registry<StructureSet> structureSetRegistry = BuiltinRegistries.STRUCTURE_SET; Registry<StructureSet> structureSetRegistry = BuiltinRegistries.STRUCTURE_SET;
Registry<NoiseParameters> noiseParametersRegistry = BuiltinRegistries.NOISE_PARAMETERS; Registry<NoiseParameters> noiseParametersRegistry = BuiltinRegistries.NOISE_PARAMETERS;
Registry<Biome> biomeRegistry = BuiltinRegistries.BIOME; Registry<Biome> biomeRegistry = BuiltinRegistries.BIOME;
RegistryEntry<DimensionType> theNetherDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.THE_NETHER); RegistryEntry<DimensionType> theNetherDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.THE_NETHER);
RegistryEntry<ChunkGeneratorSettings> RegistryEntry<ChunkGeneratorSettings>
netherChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.NETHER); netherChunkGeneratorSettings = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.NETHER);
@ -57,19 +57,19 @@ public class PresetUtil {
new NoiseChunkGenerator(structureSetRegistry, noiseParametersRegistry, new NoiseChunkGenerator(structureSetRegistry, noiseParametersRegistry,
new TheEndBiomeSource(biomeRegistry), new TheEndBiomeSource(biomeRegistry),
endChunkGeneratorSettings)); endChunkGeneratorSettings));
RegistryEntry<DimensionType> overworldDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.OVERWORLD); RegistryEntry<DimensionType> overworldDimensionType = dimensionTypeRegistry.getOrCreateEntry(DimensionTypes.OVERWORLD);
RegistryEntry<ChunkGeneratorSettings> overworld = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.OVERWORLD); RegistryEntry<ChunkGeneratorSettings> overworld = chunkGeneratorSettingsRegistry.getOrCreateEntry(ChunkGeneratorSettings.OVERWORLD);
Identifier generatorID = Identifier.of("terra", pack.getID().toLowerCase(Locale.ROOT) + "/" + pack.getNamespace().toLowerCase( Identifier generatorID = Identifier.of("terra", pack.getID().toLowerCase(Locale.ROOT) + "/" + pack.getNamespace().toLowerCase(
Locale.ROOT)); Locale.ROOT));
PRESETS.add(generatorID); PRESETS.add(generatorID);
TerraBiomeSource biomeSource = new TerraBiomeSource(biomeRegistry, pack); TerraBiomeSource biomeSource = new TerraBiomeSource(biomeRegistry, pack);
ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(structureSetRegistry, biomeSource, pack, overworld); ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(structureSetRegistry, biomeSource, pack, overworld);
DimensionOptions dimensionOptions = new DimensionOptions(overworldDimensionType, generator); DimensionOptions dimensionOptions = new DimensionOptions(overworldDimensionType, generator);
WorldPreset preset = new WorldPreset( WorldPreset preset = new WorldPreset(
Map.of( Map.of(

View File

@ -1,49 +1,49 @@
{ {
"required": true, "required": true,
"minVersion": "0.8", "minVersion": "0.8",
"package": "com.dfsek.terra.mod.mixin", "package": "com.dfsek.terra.mod.mixin",
"compatibilityLevel": "JAVA_17", "compatibilityLevel": "JAVA_17",
"mixins": [ "mixins": [
"access.BiomeAccessor", "access.BiomeAccessor",
"access.MobSpawnerLogicAccessor", "access.MobSpawnerLogicAccessor",
"access.StateAccessor", "access.StateAccessor",
"access.StructureAccessorAccessor", "access.StructureAccessorAccessor",
"access.VillagerTypeAccessor", "access.VillagerTypeAccessor",
"fix.BeeMoveGoalsUnsynchronizedRandomAccessFix", "fix.BeeMoveGoalsUnsynchronizedRandomAccessFix",
"fix.NetherFossilOptimization", "fix.NetherFossilOptimization",
"implementations.compat.GenerationSettingsFloraFeaturesMixin", "implementations.compat.GenerationSettingsFloraFeaturesMixin",
"implementations.terra.BiomeMixin", "implementations.terra.BiomeMixin",
"implementations.terra.HandleImplementationMixin", "implementations.terra.HandleImplementationMixin",
"implementations.terra.block.BlockMixin", "implementations.terra.block.BlockMixin",
"implementations.terra.block.entity.BlockEntityMixin", "implementations.terra.block.entity.BlockEntityMixin",
"implementations.terra.block.entity.LootableContainerBlockEntityMixin", "implementations.terra.block.entity.LootableContainerBlockEntityMixin",
"implementations.terra.block.entity.MobSpawnerBlockEntityMixin", "implementations.terra.block.entity.MobSpawnerBlockEntityMixin",
"implementations.terra.block.entity.SignBlockEntityMixin", "implementations.terra.block.entity.SignBlockEntityMixin",
"implementations.terra.block.state.BlockStateMixin", "implementations.terra.block.state.BlockStateMixin",
"implementations.terra.block.state.PropertyMixin", "implementations.terra.block.state.PropertyMixin",
"implementations.terra.chunk.ChunkRegionMixin", "implementations.terra.chunk.ChunkRegionMixin",
"implementations.terra.chunk.WorldChunkMixin", "implementations.terra.chunk.WorldChunkMixin",
"implementations.terra.chunk.data.ProtoChunkMixin", "implementations.terra.chunk.data.ProtoChunkMixin",
"implementations.terra.entity.EntityMixin", "implementations.terra.entity.EntityMixin",
"implementations.terra.entity.EntityTypeMixin", "implementations.terra.entity.EntityTypeMixin",
"implementations.terra.entity.PlayerEntityMixin", "implementations.terra.entity.PlayerEntityMixin",
"implementations.terra.entity.ServerCommandSourceMixin", "implementations.terra.entity.ServerCommandSourceMixin",
"implementations.terra.inventory.LockableContainerBlockEntityMixin", "implementations.terra.inventory.LockableContainerBlockEntityMixin",
"implementations.terra.inventory.item.ItemMixin", "implementations.terra.inventory.item.ItemMixin",
"implementations.terra.inventory.item.ItemStackMixin", "implementations.terra.inventory.item.ItemStackMixin",
"implementations.terra.inventory.meta.EnchantmentMixin", "implementations.terra.inventory.meta.EnchantmentMixin",
"implementations.terra.inventory.meta.ItemStackDamageableMixin", "implementations.terra.inventory.meta.ItemStackDamageableMixin",
"implementations.terra.inventory.meta.ItemStackMetaMixin", "implementations.terra.inventory.meta.ItemStackMetaMixin",
"implementations.terra.world.ChunkRegionMixin", "implementations.terra.world.ChunkRegionMixin",
"implementations.terra.world.ServerWorldMixin", "implementations.terra.world.ServerWorldMixin",
"lifecycle.DataPackContentsMixin" "lifecycle.DataPackContentsMixin"
], ],
"client": [ "client": [
], ],
"server": [ "server": [
], ],
"injectors": { "injectors": {
"defaultRequire": 1 "defaultRequire": 1
}, },
"refmap": "terra.common.refmap.json" "refmap": "terra.common.refmap.json"
} }

View File

@ -28,15 +28,15 @@ public abstract class LifecyclePlatform extends ModPlatform {
load(); load();
} }
public static void setServer(MinecraftServer server) {
LifecyclePlatform.server = server;
}
@Override @Override
public MinecraftServer getServer() { public MinecraftServer getServer() {
return server; return server;
} }
public static void setServer(MinecraftServer server) {
LifecyclePlatform.server = server;
}
@Override @Override
public boolean reload() { public boolean reload() {
getTerraConfig().load(this); getTerraConfig().load(this);

View File

@ -24,8 +24,10 @@ public class NoiseConfigMixin {
@Final @Final
private MultiNoiseSampler multiNoiseSampler; private MultiNoiseSampler multiNoiseSampler;
@Inject(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V", at = @At("TAIL")) @Inject(method = "<init>(Lnet/minecraft/world/gen/chunk/ChunkGeneratorSettings;Lnet/minecraft/util/registry/Registry;J)V",
private void mapMultiNoise(ChunkGeneratorSettings chunkGeneratorSettings, Registry<DoublePerlinNoiseSampler.NoiseParameters> noiseRegistry, long seed, CallbackInfo ci) { at = @At("TAIL"))
private void mapMultiNoise(ChunkGeneratorSettings chunkGeneratorSettings,
Registry<DoublePerlinNoiseSampler.NoiseParameters> noiseRegistry, long seed, CallbackInfo ci) {
SeedHack.register(multiNoiseSampler, seed); SeedHack.register(multiNoiseSampler, seed);
} }
} }

Some files were not shown because too many files have changed in this diff Show More