From cbc91f45237595ca8d04c0e95881ed027d11b766 Mon Sep 17 00:00:00 2001 From: Aleksey Date: Fri, 18 Jun 2021 15:08:31 +0300 Subject: [PATCH 0001/1033] Start update --- build.gradle | 10 ++++---- gradle.properties | 8 +++---- gradle/wrapper/gradle-wrapper.properties | 2 +- .../blockentities/BaseSignBlockEntity.java | 6 +++-- .../blockentities/DynamicBlockEntityType.java | 23 +++++++++++++++---- .../java/ru/bclib/blocks/BaseSignBlock.java | 12 +++------- .../render/BaseChestBlockEntityRenderer.java | 2 +- .../render/BaseSignBlockEntityRenderer.java | 2 +- .../java/ru/bclib/items/BaseBucketItem.java | 7 +++--- 9 files changed, 42 insertions(+), 30 deletions(-) diff --git a/build.gradle b/build.gradle index 843c4bb2..0f975a40 100644 --- a/build.gradle +++ b/build.gradle @@ -7,12 +7,12 @@ buildscript { plugins { id 'idea' id 'eclipse' - id 'fabric-loom' version '0.7-SNAPSHOT' + id 'fabric-loom' version '0.8-SNAPSHOT' id 'maven-publish' } -sourceCompatibility = JavaVersion.VERSION_1_8 -targetCompatibility = JavaVersion.VERSION_1_8 +sourceCompatibility = JavaVersion.VERSION_16 +targetCompatibility = JavaVersion.VERSION_16 archivesBaseName = project.archives_base_name version = project.mod_version @@ -20,7 +20,7 @@ group = project.maven_group repositories { maven { url "https://maven.dblsaiko.net/" } - maven { url "http://server.bbkr.space:8081/artifactory/libs-release/" } + maven { url "https://server.bbkr.space:8081/artifactory/libs-release/" } maven { url "https://maven.fabricmc.net/" } maven { url 'https://maven.blamejared.com' } maven { url "https://maven.shedaniel.me/" } @@ -33,7 +33,7 @@ dependencies { modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - useApi "vazkii.patchouli:Patchouli:1.16.4-${project.patchouli_version}" + //useApi "vazkii.patchouli:Patchouli:1.16.4-${project.patchouli_version}" } def useOptional(String dep) { diff --git a/gradle.properties b/gradle.properties index c43bdde4..cf464a7e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,9 +3,9 @@ org.gradle.jvmargs=-Xmx2G # Fabric Properties # check these on https://fabricmc.net/use -minecraft_version=1.16.5 -yarn_mappings=6 -loader_version=0.11.3 +minecraft_version= 1.17 +yarn_mappings= 6 +loader_version= 0.11.6 # Mod Properties mod_version = 0.1.38 @@ -15,4 +15,4 @@ archives_base_name = bclib # Dependencies # currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api patchouli_version = 50-FABRIC -fabric_version = 0.32.9+1.16 +fabric_version = 0.35.2+1.17 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 442d9132..69a97150 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java index 90bf2a21..64a9b75f 100644 --- a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java @@ -1,12 +1,14 @@ package ru.bclib.blockentities; +import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import ru.bclib.registry.BaseBlockEntities; public class BaseSignBlockEntity extends SignBlockEntity { - public BaseSignBlockEntity() { - super(); + public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) { + super(blockPos, blockState); } @Override diff --git a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java index 0b476594..abe9ce94 100644 --- a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java +++ b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java @@ -6,24 +6,39 @@ import java.util.function.Supplier; import com.google.common.collect.Sets; +import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; public class DynamicBlockEntityType extends BlockEntityType { private final Set validBlocks = Sets.newHashSet(); + private final BlockEntitySupplier factory; - public DynamicBlockEntityType(Supplier supplier) { - super(supplier, Collections.emptySet(), null); + public DynamicBlockEntityType(BlockEntitySupplier supplier) { + super(null, Collections.emptySet(), null); + this.factory = supplier; } @Override - public boolean isValid(Block block) { - return validBlocks.contains(block); + @Nullable public T create(BlockPos blockPos, BlockState blockState) { + return factory.create(blockPos, blockState); + } + + @Override + public boolean isValid(BlockState blockState) { + return validBlocks.contains(blockState.getBlock()); } public void registerBlock(Block block) { validBlocks.add(block); } + + @FunctionalInterface + interface BlockEntitySupplier { + T create(BlockPos blockPos, BlockState blockState); + } } diff --git a/src/main/java/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index f762f22d..3521f67c 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -75,8 +75,8 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe } @Override - public BlockEntity newBlockEntity(BlockGetter world) { - return new BaseSignBlockEntity(); + public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { + return new BaseSignBlockEntity(blockPos, blockState); } @Override @@ -85,7 +85,7 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe BaseSignBlockEntity sign = (BaseSignBlockEntity) world.getBlockEntity(pos); if (sign != null) { if (!world.isClientSide) { - sign.setAllowedPlayerEditor((Player) placer); + sign.setAllowedPlayerEditor(placer.getUUID()); ((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos)); } else { sign.setEditable(true); @@ -166,12 +166,6 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe return Collections.singletonList(new ItemStack(this)); } - @Override - public Fluid takeLiquid(LevelAccessor world, BlockPos pos, BlockState state) { - // TODO Auto-generated method stub - return super.takeLiquid(world, pos, state); - } - @Override public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { // TODO Auto-generated method stub diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 3626e902..81459f8c 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -34,7 +34,7 @@ import net.minecraft.world.level.block.state.properties.ChestType; import ru.bclib.blockentities.BaseChestBlockEntity; @Environment(EnvType.CLIENT) -public class BaseChestBlockEntityRenderer extends BlockEntityRenderer { +public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); private static final RenderType[] defaultLayer; diff --git a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java index 6ef7e419..33697f60 100644 --- a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java @@ -29,7 +29,7 @@ import net.minecraft.world.level.block.state.properties.WoodType; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.blocks.BaseSignBlock; -public class BaseSignBlockEntityRenderer extends BlockEntityRenderer { +public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); private static final RenderType defaultLayer; private final SignModel model = new SignRenderer.SignModel(); diff --git a/src/main/java/ru/bclib/items/BaseBucketItem.java b/src/main/java/ru/bclib/items/BaseBucketItem.java index e33ac83a..fae47053 100644 --- a/src/main/java/ru/bclib/items/BaseBucketItem.java +++ b/src/main/java/ru/bclib/items/BaseBucketItem.java @@ -1,13 +1,14 @@ package ru.bclib.items; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.EntityType; -import net.minecraft.world.item.FishBucketItem; +import net.minecraft.world.item.MobBucketItem; import net.minecraft.world.level.material.Fluids; import ru.bclib.client.models.ItemModelProvider; -public class BaseBucketItem extends FishBucketItem implements ItemModelProvider { +public class BaseBucketItem extends MobBucketItem implements ItemModelProvider { public BaseBucketItem(EntityType type, FabricItemSettings settings) { - super(type, Fluids.WATER, settings.stacksTo(1)); + super(type, Fluids.WATER, SoundEvents.BUCKET_EMPTY_FISH, settings.stacksTo(1)); } } From 849b28f7d3d0a9e747e060a4595c9969c19d8b99 Mon Sep 17 00:00:00 2001 From: Aleksey Date: Fri, 18 Jun 2021 15:38:18 +0300 Subject: [PATCH 0002/1033] Try to fix NBTStructureFeature... --- .../ru/bclib/world/features/NBTStructureFeature.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index 80d94729..598a3078 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -17,11 +17,13 @@ import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderConfiguration; +import net.minecraft.world.phys.Vec3; import ru.bclib.api.BiomeAPI; import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; @@ -76,7 +78,11 @@ public abstract class NBTStructureFeature extends DefaultFeature { } @Override - public boolean place(WorldGenLevel world, ChunkGenerator chunkGenerator, Random random, BlockPos center, NoneFeatureConfiguration featureConfig) { + public boolean place(FeaturePlaceContext context) { + WorldGenLevel world = context.level(); + Random random = context.random(); + BlockPos center = context.origin(); + center = new BlockPos(((center.getX() >> 4) << 4) | 8, 128, ((center.getZ() >> 4) << 4) | 8); center = getGround(world, center); @@ -88,14 +94,14 @@ public abstract class NBTStructureFeature extends DefaultFeature { StructureTemplate structure = getStructure(world, center, random); Rotation rotation = getRotation(world, center, random); Mirror mirror = getMirror(world, center, random); - BlockPos offset = StructureTemplate.transform(structure.getSize(), mirror, rotation, BlockPos.ZERO); + BlockPos offset = StructureTemplate.transform(new BlockPos(structure.getSize()), mirror, rotation, BlockPos.ZERO); center = center.offset(0, getYOffset(structure, world, center, random) + 0.5, 0); BoundingBox bounds = makeBox(center); StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); addStructureData(placementData); center = center.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); - structure.placeInWorldChunk(world, center, placementData, random); + structure.placeInWorld(world, center, placementData, random); TerrainMerge merge = getTerrainMerge(world, center, random); int x1 = center.getX(); From 6e601179c56dbcc0b7383314604570463f046195 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 20 Jun 2021 15:35:43 +0300 Subject: [PATCH 0003/1033] Fixed biome def --- src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index 22c75311..143751bf 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -29,6 +29,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.GenerationStep.Carving; import net.minecraft.world.level.levelgen.GenerationStep.Decoration; +import net.minecraft.world.level.levelgen.carver.CarverConfiguration; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; @@ -346,7 +347,7 @@ public class BCLBiomeDef { private static final class CarverInfo { Carving carverStep; - ConfiguredWorldCarver carver; + ConfiguredWorldCarver carver; } public ResourceLocation getID() { @@ -365,7 +366,7 @@ public class BCLBiomeDef { return edgeSize; } - public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { + public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { CarverInfo info = new CarverInfo(); info.carverStep = carverStep; info.carver = carver; From 553afd872af2ad2fba1180b06905e2b74453132f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 20 Jun 2021 16:25:59 +0300 Subject: [PATCH 0004/1033] Feature update --- .../common/FeatureDecoratorsAccessor.java | 18 +++++++++++++ .../bclib/world/features/BCLDecorators.java | 27 +++++++++++++++++++ .../ru/bclib/world/features/BCLFeature.java | 22 +++++++++------ 3 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java create mode 100644 src/main/java/ru/bclib/world/features/BCLDecorators.java diff --git a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java new file mode 100644 index 00000000..d54b39cc --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java @@ -0,0 +1,18 @@ +package ru.bclib.mixin.common; + +import net.minecraft.data.worldgen.Features; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.block.ComposterBlock; +import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.Map; + +@Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators") +public interface FeatureDecoratorsAccessor { + @Accessor("HEIGHTMAP_SQUARE") + ConfiguredDecorator bcl_getHeightmapSquare(); +} diff --git a/src/main/java/ru/bclib/world/features/BCLDecorators.java b/src/main/java/ru/bclib/world/features/BCLDecorators.java new file mode 100644 index 00000000..b302b031 --- /dev/null +++ b/src/main/java/ru/bclib/world/features/BCLDecorators.java @@ -0,0 +1,27 @@ +package ru.bclib.world.features; + +import net.minecraft.data.worldgen.Features; +import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator; +import ru.bclib.BCLib; + +import java.lang.reflect.Field; + +public class BCLDecorators { + public static final ConfiguredDecorator HEIGHTMAP_SQUARE; + + private static final ConfiguredDecorator getDecorator(Field[] fields, int index) { + try { + return (ConfiguredDecorator) fields[index].get(null); + } + catch (IllegalAccessException e) { + BCLib.LOGGER.error(e.getLocalizedMessage()); + return null; + } + } + + static { + Class[] classes = Features.class.getDeclaredClasses(); + Field[] fields = classes[1].getDeclaredFields(); // Decorators class + HEIGHTMAP_SQUARE = getDecorator(fields, 27); + } +} diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index d8d3483e..2227cddd 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -4,9 +4,11 @@ import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; import net.minecraft.data.worldgen.Features; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.VerticalAnchor; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.CountConfiguration; @@ -17,12 +19,16 @@ import net.minecraft.world.level.levelgen.feature.configurations.RangeDecoratorC import net.minecraft.world.level.levelgen.placement.ChanceDecoratorConfiguration; import net.minecraft.world.level.levelgen.placement.FeatureDecorator; import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest; +import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; +import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; +import ru.bclib.api.TagAPI; public class BCLFeature { - private Feature feature; + private static final RuleTest ANY_TERRAIN = new TagMatchTest(TagAPI.GEN_TERRAIN); private ConfiguredFeature featureConfigured; private GenerationStep.Decoration featureStep; - + private Feature feature; + public BCLFeature(Feature feature, ConfiguredFeature configuredFeature, GenerationStep.Decoration featureStep) { this.featureConfigured = configuredFeature; this.featureStep = featureStep; @@ -36,7 +42,7 @@ public class BCLFeature { } public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(Features.Decorators.HEIGHTMAP_SQUARE).countRandom(density); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(BCLDecorators.HEIGHTMAP_SQUARE).countRandom(density); return new BCLFeature(id, feature, GenerationStep.Decoration.VEGETAL_DECORATION, configured); } @@ -46,17 +52,17 @@ public class BCLFeature { } public static BCLFeature makeLakeFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.WATER_LAKE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.LAKES, configured); } public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, int veins, int veinSize, int offset, int minY, int maxY) { OreConfiguration featureConfig = new OreConfiguration(new BlockMatchTest(Blocks.END_STONE), blockOre.defaultBlockState(), veinSize); - RangeDecoratorConfiguration rangeDecorator = new RangeDecoratorConfiguration(offset, minY, maxY); + OreConfiguration config = new OreConfiguration(ANY_TERRAIN, blockOre.defaultBlockState(), 33); ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig) - .decorated(FeatureDecorator.RANGE.configured(rangeDecorator)) - .squared() - .count(veins); + .rangeUniform(VerticalAnchor.absolute(minY), VerticalAnchor.absolute(maxY)) + .squared() + .count(veins); return new BCLFeature(Feature.ORE, Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), GenerationStep.Decoration.UNDERGROUND_ORES); } From 508ae317fe29cc44acba7ac3076820c2066addfc Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 20 Jun 2021 16:29:45 +0300 Subject: [PATCH 0005/1033] Rendering update --- .../mixin/client/BackgroundRendererMixin.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index ca1076be..10495c5a 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -1,5 +1,6 @@ package ru.bclib.mixin.client; +import net.minecraft.world.level.material.FogType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -41,8 +42,8 @@ public class BackgroundRendererMixin { @Inject(method = "setupColor", at = @At("RETURN")) private static void bcl_onRender(Camera camera, float tickDelta, ClientLevel world, int i, float f, CallbackInfo info) { - FluidState fluidState = camera.getFluidInCamera(); - if (fluidState.isEmpty() && world.dimension().equals(Level.END)) { + FogType fogType = camera.getFluidInCamera(); + if (fogType != FogType.WATER && world.dimension().equals(Level.END)) { Entity entity = camera.getEntity(); boolean skip = false; if (entity instanceof LivingEntity) { @@ -62,10 +63,10 @@ public class BackgroundRendererMixin { } @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) - private static void bcl_fogDensity(Camera camera, FogRenderer.FogMode fogType, float viewDistance, boolean thickFog, CallbackInfo info) { + private static void bcl_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { Entity entity = camera.getEntity(); - FluidState fluidState = camera.getFluidInCamera(); - if (fluidState.isEmpty()) { + FogType fogType = camera.getFluidInCamera(); + if (fogType != FogType.WATER) { float fog = bcl_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); BackgroundInfo.fogDensity = fog; float start = viewDistance * 0.75F / fog; @@ -93,10 +94,8 @@ public class BackgroundRendererMixin { } } - RenderSystem.fogStart(start); - RenderSystem.fogEnd(end); - RenderSystem.fogMode(GlStateManager.FogMode.LINEAR); - RenderSystem.setupNvFogDistance(); + RenderSystem.setShaderFogStart(start); + RenderSystem.setShaderFogEnd(end); info.cancel(); } } From d7b82c3a17ea109a7187d2c2e51175667af0c345 Mon Sep 17 00:00:00 2001 From: Aleksey Date: Tue, 22 Jun 2021 13:42:26 +0300 Subject: [PATCH 0006/1033] Update gradle-wrapper.properties --- gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 69a97150..f371643e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From dccb49f51c4e50b396c98888af41b683e3c91cfd Mon Sep 17 00:00:00 2001 From: Aleksey Date: Tue, 22 Jun 2021 14:04:03 +0300 Subject: [PATCH 0007/1033] Update gradle.properties --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 66f3a9d2..e1474630 100644 --- a/gradle.properties +++ b/gradle.properties @@ -15,4 +15,4 @@ archives_base_name = bclib # Dependencies # currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api patchouli_version = 50-FABRIC -fabric_version = 0.35.2+1.17 +fabric_version = 0.36.0+1.17 From 7d7945222073202e75cd2c3c9b545f51956351ae Mon Sep 17 00:00:00 2001 From: Aleksey Date: Tue, 22 Jun 2021 16:05:46 +0300 Subject: [PATCH 0008/1033] Various fixes --- .../blockentities/BaseBarrelBlockEntity.java | 18 +++++------ .../blockentities/BaseChestBlockEntity.java | 6 ++-- .../blockentities/BaseFurnaceBlockEntity.java | 6 ++-- .../blockentities/DynamicBlockEntityType.java | 1 + .../java/ru/bclib/blocks/BaseAnvilBlock.java | 5 +-- .../ru/bclib/blocks/BaseAttachedBlock.java | 7 ++-- .../java/ru/bclib/blocks/BaseBarrelBlock.java | 5 +-- src/main/java/ru/bclib/blocks/BaseBlock.java | 1 + .../ru/bclib/blocks/BaseBlockWithEntity.java | 6 ++-- .../java/ru/bclib/blocks/BaseButtonBlock.java | 1 + .../java/ru/bclib/blocks/BaseChainBlock.java | 5 +-- .../java/ru/bclib/blocks/BaseChestBlock.java | 9 +++--- .../ru/bclib/blocks/BaseComposterBlock.java | 3 +- .../bclib/blocks/BaseCraftingTableBlock.java | 1 + .../java/ru/bclib/blocks/BaseCropBlock.java | 3 +- .../java/ru/bclib/blocks/BaseDoorBlock.java | 1 + .../ru/bclib/blocks/BaseDoublePlantBlock.java | 3 +- .../java/ru/bclib/blocks/BaseFenceBlock.java | 1 + .../ru/bclib/blocks/BaseFurnaceBlock.java | 7 ++-- .../java/ru/bclib/blocks/BaseGateBlock.java | 1 + .../java/ru/bclib/blocks/BaseLadderBlock.java | 20 ++++++------ .../java/ru/bclib/blocks/BaseLeavesBlock.java | 9 +++--- .../ru/bclib/blocks/BaseMetalBarsBlock.java | 3 +- .../java/ru/bclib/blocks/BaseOreBlock.java | 11 ++----- .../java/ru/bclib/blocks/BasePlantBlock.java | 3 +- .../bclib/blocks/BasePlantWithAgeBlock.java | 3 +- .../bclib/blocks/BasePressurePlateBlock.java | 1 + .../bclib/blocks/BaseRotatedPillarBlock.java | 3 +- .../java/ru/bclib/blocks/BaseSignBlock.java | 1 + .../java/ru/bclib/blocks/BaseSlabBlock.java | 1 + .../java/ru/bclib/blocks/BaseStairsBlock.java | 1 + .../bclib/blocks/BaseStripableLogBlock.java | 5 +-- .../ru/bclib/blocks/BaseTerrainBlock.java | 2 +- .../ru/bclib/blocks/BaseTrapdoorBlock.java | 1 + .../blocks/BaseUnderwaterWallPlantBlock.java | 1 + .../java/ru/bclib/blocks/BaseVineBlock.java | 3 +- .../java/ru/bclib/blocks/BaseWallBlock.java | 1 + .../ru/bclib/blocks/BaseWallPlantBlock.java | 2 ++ .../bclib/blocks/BaseWeightedPlateBlock.java | 1 + .../ru/bclib/blocks/FeatureSaplingBlock.java | 2 ++ .../ru/bclib/blocks/SimpleLeavesBlock.java | 4 +-- .../java/ru/bclib/blocks/StalactiteBlock.java | 1 + .../ru/bclib/blocks/StripableBarkBlock.java | 5 +-- .../ru/bclib/blocks/UnderwaterPlantBlock.java | 3 +- .../blocks/UnderwaterPlantWithAgeBlock.java | 1 + .../ru/bclib/blocks/UpDownPlantBlock.java | 3 +- .../render/BaseChestBlockEntityRenderer.java | 32 +++++++------------ .../java/ru/bclib/items/BaseDrinkItem.java | 7 ++-- .../java/ru/bclib/items/BaseSpawnEggItem.java | 3 +- .../ru/bclib/registry/BaseBlockEntities.java | 3 +- .../java/ru/bclib/registry/ItemsRegistry.java | 3 +- .../world/structures/StructureWorld.java | 2 +- 52 files changed, 130 insertions(+), 101 deletions(-) diff --git a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java index 488a86eb..c181a7a7 100644 --- a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java @@ -1,5 +1,6 @@ package ru.bclib.blockentities; +import net.minecraft.core.BlockPos; import net.minecraft.core.NonNullList; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; @@ -26,13 +27,13 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { private NonNullList inventory; private int viewerCount; - private BaseBarrelBlockEntity(BlockEntityType type) { - super(type); + private BaseBarrelBlockEntity(BlockEntityType type, BlockPos blockPos, BlockState blockState) { + super(type, blockPos, blockState); this.inventory = NonNullList.withSize(27, ItemStack.EMPTY); } - public BaseBarrelBlockEntity() { - this(BaseBlockEntities.BARREL); + public BaseBarrelBlockEntity(BlockPos blockPos, BlockState blockState) { + this(BaseBlockEntities.BARREL, blockPos, blockState); } public CompoundTag save(CompoundTag tag) { @@ -44,8 +45,8 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { return tag; } - public void load(BlockState state, CompoundTag tag) { - super.load(state, tag); + public void load(CompoundTag tag) { + super.load(tag); this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); if (!this.tryLoadLootTable(tag)) { ContainerHelper.loadAllItems(tag, this.inventory); @@ -97,10 +98,7 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { public void tick() { if (level != null) { - int x = worldPosition.getX(); - int y = worldPosition.getY(); - int z = worldPosition.getZ(); - viewerCount = ChestBlockEntity.getOpenCount(level, this, x, y, z); + viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition); if (viewerCount > 0) { scheduleUpdate(); } else { diff --git a/src/main/java/ru/bclib/blockentities/BaseChestBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseChestBlockEntity.java index 2d1ed5d4..97581739 100644 --- a/src/main/java/ru/bclib/blockentities/BaseChestBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseChestBlockEntity.java @@ -1,10 +1,12 @@ package ru.bclib.blockentities; +import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.ChestBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import ru.bclib.registry.BaseBlockEntities; public class BaseChestBlockEntity extends ChestBlockEntity { - public BaseChestBlockEntity() { - super(BaseBlockEntities.CHEST); + public BaseChestBlockEntity(BlockPos blockPos, BlockState blockState) { + super(BaseBlockEntities.CHEST, blockPos, blockState); } } diff --git a/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java index 7413bd7c..fa681007 100644 --- a/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java @@ -1,5 +1,6 @@ package ru.bclib.blockentities; +import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.entity.player.Inventory; @@ -7,11 +8,12 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.FurnaceMenu; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import ru.bclib.registry.BaseBlockEntities; public class BaseFurnaceBlockEntity extends AbstractFurnaceBlockEntity { - public BaseFurnaceBlockEntity() { - super(BaseBlockEntities.FURNACE, RecipeType.SMELTING); + public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) { + super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING); } protected Component getDefaultName() { diff --git a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java index abe9ce94..2f992c86 100644 --- a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java +++ b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java @@ -38,6 +38,7 @@ public class DynamicBlockEntityType extends BlockEntityTy } @FunctionalInterface + public interface BlockEntitySupplier { T create(BlockPos blockPos, BlockState blockState); } diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index cb17045e..5dafc0d5 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -35,7 +35,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; public BaseAnvilBlock(MaterialColor color) { - super(FabricBlockSettings.copyOf(Blocks.ANVIL).materialColor(color)); + super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color)); } @Override @@ -43,8 +43,9 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro super.createBlockStateDefinition(builder); builder.add(DESTRUCTION); } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack dropStack = new ItemStack(this); int destruction = state.getValue(DESTRUCTION); diff --git a/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java index 9d021fd0..ecf12d48 100644 --- a/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java @@ -16,12 +16,13 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.DirectionProperty; import ru.bclib.util.BlocksHelper; +@SuppressWarnings("deprecation") public abstract class BaseAttachedBlock extends BaseBlockNotFull { public static final DirectionProperty FACING = BlockStateProperties.FACING; public BaseAttachedBlock(Properties settings) { super(settings); - this.registerDefaultState(this.defaultBlockState().setValue(FACING, Direction.UP)); + registerDefaultState(defaultBlockState().setValue(FACING, Direction.UP)); } @Override @@ -31,7 +32,7 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { @Override public BlockState getStateForPlacement(BlockPlaceContext ctx) { - BlockState blockState = this.defaultBlockState(); + BlockState blockState = defaultBlockState(); LevelReader worldView = ctx.getLevel(); BlockPos blockPos = ctx.getClickedPos(); Direction[] directions = ctx.getNearestLookingDirections(); @@ -47,7 +48,7 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - Direction direction = (Direction) state.getValue(FACING); + Direction direction = state.getValue(FACING); BlockPos blockPos = pos.relative(direction.getOpposite()); return canSupportCenter(world, blockPos, direction) || world.getBlockState(blockPos).is(BlockTags.LEAVES); } diff --git a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java index af93693a..b36f8843 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java @@ -46,11 +46,12 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { } @Override - public BlockEntity newBlockEntity(BlockGetter world) { - return BaseBlockEntities.BARREL.create(); + public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { + return BaseBlockEntities.BARREL.create(blockPos, blockState); } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { List drop = super.getDrops(state, builder); drop.add(new ItemStack(this.asItem())); diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index 274261a5..97878a79 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -17,6 +17,7 @@ public class BaseBlock extends Block implements BlockModelProvider { } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java index fa731e03..718a58f7 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java +++ b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java @@ -3,6 +3,7 @@ package ru.bclib.blocks; import java.util.Collections; import java.util.List; +import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.BaseEntityBlock; @@ -16,11 +17,12 @@ public class BaseBlockWithEntity extends BaseEntityBlock { } @Override - public BlockEntity newBlockEntity(BlockGetter world) { + public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return null; } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java index 4d2c5812..5f8642ce 100644 --- a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java @@ -35,6 +35,7 @@ public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelP } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseChainBlock.java b/src/main/java/ru/bclib/blocks/BaseChainBlock.java index f8ae7090..c2a14fe3 100644 --- a/src/main/java/ru/bclib/blocks/BaseChainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChainBlock.java @@ -29,10 +29,11 @@ import ru.bclib.interfaces.IRenderTyped; public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped { public BaseChainBlock(MaterialColor color) { - super(FabricBlockSettings.copyOf(Blocks.CHAIN).materialColor(color)); + super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseChestBlock.java b/src/main/java/ru/bclib/blocks/BaseChestBlock.java index 46819d5e..2b89b5d2 100644 --- a/src/main/java/ru/bclib/blocks/BaseChestBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChestBlock.java @@ -3,6 +3,7 @@ package ru.bclib.blocks; import java.util.List; import java.util.Optional; +import net.minecraft.core.BlockPos; import org.jetbrains.annotations.Nullable; import net.fabricmc.api.EnvType; @@ -33,12 +34,12 @@ public class BaseChestBlock extends ChestBlock implements BlockModelProvider { } @Override - public BlockEntity newBlockEntity(BlockGetter world) - { - return BaseBlockEntities.CHEST.create(); + public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { + return BaseBlockEntities.CHEST.create(blockPos, blockState); } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { List drop = super.getDrops(state, builder); diff --git a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java index 09861f07..faecc6e5 100644 --- a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java @@ -28,8 +28,9 @@ public class BaseComposterBlock extends ComposterBlock implements BlockModelProv public BaseComposterBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this.asItem())); } diff --git a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java index 4cd02952..570758fe 100644 --- a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java @@ -28,6 +28,7 @@ public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockM } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this.asItem())); } diff --git a/src/main/java/ru/bclib/blocks/BaseCropBlock.java b/src/main/java/ru/bclib/blocks/BaseCropBlock.java index 703ffaab..e395d338 100644 --- a/src/main/java/ru/bclib/blocks/BaseCropBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCropBlock.java @@ -106,8 +106,9 @@ public class BaseCropBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return state.getValue(AGE) < 3; } - + @Override + @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { super.tick(state, world, pos, random); if (isBonemealSuccess(world, random, pos, state) && random.nextInt(8) == 0) { diff --git a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java index f8594a4a..1c2c6245 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java @@ -36,6 +36,7 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { if (state.getValue(HALF) == DoubleBlockHalf.LOWER) return Collections.singletonList(new ItemStack(this.asItem())); diff --git a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index 90ec93a2..73f0ed6c 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -38,6 +38,7 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +@SuppressWarnings("deprecation") public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); public static final IntegerProperty ROTATION = BlockProperties.ROTATION; @@ -110,7 +111,7 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I } ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java index 417f50cb..85adff6e 100644 --- a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java @@ -35,6 +35,7 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index e109062e..2b93d9a7 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -42,8 +42,8 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider } @Override - public BlockEntity newBlockEntity(BlockGetter world) { - return new BaseFurnaceBlockEntity(); + public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { + return new BaseFurnaceBlockEntity(blockPos, blockState); } @Override @@ -95,8 +95,9 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { List drop = Lists.newArrayList(new ItemStack(this)); BlockEntity blockEntity = builder.getOptionalParameter(LootContextParams.BLOCK_ENTITY); diff --git a/src/main/java/ru/bclib/blocks/BaseGateBlock.java b/src/main/java/ru/bclib/blocks/BaseGateBlock.java index b4393ea9..d765ca2d 100644 --- a/src/main/java/ru/bclib/blocks/BaseGateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseGateBlock.java @@ -33,6 +33,7 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index 84a396cd..93939d8f 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -39,6 +39,7 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +@SuppressWarnings("deprecation") public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; @@ -57,17 +58,14 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B stateManager.add(WATERLOGGED); } + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - switch (state.getValue(FACING)) { - case SOUTH: - return SOUTH_SHAPE; - case WEST: - return WEST_SHAPE; - case EAST: - return EAST_SHAPE; - default: - return NORTH_SHAPE; - } + return switch (state.getValue(FACING)) { + case SOUTH -> SOUTH_SHAPE; + case WEST -> WEST_SHAPE; + case EAST -> EAST_SHAPE; + default -> NORTH_SHAPE; + }; } private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) { @@ -78,7 +76,7 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = state.getValue(FACING); - return this.canPlaceOn(world, pos.relative(direction.getOpposite()), direction); + return canPlaceOn(world, pos.relative(direction.getOpposite()), direction); } @Override diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index d7a7b1cb..4e644f8e 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -29,7 +29,7 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, public BaseLeavesBlock(Block sapling, MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) - .materialColor(color) + .mapColor(color) .breakByTool(FabricToolTags.HOES) .breakByTool(FabricToolTags.SHEARS) .breakByHand(true) @@ -41,7 +41,7 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) - .materialColor(color) + .mapColor(color) .luminance(light) .breakByTool(FabricToolTags.HOES) .breakByTool(FabricToolTags.SHEARS) @@ -55,12 +55,13 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null) { - if (tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Collections.singletonList(new ItemStack(this)); } int fortune = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); diff --git a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java index 86d5a231..d4ecb9bf 100644 --- a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java @@ -34,6 +34,7 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } @@ -99,7 +100,7 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi @Environment(EnvType.CLIENT) public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - if (direction.getAxis().isVertical() && stateFrom.getBlock().is(this) && !stateFrom.equals(state)) { + if (direction.getAxis().isVertical() && stateFrom.getBlock() == this && !stateFrom.equals(state)) { return false; } return super.skipRendering(state, stateFrom, direction); diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index 5d5cc847..9f0bfaf2 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -8,6 +8,7 @@ import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; +import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; @@ -26,26 +27,20 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final Item dropItem; private final int minCount; private final int maxCount; - private final int experience; public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) .hardness(3F) .resistance(9F) .requiresCorrectToolForDrops() - .sound(SoundType.STONE)); + .sound(SoundType.STONE), UniformInt.of(1, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; - this.experience = experience; - } - - @Override - protected int xpOnDrop(Random random) { - return this.experience > 0 ? random.nextInt(experience) + 1 : 0; } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null && tool.isCorrectToolForDrops(state)) { diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index 2d83be66..b3181e9d 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -33,6 +33,7 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +@SuppressWarnings("deprecation") public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); @@ -97,7 +98,7 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java index a8c31d54..e78a0189 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java @@ -53,8 +53,9 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override + @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { super.tick(state, world, pos, random); if (random.nextInt(8) == 0) { diff --git a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java index 0d6152ca..9cd483f4 100644 --- a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java @@ -33,6 +33,7 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java index 003408ba..e5d3af50 100644 --- a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java @@ -30,8 +30,9 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM public BaseRotatedPillarBlock(Block block) { super(FabricBlockSettings.copyOf(block)); } - + @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index a650f14e..5eeb16a0 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -48,6 +48,7 @@ import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ISpetialItem; import ru.bclib.util.BlocksHelper; +@SuppressWarnings("deprecation") public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem { public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); diff --git a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java index 43edec66..49a4af52 100644 --- a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java @@ -35,6 +35,7 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java index ce2571c8..2f057e78 100644 --- a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java @@ -37,6 +37,7 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java index f956e04d..a552e9fc 100644 --- a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java @@ -20,13 +20,14 @@ public class BaseStripableLogBlock extends BaseRotatedPillarBlock { private final Block striped; public BaseStripableLogBlock(MaterialColor color, Block striped) { - super(FabricBlockSettings.copyOf(striped).materialColor(color)); + super(FabricBlockSettings.copyOf(striped).mapColor(color)); this.striped = striped; } @Override + @SuppressWarnings("deprecation") public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (player.getMainHandItem().getItem().is(FabricToolTags.AXES)) { + if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index b11b25f1..fd0537c1 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -67,7 +67,7 @@ public class BaseTerrainBlock extends BaseBlock { @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (pathBlock != null && player.getMainHandItem().getItem().is(FabricToolTags.SHOVELS)) { + if (pathBlock != null && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlockAndUpdate(pos, pathBlock.defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java index 49ff777c..b0167f0e 100644 --- a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java @@ -34,6 +34,7 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java index 5ef38d66..2254146b 100644 --- a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java @@ -48,6 +48,7 @@ public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock im } @Override + @SuppressWarnings("deprecation") public FluidState getFluidState(BlockState state) { return Fluids.WATER.getSource(false); } diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 2ac699d3..108dc183 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -37,6 +37,7 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +@SuppressWarnings("deprecation") public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; private static final VoxelShape VOXEL_SHAPE = Block.box(2, 0, 2, 14, 16, 14); @@ -106,7 +107,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/BaseWallBlock.java b/src/main/java/ru/bclib/blocks/BaseWallBlock.java index 7d232a79..031f4d31 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallBlock.java @@ -36,6 +36,7 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java index d833e3fc..9adb0c91 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java @@ -113,11 +113,13 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { } @Override + @SuppressWarnings("deprecation") public BlockState rotate(BlockState state, Rotation rotation) { return BlocksHelper.rotateHorizontal(state, rotation, FACING); } @Override + @SuppressWarnings("deprecation") public BlockState mirror(BlockState state, Mirror mirror) { return BlocksHelper.mirrorHorizontal(state, mirror, FACING); } diff --git a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java index 744392ca..28bbe68e 100644 --- a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java @@ -33,6 +33,7 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement } @Override + @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 47a6974b..5f33bb0a 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Optional; import java.util.Random; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import org.jetbrains.annotations.Nullable; import net.fabricmc.api.EnvType; @@ -36,6 +37,7 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +@SuppressWarnings("deprecation") public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 6c1895e5..ac46338c 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -11,7 +11,7 @@ public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped public SimpleLeavesBlock(MaterialColor color) { super(FabricBlockSettings.of(Material.LEAVES) .strength(0.2F) - .materialColor(color) + .mapColor(color) .sound(SoundType.GRASS) .noOcclusion() .isValidSpawn((state, world, pos, type) -> false) @@ -22,7 +22,7 @@ public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped public SimpleLeavesBlock(MaterialColor color, int light) { super(FabricBlockSettings.of(Material.LEAVES) .luminance(light) - .materialColor(color) + .mapColor(color) .strength(0.2F) .sound(SoundType.GRASS) .noOcclusion() diff --git a/src/main/java/ru/bclib/blocks/StalactiteBlock.java b/src/main/java/ru/bclib/blocks/StalactiteBlock.java index 23add876..50401565 100644 --- a/src/main/java/ru/bclib/blocks/StalactiteBlock.java +++ b/src/main/java/ru/bclib/blocks/StalactiteBlock.java @@ -43,6 +43,7 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +@SuppressWarnings("deprecation") public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped { public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; diff --git a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java index c86c792a..d0195177 100644 --- a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java @@ -20,13 +20,14 @@ public class StripableBarkBlock extends BaseBarkBlock { private final Block striped; public StripableBarkBlock(MaterialColor color, Block striped) { - super(FabricBlockSettings.copyOf(striped).materialColor(color)); + super(FabricBlockSettings.copyOf(striped).mapColor(color)); this.striped = striped; } @Override + @SuppressWarnings("deprecation") public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (player.getMainHandItem().getItem().is(FabricToolTags.AXES)) { + if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index 171deae0..4d168107 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -37,6 +37,7 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +@SuppressWarnings("deprecation") public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); @@ -95,7 +96,7 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java index fb7870b8..8b6499a2 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java @@ -47,6 +47,7 @@ public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { } @Override + @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { super.tick(state, world, pos, random); if (isBonemealSuccess(world, random, pos, state)) { diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index 3d18763a..0773a45b 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -29,6 +29,7 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +@SuppressWarnings("deprecation") public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); @@ -71,7 +72,7 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRend @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem().is(FabricToolTags.SHEARS) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 81459f8c..064cb834 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -1,12 +1,9 @@ package ru.bclib.client.render; -import java.util.HashMap; - import com.google.common.collect.Maps; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.math.Vector3f; - import it.unimi.dsi.fastutil.floats.Float2FloatFunction; import it.unimi.dsi.fastutil.ints.Int2IntFunction; import net.fabricmc.api.EnvType; @@ -21,18 +18,15 @@ import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.AbstractChestBlock; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.ChestBlock; -import net.minecraft.world.level.block.DoubleBlockCombiner; +import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.DoubleBlockCombiner.NeighborCombineResult; import net.minecraft.world.level.block.entity.ChestBlockEntity; -import net.minecraft.world.level.block.entity.LidBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.ChestType; import ru.bclib.blockentities.BaseChestBlockEntity; +import java.util.HashMap; + @Environment(EnvType.CLIENT) public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); @@ -87,8 +81,8 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer abstractChestBlock = (AbstractChestBlock) block; @@ -107,7 +101,7 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer layers[ID_LEFT]; + case RIGHT -> layers[ID_RIGHT]; + default -> layers[ID_NORMAL]; + }; } public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) { diff --git a/src/main/java/ru/bclib/items/BaseDrinkItem.java b/src/main/java/ru/bclib/items/BaseDrinkItem.java index cf4b520d..bb2216f2 100644 --- a/src/main/java/ru/bclib/items/BaseDrinkItem.java +++ b/src/main/java/ru/bclib/items/BaseDrinkItem.java @@ -30,7 +30,7 @@ public class BaseDrinkItem extends ModelProviderItem { @Override public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { - return ItemUtils.useDrink(world, user, hand); + return ItemUtils.startUsingInstantly(world, user, hand); } @Override @@ -41,13 +41,12 @@ public class BaseDrinkItem extends ModelProviderItem { stack.setCount(count); } - if (user instanceof ServerPlayer) { - ServerPlayer serverPlayerEntity = (ServerPlayer) user; + if (user instanceof ServerPlayer serverPlayerEntity) { CriteriaTriggers.CONSUME_ITEM.trigger(serverPlayerEntity, stack); serverPlayerEntity.awardStat(Stats.ITEM_USED.get(this)); } - if (user instanceof Player && !((Player) user).abilities.instabuild) { + if (user instanceof Player && !((Player) user).getAbilities().instabuild) { stack.shrink(1); } diff --git a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java index ec7b63f3..7badc6f9 100644 --- a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java +++ b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java @@ -7,6 +7,7 @@ import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; import net.minecraft.world.item.SpawnEggItem; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ItemModelProvider; @@ -14,7 +15,7 @@ import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { - public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { + public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { super(type, primaryColor, secondaryColor, settings); } diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index 989e318a..7da1352b 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -13,6 +13,7 @@ import ru.bclib.blockentities.BaseChestBlockEntity; import ru.bclib.blockentities.BaseFurnaceBlockEntity; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.blockentities.DynamicBlockEntityType; +import ru.bclib.blockentities.DynamicBlockEntityType.BlockEntitySupplier; import ru.bclib.blocks.BaseBarrelBlock; import ru.bclib.blocks.BaseChestBlock; import ru.bclib.blocks.BaseFurnaceBlock; @@ -24,7 +25,7 @@ public class BaseBlockEntities { public static final DynamicBlockEntityType SIGN = registerBlockEntityType(BCLib.makeID("sign"), BaseSignBlockEntity::new); public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID("furnace"), BaseFurnaceBlockEntity::new); - public static DynamicBlockEntityType registerBlockEntityType(ResourceLocation typeId, Supplier supplier) { + public static DynamicBlockEntityType registerBlockEntityType(ResourceLocation typeId, BlockEntitySupplier supplier) { return Registry.register(Registry.BLOCK_ENTITY_TYPE, typeId, new DynamicBlockEntityType<>(supplier)); } diff --git a/src/main/java/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemsRegistry.java index 57d884bf..7dcc9744 100644 --- a/src/main/java/ru/bclib/registry/ItemsRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemsRegistry.java @@ -9,6 +9,7 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.tags.Tag; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.CreativeModeTab; @@ -67,7 +68,7 @@ public abstract class ItemsRegistry extends BaseRegistry { return item; } - public Item registerEgg(String name, EntityType type, int background, int dots) { + public Item registerEgg(String name, EntityType type, int background, int dots) { SpawnEggItem item = new BaseSpawnEggItem(type, background, dots, makeItemSettings()); DefaultDispenseItemBehavior behavior = new DefaultDispenseItemBehavior() { public ItemStack execute(BlockSource pointer, ItemStack stack) { diff --git a/src/main/java/ru/bclib/world/structures/StructureWorld.java b/src/main/java/ru/bclib/world/structures/StructureWorld.java index af49651b..8f3c80d5 100644 --- a/src/main/java/ru/bclib/world/structures/StructureWorld.java +++ b/src/main/java/ru/bclib/world/structures/StructureWorld.java @@ -100,7 +100,7 @@ public class StructureWorld { public BoundingBox getBounds() { if (minX == Integer.MAX_VALUE || maxX == Integer.MIN_VALUE || minZ == Integer.MAX_VALUE || maxZ == Integer.MIN_VALUE) { - return BoundingBox.getUnknownBox(); + return BoundingBox.infinite(); } return new BoundingBox(minX << 4, minY, minZ << 4, (maxX << 4) | 15, maxY, (maxZ << 4) | 15); } From 02068df82dc5db49b0dee1cde103e34a8ddc58c3 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 24 Jun 2021 18:02:56 +0300 Subject: [PATCH 0009/1033] Fixed Structure Helper --- gradle.properties | 2 +- .../java/ru/bclib/util/StructureHelper.java | 76 ++++++++++--------- 2 files changed, 40 insertions(+), 38 deletions(-) diff --git a/gradle.properties b/gradle.properties index e1474630..f0252152 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.1.43 +mod_version = 0.2.0 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/util/StructureHelper.java b/src/main/java/ru/bclib/util/StructureHelper.java index 179159e3..9d724ac8 100644 --- a/src/main/java/ru/bclib/util/StructureHelper.java +++ b/src/main/java/ru/bclib/util/StructureHelper.java @@ -14,6 +14,7 @@ import com.google.common.collect.Sets; import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.resources.ResourceLocation; @@ -27,6 +28,7 @@ import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.material.Material; +import net.minecraft.world.phys.Vec3; import ru.bclib.api.TagAPI; public class StructureHelper { @@ -86,8 +88,8 @@ public class StructureHelper { } public static BlockPos offsetPos(BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror) { - BlockPos offset = StructureTemplate.transform(structure.getSize(), mirror, rotation, BlockPos.ZERO); - return pos.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); + Vec3 offset = StructureTemplate.transform(Vec3.atCenterOf(structure.getSize()), mirror, rotation, BlockPos.ZERO); + return pos.offset(-offset.x * 0.5, 0, -offset.z * 0.5); } public static void placeCenteredBottom(WorldGenLevel world, BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror, Random random) { @@ -97,7 +99,7 @@ public class StructureHelper { public static void placeCenteredBottom(WorldGenLevel world, BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror, BoundingBox bounds, Random random) { BlockPos offset = offsetPos(pos, structure, rotation, mirror); StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); - structure.placeInWorldChunk(world, offset, placementData, random); + structure.placeInWorld(world, offset, offset, placementData, random, 4); } private static BoundingBox makeBox(BlockPos pos) { @@ -105,37 +107,37 @@ public class StructureHelper { int sz = ((pos.getZ() >> 4) << 4) - 16; int ex = sx + 47; int ez = sz + 47; - return BoundingBox.createProper(sx, 0, sz, ex, 255, ez); + return BoundingBox.fromCorners(new Vec3i(sx, 0, sz), new Vec3i(ex, 255, ez)); } public static BoundingBox getStructureBounds(BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror) { - BlockPos max = structure.getSize(); - BlockPos min = StructureTemplate.transform(structure.getSize(), mirror, rotation, BlockPos.ZERO); - max = max.subtract(min); - return new BoundingBox(min.offset(pos), max.offset(pos)); + Vec3i max = structure.getSize(); + Vec3 min = StructureTemplate.transform(Vec3.atCenterOf(structure.getSize()), mirror, rotation, BlockPos.ZERO); + max = max.offset(-min.x, -min.y, -min.z); + return BoundingBox.fromCorners(pos.offset(min.x, min.y, min.z), max.offset(pos)); } public static BoundingBox intersectBoxes(BoundingBox box1, BoundingBox box2) { - int x1 = MHelper.max(box1.x0, box2.x0); - int y1 = MHelper.max(box1.y0, box2.y0); - int z1 = MHelper.max(box1.z0, box2.z0); + int x1 = MHelper.max(box1.minX(), box2.minX()); + int y1 = MHelper.max(box1.minY(), box2.minY()); + int z1 = MHelper.max(box1.minZ(), box2.minZ()); - int x2 = MHelper.min(box1.x1, box2.x1); - int y2 = MHelper.min(box1.y1, box2.y1); - int z2 = MHelper.min(box1.z1, box2.z1); + int x2 = MHelper.min(box1.maxX(), box2.maxX()); + int y2 = MHelper.min(box1.maxY(), box2.maxY()); + int z2 = MHelper.min(box1.maxZ(), box2.maxZ()); - return BoundingBox.createProper(x1, y1, z1, x2, y2, z2); + return BoundingBox.fromCorners(new Vec3i(x1, y1, z1), new Vec3i(x2, y2, z2)); } public static void erode(WorldGenLevel world, BoundingBox bounds, int iterations, Random random) { MutableBlockPos mut = new MutableBlockPos(); boolean canDestruct = true; for (int i = 0; i < iterations; i++) { - for (int x = bounds.x0; x <= bounds.x1; x++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); - for (int y = bounds.y1; y >= bounds.y0; y--) { + for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); boolean ignore = ignore(state, world, mut); @@ -183,7 +185,7 @@ public class StructureHelper { if (world.isEmptyBlock(mut.relative(dir)) && world.isEmptyBlock(mut.below().relative(dir))) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); mut.move(dir).move(Direction.DOWN); - for (int py = mut.getY(); y >= bounds.y0 - 10; y--) { + for (int py = mut.getY(); y >= bounds.minY() - 10; y--) { mut.setY(py - 1); if (!world.isEmptyBlock(mut)) { mut.setY(py); @@ -202,16 +204,16 @@ public class StructureHelper { } } } - for (int x = bounds.x0; x <= bounds.x1; x++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); - for (int y = bounds.y1; y >= bounds.y0; y--) { + for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); if (!ignore(state, world, mut) && world.isEmptyBlock(mut.below())) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - for (int py = mut.getY(); py >= bounds.y0 - 10; py--) { + for (int py = mut.getY(); py >= bounds.minY() - 10; py--) { mut.setY(py - 1); if (!world.isEmptyBlock(mut)) { mut.setY(py); @@ -228,12 +230,12 @@ public class StructureHelper { public static void erodeIntense(WorldGenLevel world, BoundingBox bounds, Random random) { MutableBlockPos mut = new MutableBlockPos(); MutableBlockPos mut2 = new MutableBlockPos(); - int minY = bounds.y0 - 10; - for (int x = bounds.x0; x <= bounds.x1; x++) { + int minY = bounds.minY() - 10; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); - for (int y = bounds.y1; y >= bounds.y0; y--) { + for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); if (!ignore(state, world, mut)) { @@ -279,11 +281,11 @@ public class StructureHelper { Set edge = Sets.newHashSet(); Set add = Sets.newHashSet(); - for (int x = bounds.x0; x <= bounds.x1; x++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); - for (int y = bounds.y0; y <= bounds.y1; y++) { + for (int y = bounds.minY(); y <= bounds.maxY(); y++) { mut.setY(y); BlockState state = world.getBlockState(mut); if (!ignore(state, world, mut) && isTerrainNear(world, mut)) { @@ -319,12 +321,12 @@ public class StructureHelper { add.clear(); } - int minY = bounds.y0 - 10; - for (int x = bounds.x0; x <= bounds.x1; x++) { + int minY = bounds.minY() - 10; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); - for (int y = bounds.y0; y <= bounds.y1; y++) { + for (int y = bounds.minY(); y <= bounds.maxY(); y++) { mut.setY(y); BlockState state = world.getBlockState(mut); if (!ignore(state, world, mut) && !blocks.contains(mut)) { @@ -355,12 +357,12 @@ public class StructureHelper { public static void cover(WorldGenLevel world, BoundingBox bounds, Random random) { MutableBlockPos mut = new MutableBlockPos(); - for (int x = bounds.x0; x <= bounds.x1; x++) { + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { mut.setX(x); - for (int z = bounds.z0; z <= bounds.z1; z++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { mut.setZ(z); BlockState top = world.getBiome(mut).getGenerationSettings().getSurfaceBuilderConfig().getTopMaterial(); - for (int y = bounds.y1; y >= bounds.y0; y--) { + for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); if (state.is(TagAPI.END_GROUND) && !world.getBlockState(mut.above()).getMaterial().isSolidBlocking()) { From 947b790138e9d1fad6ed0070afe83eee685f4824 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 24 Jun 2021 18:06:24 +0300 Subject: [PATCH 0010/1033] NBT Structure fix & Surface Builder fix --- .../ru/bclib/world/features/NBTStructureFeature.java | 5 +++-- .../world/surface/DoubleBlockSurfaceBuilder.java | 12 ++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index 598a3078..e48bfb5a 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -7,6 +7,7 @@ import java.util.Random; import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.resources.ResourceLocation; @@ -101,7 +102,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); addStructureData(placementData); center = center.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); - structure.placeInWorld(world, center, placementData, random); + structure.placeInWorld(world, center, center, placementData, random, 4); TerrainMerge merge = getTerrainMerge(world, center, random); int x1 = center.getX(); @@ -173,7 +174,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { int sz = ((pos.getZ() >> 4) << 4) - 16; int ex = sx + 47; int ez = sz + 47; - return BoundingBox.createProper(sx, 0, sz, ex, 255, ez); + return BoundingBox.fromCorners(new Vec3i(sx, 0, sz), new Vec3i(ex, 255, ez)); } protected static StructureTemplate readStructure(ResourceLocation resource) { diff --git a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java index 1e19d33e..14e6bba4 100644 --- a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java +++ b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java @@ -34,12 +34,6 @@ public class DoubleBlockSurfaceBuilder extends SurfaceBuilder 0 ? config1 : config2); - } public static DoubleBlockSurfaceBuilder register(String name) { return Registry.register(Registry.SURFACE_BUILDER, name, new DoubleBlockSurfaceBuilder()); @@ -49,4 +43,10 @@ public class DoubleBlockSurfaceBuilder extends SurfaceBuilder 0 ? config1 : config2); + } } \ No newline at end of file From 3143de77c3a58604441ed5e292cb87277eaf54b5 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 24 Jun 2021 18:08:27 +0300 Subject: [PATCH 0011/1033] Fixed feature sapling block --- src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 5f33bb0a..38548c2f 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -87,7 +87,8 @@ public abstract class FeatureSaplingBlock extends SaplingBlock implements IRende @Override public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { - getFeature().place(world, world.getChunkSource().getGenerator(), random, pos, null); + FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null); + getFeature().place(context); } @Override From 5512ece14eac2b1c9cb14153794882c410839582 Mon Sep 17 00:00:00 2001 From: Aleksey Date: Fri, 25 Jun 2021 14:38:29 +0300 Subject: [PATCH 0012/1033] Tag loader fix --- .../ru/bclib/mixin/common/TagLoaderMixin.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index 743a59f5..462ac1d1 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -1,26 +1,23 @@ package ru.bclib.mixin.common; -import java.util.Map; -import java.util.concurrent.Executor; -import java.util.function.Supplier; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; import net.minecraft.tags.TagLoader; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; import ru.bclib.util.TagHelper; +import java.util.Map; + @Mixin(TagLoader.class) public class TagLoaderMixin { @Shadow - private String name; + private String directory; - @ModifyArg(method = "prepare", at = @At(value = "INVOKE", target = "Ljava/util/concurrent/CompletableFuture;supplyAsync(Ljava/util/function/Supplier;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;")) - public Supplier> be_modifyTags(Supplier> supplier, Executor executor) { - return () -> TagHelper.apply(name, supplier.get()); + @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) + public Map be_modifyTags(Map tagsMap) { + return TagHelper.apply(directory, tagsMap); } } From 7dfbe7bfafbbd5c59ae3e5851845e5915b824224 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 25 Jun 2021 17:48:58 +0200 Subject: [PATCH 0013/1033] `HEIGHTMAP_SQUARE` has index 17 --- src/main/java/ru/bclib/world/features/BCLDecorators.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/world/features/BCLDecorators.java b/src/main/java/ru/bclib/world/features/BCLDecorators.java index b302b031..d037c5f6 100644 --- a/src/main/java/ru/bclib/world/features/BCLDecorators.java +++ b/src/main/java/ru/bclib/world/features/BCLDecorators.java @@ -22,6 +22,6 @@ public class BCLDecorators { static { Class[] classes = Features.class.getDeclaredClasses(); Field[] fields = classes[1].getDeclaredFields(); // Decorators class - HEIGHTMAP_SQUARE = getDecorator(fields, 27); + HEIGHTMAP_SQUARE = getDecorator(fields, 17); } } From a53114779ad9b9b08791986670d75977f08b795c Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 29 Jun 2021 23:32:31 +0200 Subject: [PATCH 0014/1033] `blockState`is `null` if it can not be placed --- src/main/java/ru/bclib/items/BaseAnvilItem.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index d4c51755..c1b36914 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -34,7 +34,9 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { BlockState blockState = super.getPlacementState(blockPlaceContext); ItemStack stack = blockPlaceContext.getItemInHand(); int destruction = stack.getOrCreateTag().getInt(DESTRUCTION); - blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); + if (blockState != null) { + blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); + } return blockState; } From 827018078ff57d5e90aab10cc65f95746ca7e15e Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 7 Jul 2021 13:30:16 +0200 Subject: [PATCH 0015/1033] Register `tick` for *Furnace*-Blocks --- .../ru/bclib/blocks/BaseFurnaceBlock.java | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index 2b93d9a7..925a3e45 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -1,14 +1,7 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -20,14 +13,17 @@ import net.minecraft.stats.Stats; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FurnaceBlock; +import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseFurnaceBlockEntity; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; @@ -35,6 +31,11 @@ import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.registry.BaseBlockEntities; + +import java.util.List; +import java.util.Map; +import java.util.Optional; public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, IRenderTyped { public BaseFurnaceBlock(Block source) { @@ -109,4 +110,15 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider } return drop; } + + @Override + @Nullable + public BlockEntityTicker getTicker(Level level, BlockState blockState, BlockEntityType blockEntityType) { + return createFurnaceTicker(level, blockEntityType, BaseBlockEntities.FURNACE); + } + + @Nullable + protected static BlockEntityTicker createFurnaceTicker(Level level, BlockEntityType blockEntityType, BlockEntityType blockEntityType2) { + return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick); + } } From abcf90e0bc932cfd77afc8c849212885fa1e051a Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 7 Jul 2021 13:30:42 +0200 Subject: [PATCH 0016/1033] Fixed *Sign* rendering --- .../bclib/client/gui/BlockSignEditScreen.java | 23 ++-- .../render/BaseSignBlockEntityRenderer.java | 104 ++++++++++++++---- 2 files changed, 95 insertions(+), 32 deletions(-) diff --git a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java index 25be05c9..89954126 100644 --- a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java +++ b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java @@ -1,7 +1,5 @@ package ru.bclib.client.gui; -import java.util.Arrays; - import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; @@ -11,8 +9,8 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexConsumer; +import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.math.Matrix4f; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.Util; @@ -20,22 +18,25 @@ import net.minecraft.client.gui.GuiComponent; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.font.TextFieldHelper; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.model.geom.ModelLayers; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.blockentity.SignRenderer.SignModel; +import net.minecraft.client.renderer.blockentity.SignRenderer; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.network.protocol.game.ServerboundSignUpdatePacket; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.WoodType; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.blocks.BaseSignBlock; import ru.bclib.client.render.BaseSignBlockEntityRenderer; +import java.util.Arrays; + @Environment(EnvType.CLIENT) public class BlockSignEditScreen extends Screen { - private final SignModel model = new SignModel(); private final BaseSignBlockEntity sign; private int ticksSinceOpened; private int currentRow; @@ -43,6 +44,7 @@ public class BlockSignEditScreen extends Screen { private final String[] text = (String[]) Util.make(new String[4], (strings) -> { Arrays.fill(strings, ""); }); + private SignRenderer.SignModel model; public BlockSignEditScreen(BaseSignBlockEntity sign) { super(new TranslatableComponent("sign.edit")); @@ -50,8 +52,11 @@ public class BlockSignEditScreen extends Screen { } protected void init() { + //set up a default model + model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); + minecraft.keyboardHandler.setSendRepeatsToGui(true); - this.addButton(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, + this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, (buttonWidget) -> { this.finishEditing(); })); @@ -80,7 +85,7 @@ public class BlockSignEditScreen extends Screen { public void tick() { ++this.ticksSinceOpened; - if (!this.sign.getType().isValid(this.sign.getBlockState().getBlock())) { + if (!this.sign.getType().isValid(this.sign.getBlockState())) { this.finishEditing(); } } @@ -135,7 +140,7 @@ public class BlockSignEditScreen extends Screen { matrices.scale(0.6666667F, -0.6666667F, -0.6666667F); MultiBufferSource.BufferSource immediate = minecraft.renderBuffers().bufferSource(); VertexConsumer vertexConsumer = BaseSignBlockEntityRenderer.getConsumer(immediate, blockState.getBlock()); - model.sign.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); + model.root.getChild("sign").render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); if (bl) { model.stick.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); @@ -206,7 +211,7 @@ public class BlockSignEditScreen extends Screen { RenderSystem.disableTexture(); RenderSystem.enableColorLogicOp(); RenderSystem.logicOp(GlStateManager.LogicOp.OR_REVERSE); - bufferBuilder.begin(7, DefaultVertexFormat.POSITION_COLOR); + bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); float var32 = (float) x; bufferBuilder.vertex(matrix4f, var32, (float) (l + 9), 0.0F).color(0, 0, 255, 255).endVertex(); var32 = (float) y; diff --git a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java index 33697f60..6d26f1d6 100644 --- a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java @@ -1,68 +1,84 @@ package ru.bclib.client.render; -import java.util.HashMap; -import java.util.List; - import com.google.common.collect.Maps; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.math.Vector3f; - +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; +import net.minecraft.client.model.geom.ModelLayers; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.Sheets; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.SignRenderer; -import net.minecraft.client.renderer.blockentity.SignRenderer.SignModel; import net.minecraft.client.resources.model.Material; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.item.DyeColor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SignBlock; import net.minecraft.world.level.block.StandingSignBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.WoodType; +import net.minecraft.world.phys.Vec3; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.blocks.BaseSignBlock; +import java.util.HashMap; +import java.util.List; + public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); private static final RenderType defaultLayer; - private final SignModel model = new SignRenderer.SignModel(); + private final Font font; + private final SignRenderer.SignModel model; - public BaseSignBlockEntityRenderer(BlockEntityRenderDispatcher dispatcher) { - super(dispatcher); + + private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16); + + public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { + super(); + this.font = ctx.getFont(); + + //set up a default model + model = new SignRenderer.SignModel(ctx.bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); } public void render(BaseSignBlockEntity signBlockEntity, float tickDelta, PoseStack matrixStack, MultiBufferSource provider, int light, int overlay) { BlockState state = signBlockEntity.getBlockState(); + matrixStack.pushPose(); + matrixStack.translate(0.5D, 0.5D, 0.5D); float angle = -((float) (state.getValue(StandingSignBlock.ROTATION) * 360) / 16.0F); BlockState blockState = signBlockEntity.getBlockState(); if (blockState.getValue(BaseSignBlock.FLOOR)) { matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle)); - this.model.stick.visible = true; + model.stick.visible = true; } else { matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle + 180)); matrixStack.translate(0.0D, -0.3125D, -0.4375D); - this.model.stick.visible = false; + model.stick.visible = false; } matrixStack.pushPose(); matrixStack.scale(0.6666667F, -0.6666667F, -0.6666667F); VertexConsumer vertexConsumer = getConsumer(provider, state.getBlock()); - model.sign.render(matrixStack, vertexConsumer, light, overlay); - model.stick.render(matrixStack, vertexConsumer, light, overlay); + + model.root.render(matrixStack, vertexConsumer, light, overlay); + //model.stick.render(matrixStack, vertexConsumer, light, overlay); matrixStack.popPose(); - Font textRenderer = renderer.getFont(); + //Font textRenderer = renderer.getFont(); matrixStack.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); matrixStack.scale(0.010416667F, -0.010416667F, 0.010416667F); int m = signBlockEntity.getColor().getTextColor(); @@ -71,21 +87,59 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { + List list = this.font.split(component, 90); + return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); + }); + int drawColor; + boolean drawOutlined; + int drawLight; + if (signBlockEntity.hasGlowingText()) { + drawColor = signBlockEntity.getColor().getTextColor(); + drawOutlined = isOutlineVisible(signBlockEntity, drawColor); + drawLight = 15728880; + } else { + drawColor = m; + drawOutlined = false; + drawLight = light; + } + for (int s = 0; s < 4; ++s) { - FormattedCharSequence orderedText = signBlockEntity.getRenderMessage(s, (text) -> { - List list = textRenderer.split(text, 90); - return list.isEmpty() ? FormattedCharSequence.EMPTY : list.get(0); - }); - if (orderedText != null) { - float t = (float) (-textRenderer.width(orderedText) / 2); - textRenderer.drawInBatch(orderedText, t, (float) (s * 10 - 20), q, false, matrixStack.last().pose(), provider, false, 0, light); + FormattedCharSequence formattedCharSequence = formattedCharSequences[s]; + float t = (float) (-this.font.width(formattedCharSequence) / 2); + if (drawOutlined) { + this.font.drawInBatch8xOutline(formattedCharSequence, t, (float) (s * 10 - 20), drawColor, m, + matrixStack.last().pose(), provider, drawLight); + } else { + this.font.drawInBatch((FormattedCharSequence) formattedCharSequence, t, (float) (s * 10 - 20), drawColor, false, + matrixStack.last().pose(), provider, false, 0, drawLight); } } + matrixStack.popPose(); } - public static Material getModelTexture(Block block) { + + + private static boolean isOutlineVisible(BaseSignBlockEntity signBlockEntity, int i) { + if (i == DyeColor.BLACK.getTextColor()) { + return true; + } else { + Minecraft minecraft = Minecraft.getInstance(); + LocalPlayer localPlayer = minecraft.player; + if (localPlayer != null && minecraft.options.getCameraType().isFirstPerson() && localPlayer.isScoping()) { + return true; + } else { + Entity entity = minecraft.getCameraEntity(); + return entity != null && entity.distanceToSqr( + Vec3.atCenterOf(signBlockEntity.getBlockPos())) < (double) OUTLINE_RENDER_DISTANCE; + } + } + } + + public static WoodType getSignType(Block block) { WoodType signType2; if (block instanceof SignBlock) { signType2 = ((SignBlock) block).type(); @@ -93,7 +147,11 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer Date: Wed, 7 Jul 2021 13:31:02 +0200 Subject: [PATCH 0017/1033] Fixed *Chest* rendering --- .../client/models/BaseChestBlockModel.java | 91 +++++++++++++++++++ .../render/BaseChestBlockEntityRenderer.java | 53 ++--------- 2 files changed, 100 insertions(+), 44 deletions(-) create mode 100644 src/main/java/ru/bclib/client/models/BaseChestBlockModel.java diff --git a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java new file mode 100644 index 00000000..ec5bf62d --- /dev/null +++ b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java @@ -0,0 +1,91 @@ +package ru.bclib.client.models; + +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.model.geom.PartPose; +import net.minecraft.client.model.geom.builders.*; + +public class BaseChestBlockModel { + public final ModelPart partA; + public final ModelPart partC; + public final ModelPart partB; + public final ModelPart partRightA; + public final ModelPart partRightC; + public final ModelPart partRightB; + public final ModelPart partLeftA; + public final ModelPart partLeftC; + public final ModelPart partLeftB; + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + CubeDeformation deformation_partC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partC", CubeListBuilder.create() + .texOffs(0, 19) + .addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), + PartPose.ZERO); + + CubeDeformation deformation_partA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partA", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), + PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partB = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partB", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), + PartPose.offset(0.0f, 8.0f, 0.0f)); + + CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create() + .texOffs(0, 19) + .addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), + PartPose.ZERO); + + CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), + PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); + PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), + PartPose.offset(0.0f, 8.0f, 0.0f)); + + CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create() + .texOffs(0, 19) + .addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), + PartPose.ZERO); + + CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), + PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create() + .texOffs(0, 0) + .addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), + PartPose.offset(0.0f, 8.0f, 0.0f)); + + return LayerDefinition.create(modelData, 64, 64); + } + + public BaseChestBlockModel(ModelPart modelPart) { + super(); + + partC = modelPart.getChild("partC"); + partA = modelPart.getChild("partA"); + partB = modelPart.getChild("partB"); + partRightC = modelPart.getChild("partRightC"); + partRightA = modelPart.getChild("partRightA"); + partRightB = modelPart.getChild("partRightB"); + partLeftC = modelPart.getChild("partLeftC"); + partLeftA = modelPart.getChild("partLeftA"); + partLeftB = modelPart.getChild("partLeftB"); + } +} diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 064cb834..96d59f04 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -11,8 +11,8 @@ import net.fabricmc.api.Environment; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.BrightnessCombiner; import net.minecraft.core.Direction; import net.minecraft.core.Registry; @@ -24,6 +24,7 @@ import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.ChestType; import ru.bclib.blockentities.BaseChestBlockEntity; +import ru.bclib.client.models.BaseChestBlockModel; import java.util.HashMap; @@ -36,46 +37,10 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer Date: Wed, 7 Jul 2021 13:32:17 +0200 Subject: [PATCH 0018/1033] `TagLoader` fixes --- .../ru/bclib/mixin/common/TagLoaderMixin.java | 46 +++++++++---------- src/main/java/ru/bclib/util/TagHelper.java | 6 +-- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index 462ac1d1..ced2df40 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -1,23 +1,23 @@ -package ru.bclib.mixin.common; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.tags.TagLoader; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import ru.bclib.util.TagHelper; - -import java.util.Map; - -@Mixin(TagLoader.class) -public class TagLoaderMixin { - @Shadow - private String directory; - - @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) - public Map be_modifyTags(Map tagsMap) { - return TagHelper.apply(directory, tagsMap); - } -} +package ru.bclib.mixin.common; + +import java.util.Map; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.Tag; +import net.minecraft.tags.TagLoader; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import ru.bclib.util.TagHelper; + +@Mixin(TagLoader.class) +public class TagLoaderMixin { + @Shadow + private String directory; + + @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) + public Map be_modifyTags(Map tagsMap) { + return TagHelper.apply(directory, tagsMap); + } +} diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java index f5dc604d..dae193d0 100644 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -58,11 +58,11 @@ public class TagHelper { return builder; } - public static Map apply(String entry, Map tagsMap) { + public static Map apply(String directory, Map tagsMap) { Map> endTags = null; - if (entry.equals("block")) { + if ("tags/blocks".equals(directory)) { endTags = TAGS_BLOCK; - } else if (entry.equals("item")) { + } else if ("tags/items".equals(directory)) { endTags = TAGS_ITEM; } if (endTags != null) { From daeca492ec697a70b454893daf3f83cf3aadd989 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 7 Jul 2021 13:35:41 +0200 Subject: [PATCH 0019/1033] Dependencies updated for 1.17.1 --- gradle.properties | 4 ++-- src/main/resources/fabric.mod.json | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gradle.properties b/gradle.properties index f0252152..a65a9b79 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx2G # Fabric Properties # check these on https://fabricmc.net/use -minecraft_version= 1.17 +minecraft_version= 1.17.1 yarn_mappings= 6 loader_version= 0.11.6 @@ -15,4 +15,4 @@ archives_base_name = bclib # Dependencies # currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api patchouli_version = 50-FABRIC -fabric_version = 0.36.0+1.17 +fabric_version = 0.36.1+1.17 diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index d4c9f8f1..6d8a5cb6 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -36,8 +36,8 @@ ], "depends": { - "fabricloader": ">=0.11.0", - "fabric": ">=0.32.0", - "minecraft": ">=1.16.4" + "fabricloader": ">=0.11.6", + "fabric": ">=0.36.0", + "minecraft": ">=1.17" } } From 1ebb93d7abfbdad4cde855ae9b70508a7301ec60 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 29 Jun 2021 23:32:31 +0200 Subject: [PATCH 0020/1033] `blockState`is `null` if it can not be placed --- src/main/java/ru/bclib/items/BaseAnvilItem.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index d4c51755..c1b36914 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -34,7 +34,9 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { BlockState blockState = super.getPlacementState(blockPlaceContext); ItemStack stack = blockPlaceContext.getItemInHand(); int destruction = stack.getOrCreateTag().getInt(DESTRUCTION); - blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); + if (blockState != null) { + blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); + } return blockState; } From 4ece50ddb1696042214fa930b460d6e8ab3b0e97 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 25 Jun 2021 17:48:58 +0200 Subject: [PATCH 0021/1033] duplicatesStrategy `EXCLUDE` will not copy the version number to the built jar --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 3b9ff8a6..8e2dc088 100644 --- a/build.gradle +++ b/build.gradle @@ -65,7 +65,7 @@ def useApi(String dep) { processResources { inputs.property "version", project.version - duplicatesStrategy = 'EXCLUDE' + duplicatesStrategy = 'WARN' from(sourceSets.main.resources.srcDirs) { include "fabric.mod.json" From 1a049d05c45f429c36323917ac25087af38bbe55 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 25 Jun 2021 17:48:58 +0200 Subject: [PATCH 0022/1033] duplicatesStrategy `EXCLUDE` will not copy the version number to the built jar --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 9d232758..b0cead1a 100644 --- a/build.gradle +++ b/build.gradle @@ -65,7 +65,7 @@ def useApi(String dep) { processResources { inputs.property "version", project.version - duplicatesStrategy = 'EXCLUDE' + duplicatesStrategy = 'WARN' from(sourceSets.main.resources.srcDirs) { include "fabric.mod.json" From 370add478f37e8f28cb494fe08e0f5a2a10b45d8 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 9 Jul 2021 09:16:08 +0200 Subject: [PATCH 0023/1033] Force jitpack to use Java16 --- jitpack.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 jitpack.yml diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 00000000..b0b045eb --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,6 @@ +# From https://github.com/jitpack/jitpack.io/issues/4506#issuecomment-864562270 +before_install: + - source "$HOME/.sdkman/bin/sdkman-init.sh" + - sdk update + - sdk install java 16.0.1.hs-adpt + - sdk use java 16.0.1.hs-adpt \ No newline at end of file From 5a9365e2bb04bd2c751994cb6c51bb5333eab12e Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 10 Jul 2021 16:07:44 +0300 Subject: [PATCH 0024/1033] Fixed structure features and code style --- gradle.properties | 2 +- src/main/java/ru/bclib/BCLib.java | 2 +- src/main/java/ru/bclib/api/BiomeAPI.java | 27 +- src/main/java/ru/bclib/api/BonemealAPI.java | 21 +- src/main/java/ru/bclib/api/DataFixerAPI.java | 39 +- .../java/ru/bclib/api/ModIntegrationAPI.java | 7 +- src/main/java/ru/bclib/api/TagAPI.java | 26 +- src/main/java/ru/bclib/api/WorldDataAPI.java | 25 +- .../blockentities/BaseBarrelBlockEntity.java | 42 +- .../blockentities/BaseFurnaceBlockEntity.java | 4 +- .../blockentities/BaseSignBlockEntity.java | 2 +- .../blockentities/DynamicBlockEntityType.java | 26 +- .../java/ru/bclib/blocks/BaseAnvilBlock.java | 26 +- .../ru/bclib/blocks/BaseAttachedBlock.java | 8 +- .../java/ru/bclib/blocks/BaseBarkBlock.java | 8 +- .../java/ru/bclib/blocks/BaseBarrelBlock.java | 72 +- src/main/java/ru/bclib/blocks/BaseBlock.java | 10 +- .../ru/bclib/blocks/BaseBlockNotFull.java | 8 +- .../ru/bclib/blocks/BaseBlockWithEntity.java | 11 +- .../ru/bclib/blocks/BaseBookshelfBlock.java | 15 +- .../java/ru/bclib/blocks/BaseButtonBlock.java | 66 +- .../java/ru/bclib/blocks/BaseChainBlock.java | 26 +- .../java/ru/bclib/blocks/BaseChestBlock.java | 21 +- .../ru/bclib/blocks/BaseComposterBlock.java | 28 +- .../bclib/blocks/BaseCraftingTableBlock.java | 20 +- .../java/ru/bclib/blocks/BaseCropBlock.java | 20 +- .../java/ru/bclib/blocks/BaseDoorBlock.java | 69 +- .../ru/bclib/blocks/BaseDoublePlantBlock.java | 34 +- .../java/ru/bclib/blocks/BaseFenceBlock.java | 40 +- .../ru/bclib/blocks/BaseFurnaceBlock.java | 22 +- .../java/ru/bclib/blocks/BaseGateBlock.java | 33 +- .../java/ru/bclib/blocks/BaseLadderBlock.java | 51 +- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 31 +- .../ru/bclib/blocks/BaseMetalBarsBlock.java | 50 +- .../java/ru/bclib/blocks/BaseOreBlock.java | 20 +- .../java/ru/bclib/blocks/BasePathBlock.java | 22 +- .../java/ru/bclib/blocks/BasePlantBlock.java | 36 +- .../bclib/blocks/BasePlantWithAgeBlock.java | 13 +- .../bclib/blocks/BasePressurePlateBlock.java | 27 +- .../bclib/blocks/BaseRotatedPillarBlock.java | 23 +- .../java/ru/bclib/blocks/BaseSignBlock.java | 58 +- .../java/ru/bclib/blocks/BaseSlabBlock.java | 27 +- .../java/ru/bclib/blocks/BaseStairsBlock.java | 33 +- .../ru/bclib/blocks/BaseStoneButtonBlock.java | 4 +- .../ru/bclib/blocks/BaseTerrainBlock.java | 28 +- .../ru/bclib/blocks/BaseTrapdoorBlock.java | 27 +- .../blocks/BaseUnderwaterWallPlantBlock.java | 15 +- .../java/ru/bclib/blocks/BaseVineBlock.java | 34 +- .../java/ru/bclib/blocks/BaseWallBlock.java | 52 +- .../ru/bclib/blocks/BaseWallPlantBlock.java | 34 +- .../bclib/blocks/BaseWeightedPlateBlock.java | 27 +- .../bclib/blocks/BaseWoodenButtonBlock.java | 4 +- .../java/ru/bclib/blocks/BlockProperties.java | 14 +- .../ru/bclib/blocks/FeatureSaplingBlock.java | 60 +- .../ru/bclib/blocks/SimpleLeavesBlock.java | 21 +- .../java/ru/bclib/blocks/StalactiteBlock.java | 32 +- .../ru/bclib/blocks/TripleTerrainBlock.java | 57 +- .../ru/bclib/blocks/UnderwaterPlantBlock.java | 38 +- .../blocks/UnderwaterPlantWithAgeBlock.java | 11 +- .../ru/bclib/blocks/UpDownPlantBlock.java | 19 +- .../ru/bclib/blocks/WallMushroomBlock.java | 14 +- .../java/ru/bclib/client/BCLibClient.java | 6 +- .../bclib/client/gui/BlockSignEditScreen.java | 89 +- .../client/models/BaseChestBlockModel.java | 145 ++- .../ru/bclib/client/models/BasePatterns.java | 2 +- .../client/models/BlockModelProvider.java | 20 +- .../ru/bclib/client/models/ModelsHelper.java | 71 +- .../bclib/client/models/PatternsHelper.java | 33 +- .../bclib/client/render/BCLRenderLayer.java | 3 +- .../render/BaseChestBlockEntityRenderer.java | 59 +- .../render/BaseSignBlockEntityRenderer.java | 87 +- .../ru/bclib/client/sound/BlockSounds.java | 7 +- .../java/ru/bclib/config/CategoryConfig.java | 2 +- src/main/java/ru/bclib/config/Config.java | 20 +- .../java/ru/bclib/config/ConfigKeeper.java | 147 ++- src/main/java/ru/bclib/config/ConfigKey.java | 8 +- .../java/ru/bclib/config/ConfigWriter.java | 29 +- src/main/java/ru/bclib/config/IdConfig.java | 41 +- src/main/java/ru/bclib/config/PathConfig.java | 57 +- .../ru/bclib/integration/ModIntegration.java | 14 +- .../ru/bclib/interfaces/IColorProvider.java | 2 +- .../ru/bclib/interfaces/ISpetialItem.java | 1 + .../java/ru/bclib/items/BaseAnvilItem.java | 17 +- .../java/ru/bclib/items/BaseArmorItem.java | 22 +- .../java/ru/bclib/items/BaseDrinkItem.java | 14 +- .../java/ru/bclib/items/BaseSpawnEggItem.java | 4 +- .../java/ru/bclib/items/tool/BaseAxeItem.java | 2 +- .../mixin/client/BackgroundRendererMixin.java | 16 +- .../client/EnchantingTableBlockMixin.java | 17 +- .../bclib/mixin/client/ModelBakeryMixin.java | 44 +- .../bclib/mixin/common/BoneMealItemMixin.java | 13 +- .../mixin/common/ComposterBlockAccessor.java | 5 +- .../mixin/common/EnchantmentMenuMixin.java | 57 +- .../common/FeatureDecoratorsAccessor.java | 7 - .../mixin/common/MinecraftServerMixin.java | 29 +- .../mixin/common/PotionBrewingAccessor.java | 5 +- .../mixin/common/RecipeManagerAccessor.java | 11 +- .../mixin/common/RecipeManagerMixin.java | 34 +- .../bclib/mixin/common/ServerLevelMixin.java | 19 +- .../ru/bclib/mixin/common/TagLoaderMixin.java | 6 +- .../java/ru/bclib/noise/OpenSimplexNoise.java | 933 ++++++++++-------- .../java/ru/bclib/noise/VoronoiNoise.java | 8 +- .../ru/bclib/recipes/BCLRecipeManager.java | 29 +- .../ru/bclib/recipes/CraftingRecipes.java | 16 +- .../java/ru/bclib/recipes/GridRecipe.java | 20 +- .../ru/bclib/recipes/SmithingTableRecipe.java | 2 +- .../ru/bclib/registry/BaseBlockEntities.java | 28 +- .../java/ru/bclib/registry/BaseRegistry.java | 35 +- .../ru/bclib/registry/BlocksRegistry.java | 7 +- .../java/ru/bclib/registry/ItemsRegistry.java | 40 +- src/main/java/ru/bclib/sdf/PosInfo.java | 8 +- src/main/java/ru/bclib/sdf/SDF.java | 39 +- .../java/ru/bclib/sdf/operator/SDFBinary.java | 3 +- .../ru/bclib/sdf/operator/SDFCoordModify.java | 4 +- .../bclib/sdf/operator/SDFDisplacement.java | 4 +- .../ru/bclib/sdf/operator/SDFHeightmap.java | 1 - .../sdf/operator/SDFSmoothIntersection.java | 2 +- .../sdf/operator/SDFSmoothSubtraction.java | 2 +- .../ru/bclib/sdf/operator/SDFSmoothUnion.java | 4 +- .../ru/bclib/sdf/primitive/SDFCappedCone.java | 2 +- .../ru/bclib/sdf/primitive/SDFFlatland.java | 2 +- .../ru/bclib/sdf/primitive/SDFHexPrism.java | 2 +- .../java/ru/bclib/sdf/primitive/SDFLine.java | 6 +- .../java/ru/bclib/sdf/primitive/SDFPie.java | 8 +- .../ru/bclib/sdf/primitive/SDFPrimitive.java | 4 +- .../ru/bclib/sdf/primitive/SDFSphere.java | 2 +- src/main/java/ru/bclib/util/BlocksHelper.java | 68 +- .../java/ru/bclib/util/ColorExtractor.java | 35 +- src/main/java/ru/bclib/util/ColorUtil.java | 85 +- src/main/java/ru/bclib/util/JsonFactory.java | 31 +- src/main/java/ru/bclib/util/Logger.java | 26 +- src/main/java/ru/bclib/util/MHelper.java | 30 +- src/main/java/ru/bclib/util/SplineHelper.java | 31 +- .../java/ru/bclib/util/StructureHelper.java | 48 +- src/main/java/ru/bclib/util/TagHelper.java | 18 +- .../java/ru/bclib/util/TranslationHelper.java | 15 +- src/main/java/ru/bclib/util/WeighTree.java | 5 +- src/main/java/ru/bclib/util/WeightedList.java | 24 +- .../java/ru/bclib/world/biomes/BCLBiome.java | 53 +- .../ru/bclib/world/biomes/BCLBiomeDef.java | 83 +- .../bclib/world/features/BCLDecorators.java | 4 +- .../ru/bclib/world/features/BCLFeature.java | 14 +- .../ru/bclib/world/features/ListFeature.java | 16 +- .../world/features/NBTStructureFeature.java | 74 +- .../ru/bclib/world/generator/BiomeChunk.java | 28 +- .../ru/bclib/world/generator/BiomeMap.java | 5 +- .../ru/bclib/world/generator/BiomePicker.java | 11 +- .../ru/bclib/world/generator/BiomeType.java | 3 +- .../DestructionStructureProcessor.java | 2 +- .../processors/TerrainStructureProcessor.java | 2 +- .../world/structures/BCLStructureFeature.java | 21 +- .../world/structures/StructureWorld.java | 7 +- .../surface/DoubleBlockSurfaceBuilder.java | 6 +- 153 files changed, 2304 insertions(+), 2459 deletions(-) diff --git a/gradle.properties b/gradle.properties index a65a9b79..6a32f158 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.0 +mod_version = 0.2.1 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index e3bbee16..e0936be0 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -33,7 +33,7 @@ public class BCLib implements ModInitializer { public static boolean isClient() { return FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT; } - + public static ResourceLocation makeID(String path) { return new ResourceLocation(MOD_ID, path); } diff --git a/src/main/java/ru/bclib/api/BiomeAPI.java b/src/main/java/ru/bclib/api/BiomeAPI.java index 0a1cb7b5..a63db6fd 100644 --- a/src/main/java/ru/bclib/api/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/BiomeAPI.java @@ -1,10 +1,6 @@ package ru.bclib.api; -import java.util.HashMap; -import java.util.Random; - import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.biome.InternalBiomeData; @@ -20,6 +16,9 @@ import net.minecraft.world.level.biome.Biomes; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; +import java.util.HashMap; +import java.util.Random; + public class BiomeAPI { /** * Empty biome used as default value if requested biome doesn't exist or linked. Shouldn't be registered anywhere to prevent bugs. @@ -33,6 +32,7 @@ public class BiomeAPI { /** * Initialize registry for current server. + * * @param server - {@link MinecraftServer} */ public static void initRegistry(MinecraftServer server) { @@ -49,23 +49,19 @@ public class BiomeAPI { /** * Adds {@link BCLBiome} to FabricAPI biomes as the Nether biome (with random {@link ClimateParameters}). + * * @param biome - {@link BCLBiome}. */ public static void addNetherBiomeToFabricApi(BCLBiome biome) { ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); Random random = new Random(biome.getID().toString().hashCode()); - ClimateParameters parameters = new ClimateParameters( - MHelper.randRange(-2F, 2F, random), - MHelper.randRange(-2F, 2F, random), - MHelper.randRange(-2F, 2F, random), - MHelper.randRange(-2F, 2F, random), - MHelper.randRange(-2F, 2F, random) - ); + ClimateParameters parameters = new ClimateParameters(MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random)); InternalBiomeData.addNetherBiome(key, parameters); } /** * Adds {@link BCLBiome} to FabricAPI biomes as an End land biome (generating on islands). + * * @param biome - {@link BCLBiome}. */ public static void addEndLandBiomeToFabricApi(BCLBiome biome) { @@ -77,6 +73,7 @@ public class BiomeAPI { /** * Adds {@link BCLBiome} to FabricAPI biomes as an End void biome (generating between islands in the void). + * * @param biome - {@link BCLBiome}. */ public static void addEndVoidBiomeToFabricApi(BCLBiome biome) { @@ -87,6 +84,7 @@ public class BiomeAPI { /** * Get {@link BCLBiome} from {@link Biome} instance on server. Used to convert world biomes to BCLBiomes. + * * @param biome - {@link Biome} from world. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ @@ -99,6 +97,7 @@ public class BiomeAPI { /** * Get {@link BCLBiome} from biome on client. Used in fog rendering. + * * @param biome - {@link Biome} from client world. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ @@ -116,6 +115,7 @@ public class BiomeAPI { /** * Get biome {@link ResourceLocation} from given {@link Biome}. + * * @param biome - {@link Biome} from server world. * @return biome {@link ResourceLocation}. */ @@ -123,9 +123,10 @@ public class BiomeAPI { ResourceLocation id = biomeRegistry.getKey(biome); return id == null ? EMPTY_BIOME.getID() : id; } - + /** * Get {@link BCLBiome} from given {@link ResourceLocation}. + * * @param biomeID - biome {@link ResourceLocation}. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ @@ -135,6 +136,7 @@ public class BiomeAPI { /** * Get actual {@link Biome} from given {@link BCLBiome}. If it is null it will request it from current {@link Registry}. + * * @param biome - {@link BCLBiome}. * @return {@link Biome}. */ @@ -149,6 +151,7 @@ public class BiomeAPI { /** * Check if biome with {@link ResourceLocation} exists in API registry. + * * @param biomeID - biome {@link ResourceLocation}. * @return {@code true} if biome exists in API registry and {@code false} if not. */ diff --git a/src/main/java/ru/bclib/api/BonemealAPI.java b/src/main/java/ru/bclib/api/BonemealAPI.java index 4e9a200f..56276fd3 100644 --- a/src/main/java/ru/bclib/api/BonemealAPI.java +++ b/src/main/java/ru/bclib/api/BonemealAPI.java @@ -1,16 +1,15 @@ package ru.bclib.api; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Block; +import ru.bclib.util.WeightedList; + import java.util.Map; import java.util.Random; import java.util.Set; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; -import ru.bclib.util.WeightedList; - public class BonemealAPI { private static final Map>> WATER_GRASS_BIOMES = Maps.newHashMap(); private static final Map>> LAND_GRASS_BIOMES = Maps.newHashMap(); @@ -27,13 +26,13 @@ public class BonemealAPI { } public static void addLandGrass(Block plant, Block... terrain) { - for (Block block: terrain) { + for (Block block : terrain) { addLandGrass(block, plant, 1F); } } public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) { - for (Block block: terrain) { + for (Block block : terrain) { addLandGrass(biome, block, plant, 1F); } } @@ -62,13 +61,13 @@ public class BonemealAPI { } public static void addWaterGrass(Block plant, Block... terrain) { - for (Block block: terrain) { + for (Block block : terrain) { addWaterGrass(block, plant, 1F); } } public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) { - for (Block block: terrain) { + for (Block block : terrain) { addWaterGrass(biome, block, plant, 1F); } } diff --git a/src/main/java/ru/bclib/api/DataFixerAPI.java b/src/main/java/ru/bclib/api/DataFixerAPI.java index cf644539..e2eaff5b 100644 --- a/src/main/java/ru/bclib/api/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/DataFixerAPI.java @@ -1,5 +1,15 @@ package ru.bclib.api; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.RegionFile; + import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; @@ -8,17 +18,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.storage.RegionFile; - public class DataFixerAPI { private static final Map REPLACEMENT = Maps.newHashMap(); private static final Map FIX_VERSIONS = Maps.newHashMap(); @@ -31,7 +30,7 @@ public class DataFixerAPI { boolean shoudFix = false; Collection mods = FabricLoader.getInstance().getAllMods(); - for (ModContainer mod: mods) { + for (ModContainer mod : mods) { String name = mod.getMetadata().getId(); int preVersion = WorldDataAPI.getIntModVersion(name); int version = getModVersion(mod.getMetadata().getVersion().toString()); @@ -39,7 +38,8 @@ public class DataFixerAPI { int fixVersion = FIX_VERSIONS.getOrDefault(name, version); shoudFix |= fixVersion < version && fixVersion >= preVersion; } - }; + } + ; if (!shoudFix) { return; } @@ -90,14 +90,15 @@ public class DataFixerAPI { /** * Register block data fix. Fix will be applied on world load if current mod version will be newer than specified one. - * @param modID - {@link String} mod id; + * + * @param modID - {@link String} mod id; * @param modVersion - {@link String} mod version, should be in format: %d.%d.%d - * @param result - {@link String} new block name; - * @param names - array of {@link String}, old block names to convert. + * @param result - {@link String} new block name; + * @param names - array of {@link String}, old block names to convert. */ protected static void addFix(String modID, String modVersion, String result, String... names) { FIX_VERSIONS.put(modID, getModVersion(modVersion)); - for (String name: names) { + for (String name : names) { REPLACEMENT.put(name, result); } } @@ -106,7 +107,7 @@ public class DataFixerAPI { if (list == null) { list = Lists.newArrayList(); } - for (File file: dir.listFiles()) { + for (File file : dir.listFiles()) { if (file.isDirectory()) { getAllRegions(file, list); } @@ -119,6 +120,7 @@ public class DataFixerAPI { /** * Get mod version from string. String should be in format: %d.%d.%d + * * @param version - {@link String} mod version. * @return int mod version. */ @@ -137,6 +139,7 @@ public class DataFixerAPI { /** * Get mod version from integer. String will be in format %d.%d.%d + * * @param version - mod version in integer form. * @return {@link String} mod version. */ diff --git a/src/main/java/ru/bclib/api/ModIntegrationAPI.java b/src/main/java/ru/bclib/api/ModIntegrationAPI.java index eff311dc..5c6b186c 100644 --- a/src/main/java/ru/bclib/api/ModIntegrationAPI.java +++ b/src/main/java/ru/bclib/api/ModIntegrationAPI.java @@ -1,16 +1,16 @@ package ru.bclib.api; -import java.util.List; - import com.google.common.collect.Lists; - import ru.bclib.integration.ModIntegration; +import java.util.List; + public class ModIntegrationAPI { private static final List INTEGRATIONS = Lists.newArrayList(); /** * Registers mod integration + * * @param integration * @return */ @@ -21,6 +21,7 @@ public class ModIntegrationAPI { /** * Get all registered mod integrations. + * * @return {@link List} of {@link ModIntegration}. */ public static List getIntegrations() { diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 8a4accba..e3491e2a 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,7 +1,5 @@ package ru.bclib.api; -import java.util.function.Supplier; - import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -16,6 +14,8 @@ import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; import ru.bclib.util.TagHelper; +import java.util.function.Supplier; + public class TagAPI { // Block Tags public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); @@ -34,22 +34,24 @@ public class TagAPI { public static final Tag.Named IRON_INGOTS = makeCommonItemTag("iron_ingots"); public static final Tag.Named FURNACES = makeCommonItemTag("furnaces"); public final static Tag.Named HAMMERS = makeItemTag("fabric", "hammers"); - + /** * Get or create {@link Tag.Named}. + * * @param containerSupplier - {@link TagCollection} {@link Supplier} tag collection; - * @param id - {@link ResourceLocation} tag id. + * @param id - {@link ResourceLocation} tag id. * @return {@link Tag.Named}. */ public static Tag.Named makeTag(Supplier> containerSupplier, ResourceLocation id) { Tag tag = containerSupplier.get().getTag(id); return tag == null ? TagRegistry.create(id, containerSupplier) : (Named) tag; } - + /** * Get or create {@link Block} {@link Tag.Named} with mod namespace. + * * @param modID - {@link String} mod namespace (mod id); - * @param name - {@link String} tag name. + * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. */ public static Tag.Named makeBlockTag(String modID, String name) { @@ -58,8 +60,9 @@ public class TagAPI { /** * Get or create {@link Item} {@link Tag.Named} with mod namespace. + * * @param modID - {@link String} mod namespace (mod id); - * @param name - {@link String} tag name. + * @param name - {@link String} tag name. * @return {@link Item} {@link Tag.Named}. */ public static Tag.Named makeItemTag(String modID, String name) { @@ -68,9 +71,10 @@ public class TagAPI { /** * Get or create {@link Block} {@link Tag.Named}. - * @see Fabric Wiki (Tags) + * * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. + * @see Fabric Wiki (Tags) */ public static Tag.Named makeCommonBlockTag(String name) { return makeTag(BlockTags::getAllTags, new ResourceLocation("c", name)); @@ -78,9 +82,10 @@ public class TagAPI { /** * Get or create {@link Item} {@link Tag.Named}. - * @see Fabric Wiki (Tags) + * * @param name - {@link String} tag name. * @return {@link Item} {@link Tag.Named}. + * @see Fabric Wiki (Tags) */ public static Tag.Named makeCommonItemTag(String name) { return makeTag(ItemTags::getAllTags, new ResourceLocation("c", name)); @@ -88,6 +93,7 @@ public class TagAPI { /** * Get or create Minecraft {@link Block} {@link Tag.Named}. + * * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. */ @@ -99,6 +105,7 @@ public class TagAPI { /** * Adds {@link Block} to NETHER_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. + * * @param block - {@link Block}. */ public static void addNetherGround(Block block) { @@ -108,6 +115,7 @@ public class TagAPI { /** * Adds {@link Block} to END_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. + * * @param block - {@link Block}. */ public static void addEndGround(Block block) { diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index 6927c9ed..842699c5 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -1,20 +1,19 @@ package ru.bclib.api; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtIo; +import ru.bclib.BCLib; + import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtIo; -import ru.bclib.BCLib; - public class WorldDataAPI { private static final Map TAGS = Maps.newHashMap(); private static final List MODS = Lists.newArrayList(); @@ -52,6 +51,7 @@ public class WorldDataAPI { /** * Register mod cache, world cache is located in world data folder. + * * @param modID - {@link String} modID. */ public static void registerModCache(String modID) { @@ -60,6 +60,7 @@ public class WorldDataAPI { /** * Get root {@link CompoundTag} for mod cache in world data folder. + * * @param modID - {@link String} modID. * @return {@link CompoundTag} */ @@ -74,13 +75,14 @@ public class WorldDataAPI { /** * Get {@link CompoundTag} with specified path from mod cache in world data folder. + * * @param modID - {@link String} path to tag, dot-separated. * @return {@link CompoundTag} */ public static CompoundTag getCompoundTag(String modID, String path) { String[] parts = path.split("\\."); CompoundTag tag = getRootTag(modID); - for (String part: parts) { + for (String part : parts) { if (tag.contains(part)) { tag = tag.getCompound(part); } @@ -95,6 +97,7 @@ public class WorldDataAPI { /** * Forces mod cache file to be saved. + * * @param modID {@link String} mod ID. */ public static void saveFile(String modID) { @@ -108,6 +111,7 @@ public class WorldDataAPI { /** * Get stored mod version (only for mods with registered cache). + * * @return {@link String} mod version. */ public static String getModVersion(String modID) { @@ -116,6 +120,7 @@ public class WorldDataAPI { /** * Get stored mod version as integer (only for mods with registered cache). + * * @return {@code int} mod version. */ public static int getIntModVersion(String modID) { diff --git a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java index c181a7a7..571fb407 100644 --- a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java @@ -26,25 +26,25 @@ import ru.bclib.registry.BaseBlockEntities; public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { private NonNullList inventory; private int viewerCount; - + private BaseBarrelBlockEntity(BlockEntityType type, BlockPos blockPos, BlockState blockState) { super(type, blockPos, blockState); this.inventory = NonNullList.withSize(27, ItemStack.EMPTY); } - + public BaseBarrelBlockEntity(BlockPos blockPos, BlockState blockState) { this(BaseBlockEntities.BARREL, blockPos, blockState); } - + public CompoundTag save(CompoundTag tag) { super.save(tag); if (!this.trySaveLootTable(tag)) { ContainerHelper.saveAllItems(tag, this.inventory); } - + return tag; } - + public void load(CompoundTag tag) { super.load(tag); this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); @@ -52,56 +52,57 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { ContainerHelper.loadAllItems(tag, this.inventory); } } - + public int getContainerSize() { return 27; } - + protected NonNullList getItems() { return this.inventory; } - + protected void setItems(NonNullList list) { this.inventory = list; } - + protected Component getDefaultName() { return new TranslatableComponent("container.barrel"); } - + protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { return ChestMenu.threeRows(syncId, playerInventory, this); } - + public void startOpen(Player player) { if (!player.isSpectator()) { if (viewerCount < 0) { viewerCount = 0; } - + ++viewerCount; BlockState blockState = this.getBlockState(); if (!blockState.getValue(BarrelBlock.OPEN)) { playSound(blockState, SoundEvents.BARREL_OPEN); setOpen(blockState, true); } - + if (level != null) { scheduleUpdate(); } } } - + private void scheduleUpdate() { level.getBlockTicks().scheduleTick(getBlockPos(), getBlockState().getBlock(), 5); } - + public void tick() { if (level != null) { viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition); if (viewerCount > 0) { scheduleUpdate(); - } else { + } + else { BlockState blockState = getBlockState(); if (!(blockState.getBlock() instanceof BaseBarrelBlock)) { setRemoved(); @@ -114,27 +115,26 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { } } } - + public void stopOpen(Player player) { if (!player.isSpectator()) { --this.viewerCount; } } - + private void setOpen(BlockState state, boolean open) { if (level != null) { level.setBlock(this.getBlockPos(), state.setValue(BarrelBlock.OPEN, open), 3); } } - + private void playSound(BlockState blockState, SoundEvent soundEvent) { if (level != null) { Vec3i vec3i = blockState.getValue(BarrelBlock.FACING).getNormal(); double d = (double) this.worldPosition.getX() + 0.5D + (double) vec3i.getX() / 2.0D; double e = (double) this.worldPosition.getY() + 0.5D + (double) vec3i.getY() / 2.0D; double f = (double) this.worldPosition.getZ() + 0.5D + (double) vec3i.getZ() / 2.0D; - level.playSound(null, d, e, f, soundEvent, SoundSource.BLOCKS, 0.5F, - this.level.random.nextFloat() * 0.1F + 0.9F); + level.playSound(null, d, e, f, soundEvent, SoundSource.BLOCKS, 0.5F, this.level.random.nextFloat() * 0.1F + 0.9F); } } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java index fa681007..f6d2f469 100644 --- a/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java @@ -15,11 +15,11 @@ public class BaseFurnaceBlockEntity extends AbstractFurnaceBlockEntity { public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) { super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING); } - + protected Component getDefaultName() { return new TranslatableComponent("container.furnace"); } - + protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { return new FurnaceMenu(syncId, playerInventory, this, this.dataAccess); } diff --git a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java index 64a9b75f..a2ebfb31 100644 --- a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java @@ -10,7 +10,7 @@ public class BaseSignBlockEntity extends SignBlockEntity { public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) { super(blockPos, blockState); } - + @Override public BlockEntityType getType() { return BaseBlockEntities.SIGN; diff --git a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java index 2f992c86..ad656251 100644 --- a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java +++ b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java @@ -1,11 +1,6 @@ package ru.bclib.blockentities; -import java.util.Collections; -import java.util.Set; -import java.util.function.Supplier; - import com.google.common.collect.Sets; - import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; @@ -13,33 +8,36 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; -public class DynamicBlockEntityType extends BlockEntityType { +import java.util.Collections; +import java.util.Set; +public class DynamicBlockEntityType extends BlockEntityType { + private final Set validBlocks = Sets.newHashSet(); private final BlockEntitySupplier factory; - + public DynamicBlockEntityType(BlockEntitySupplier supplier) { super(null, Collections.emptySet(), null); this.factory = supplier; } - + @Override - @Nullable public T create(BlockPos blockPos, BlockState blockState) { + @Nullable + public T create(BlockPos blockPos, BlockState blockState) { return factory.create(blockPos, blockState); } - + @Override public boolean isValid(BlockState blockState) { return validBlocks.contains(blockState.getBlock()); } - + public void registerBlock(Block block) { validBlocks.add(block); } - + @FunctionalInterface - public - interface BlockEntitySupplier { + public interface BlockEntitySupplier { T create(BlockPos blockPos, BlockState blockState); } } diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 5dafc0d5..192624c2 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -1,14 +1,7 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -25,15 +18,20 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.items.BaseAnvilItem; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider { public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; - + public BaseAnvilBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color)); } @@ -43,7 +41,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro super.createBlockStateDefinition(builder); builder.add(DESTRUCTION); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -52,7 +50,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro dropStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, destruction); return Lists.newArrayList(dropStack); } - + protected String getTop(ResourceLocation blockId, String block) { if (block.contains("item")) { return blockId.getPath() + "_top_0"; @@ -60,16 +58,16 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro char last = block.charAt(block.length() - 1); return blockId.getPath() + "_top_" + last; } - + @Override public abstract Item asItem(); - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -82,7 +80,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_ANVIL, textures); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { diff --git a/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java index ecf12d48..a0e2b1af 100644 --- a/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java @@ -45,14 +45,14 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { } return null; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = state.getValue(FACING); BlockPos blockPos = pos.relative(direction.getOpposite()); return canSupportCenter(world, blockPos, direction) || world.getBlockState(blockPos).is(BlockTags.LEAVES); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -62,13 +62,13 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { return state; } } - + @Override public BlockState rotate(BlockState state, Rotation rotation) { return BlocksHelper.rotateHorizontal(state, rotation, FACING); } - + @Override public BlockState mirror(BlockState state, Mirror mirror) { return BlocksHelper.mirrorHorizontal(state, mirror, FACING); diff --git a/src/main/java/ru/bclib/blocks/BaseBarkBlock.java b/src/main/java/ru/bclib/blocks/BaseBarkBlock.java index 743ff0af..7adca093 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarkBlock.java @@ -1,23 +1,23 @@ package ru.bclib.blocks; -import java.util.Optional; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.PatternsHelper; +import java.util.Optional; + public class BaseBarkBlock extends BaseRotatedPillarBlock { public BaseBarkBlock(Properties settings) { super(settings); } - + @Override protected Optional createBlockPattern(ResourceLocation blockId) { blockId = Registry.BLOCK.getKey(this); return PatternsHelper.createJson(BasePatterns.BLOCK_BASE, replacePath(blockId)); } - + private ResourceLocation replacePath(ResourceLocation blockId) { String newPath = blockId.getPath().replace("_bark", "_log_side"); return new ResourceLocation(blockId.getNamespace(), newPath); diff --git a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java index b36f8843..cde83356 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -24,7 +17,6 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.piglin.PiglinAi; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BarrelBlock; import net.minecraft.world.level.block.Block; @@ -33,6 +25,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.phys.BlockHitResult; +import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseBarrelBlockEntity; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; @@ -40,16 +33,21 @@ import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.registry.BaseBlockEntities; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { public BaseBarrelBlock(Block source) { super(FabricBlockSettings.copyOf(source).noOcclusion()); } - + @Override public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return BaseBlockEntities.BARREL.create(blockPos, blockState); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -57,24 +55,24 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { drop.add(new ItemStack(this.asItem())); return drop; } - + @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult hit) { + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { if (world.isClientSide) { return InteractionResult.SUCCESS; - } else { + } + else { BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity instanceof BaseBarrelBlockEntity) { player.openMenu((BaseBarrelBlockEntity) blockEntity); player.awardStat(Stats.OPEN_BARREL); PiglinAi.angerNearbyPiglins(player, true); } - + return InteractionResult.CONSUME; } } - + @Override public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { BlockEntity blockEntity = world.getBlockEntity(pos); @@ -82,15 +80,14 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { ((BaseBarrelBlockEntity) blockEntity).tick(); } } - + @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } - + @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, - ItemStack itemStack) { + public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { if (itemStack.hasCustomHoverName()) { BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity instanceof BaseBarrelBlockEntity) { @@ -98,41 +95,52 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { } } } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern; if (blockState.getValue(OPEN)) { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARREL_OPEN, blockId); - } else { + } + else { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { String open = blockState.getValue(OPEN) ? "_open" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + open); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + open); registerBlockModel(stateId, modelId, blockState, modelCache); Direction facing = blockState.getValue(FACING); BlockModelRotation rotation = BlockModelRotation.X0_Y0; switch (facing) { - case NORTH: rotation = BlockModelRotation.X90_Y0; break; - case EAST: rotation = BlockModelRotation.X90_Y90; break; - case SOUTH: rotation = BlockModelRotation.X90_Y180; break; - case WEST: rotation = BlockModelRotation.X90_Y270; break; - case DOWN: rotation = BlockModelRotation.X180_Y0; break; - default: break; + case NORTH: + rotation = BlockModelRotation.X90_Y0; + break; + case EAST: + rotation = BlockModelRotation.X90_Y90; + break; + case SOUTH: + rotation = BlockModelRotation.X90_Y180; + break; + case WEST: + rotation = BlockModelRotation.X90_Y270; + break; + case DOWN: + rotation = BlockModelRotation.X180_Y0; + break; + default: + break; } return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); } diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index 97878a79..bfb52a10 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -1,8 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; - import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; @@ -11,17 +8,20 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import ru.bclib.client.models.BlockModelProvider; +import java.util.Collections; +import java.util.List; + public class BaseBlock extends Block implements BlockModelProvider { public BaseBlock(Properties settings) { super(settings); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java b/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java index 6d1a0a38..0ddc700c 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java +++ b/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java @@ -6,19 +6,19 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.state.BlockState; public class BaseBlockNotFull extends BaseBlock { - + public BaseBlockNotFull(Properties settings) { super(settings); } - + public boolean canSuffocate(BlockState state, BlockGetter view, BlockPos pos) { return false; } - + public boolean isSimpleFullBlock(BlockState state, BlockGetter view, BlockPos pos) { return false; } - + public boolean allowsSpawning(BlockState state, BlockGetter view, BlockPos pos, EntityType type) { return false; } diff --git a/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java index 718a58f7..26b9cf22 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java +++ b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java @@ -1,26 +1,25 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; - import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import java.util.Collections; +import java.util.List; + public class BaseBlockWithEntity extends BaseEntityBlock { public BaseBlockWithEntity(Properties settings) { super(settings); } - + @Override public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return null; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { diff --git a/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java b/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java index a1b68b1d..68999421 100644 --- a/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java @@ -1,11 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -19,10 +13,15 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + public class BaseBookshelfBlock extends BaseBlock { public BaseBookshelfBlock(Block source) { super(FabricBlockSettings.copyOf(source)); @@ -39,14 +38,14 @@ public class BaseBookshelfBlock extends BaseBlock { } return Collections.singletonList(new ItemStack(Items.BOOK, 3)); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOOKSHELF, replacePath(blockId)); return ModelsHelper.fromPattern(pattern); } - + private ResourceLocation replacePath(ResourceLocation blockId) { String newPath = blockId.getPath().replace("_bookshelf", ""); return new ResourceLocation(blockId.getNamespace(), newPath); diff --git a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java index 5f8642ce..5fbd0d2c 100644 --- a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -20,26 +13,32 @@ import net.minecraft.world.level.block.ButtonBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { - + private final Block parent; - + protected BaseButtonBlock(Block parent, Properties properties, boolean sensitive) { super(sensitive, properties); this.parent = parent; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { @@ -47,38 +46,53 @@ public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelP Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_BUTTON, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = blockState.getValue(POWERED) ? - PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON_PRESSED, parentId) : - PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId); + Optional pattern = blockState.getValue(POWERED) ? PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON_PRESSED, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { String powered = blockState.getValue(POWERED) ? "_powered" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + powered); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + powered); registerBlockModel(stateId, modelId, blockState, modelCache); AttachFace face = blockState.getValue(FACE); boolean isCeiling = face == AttachFace.CEILING; int x = 0, y = 0; switch (face) { - case CEILING: x = 180; break; - case WALL: x = 90; break; - default: break; + case CEILING: + x = 180; + break; + case WALL: + x = 90; + break; + default: + break; } switch (blockState.getValue(FACING)) { - case NORTH: if (isCeiling) { y = 180; } break; - case EAST: y = isCeiling ? 270 : 90; break; - case SOUTH: if(!isCeiling) { y = 180; } break; - case WEST: y = isCeiling ? 90 : 270; break; - default: break; + case NORTH: + if (isCeiling) { + y = 180; + } + break; + case EAST: + y = isCeiling ? 270 : 90; + break; + case SOUTH: + if (!isCeiling) { + y = 180; + } + break; + case WEST: + y = isCeiling ? 90 : 270; + break; + default: + break; } BlockModelRotation rotation = BlockModelRotation.by(x, y); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), face == AttachFace.WALL); diff --git a/src/main/java/ru/bclib/blocks/BaseChainBlock.java b/src/main/java/ru/bclib/blocks/BaseChainBlock.java index c2a14fe3..4b3cc0ef 100644 --- a/src/main/java/ru/bclib/blocks/BaseChainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChainBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -20,6 +13,7 @@ import net.minecraft.world.level.block.ChainBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -27,40 +21,44 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped { public BaseChainBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return ModelsHelper.createItemModel(blockId); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CHAIN, blockId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { Direction.Axis axis = blockState.getValue(AXIS); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath()); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createRotatedModel(modelId, axis); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; diff --git a/src/main/java/ru/bclib/blocks/BaseChestBlock.java b/src/main/java/ru/bclib/blocks/BaseChestBlock.java index 2b89b5d2..a38d3b28 100644 --- a/src/main/java/ru/bclib/blocks/BaseChestBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChestBlock.java @@ -1,30 +1,28 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Optional; - -import net.minecraft.core.BlockPos; -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; +import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.ChestBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.registry.BaseBlockEntities; +import java.util.List; +import java.util.Optional; + public class BaseChestBlock extends ChestBlock implements BlockModelProvider { private final Block parent; @@ -37,23 +35,22 @@ public class BaseChestBlock extends ChestBlock implements BlockModelProvider { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return BaseBlockEntities.CHEST.create(blockPos, blockState); } - + @Override @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) - { + public List getDrops(BlockState state, LootContext.Builder builder) { List drop = super.getDrops(state, builder); drop.add(new ItemStack(this.asItem())); return drop; } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_CHEST, blockId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { diff --git a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java index faecc6e5..b7735daf 100644 --- a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -18,56 +11,63 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { public BaseComposterBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this.asItem())); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_COMPOSTER, blockId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); registerBlockModel(stateId, modelId, blockState, modelCache); - + MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); LEVEL.getPossibleValues().forEach(level -> { if (level > 0) { ResourceLocation contentId; if (level > 7) { contentId = new ResourceLocation("block/composter_contents_ready"); - } else { + } + else { contentId = new ResourceLocation("block/composter_contents" + level); } builder.part(contentId).setCondition(state -> state.getValue(LEVEL).equals(level)).add(); } }); builder.part(modelId).add(); - + return builder.build(); } } diff --git a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java index 570758fe..f4718e40 100644 --- a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -17,34 +10,41 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.CraftingTableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; + public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { public BaseCraftingTableBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this.asItem())); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { String blockName = blockId.getPath(); Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SIDED, new HashMap() { private static final long serialVersionUID = 1L; + { put("%modid%", blockId.getNamespace()); put("%particle%", blockName + "_front"); diff --git a/src/main/java/ru/bclib/blocks/BaseCropBlock.java b/src/main/java/ru/bclib/blocks/BaseCropBlock.java index e395d338..ec0ce04b 100644 --- a/src/main/java/ru/bclib/blocks/BaseCropBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCropBlock.java @@ -1,11 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Random; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -31,6 +26,10 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; +import java.util.Collections; +import java.util.List; +import java.util.Random; + public class BaseCropBlock extends BasePlantBlock { private static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 14, 14); public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); @@ -39,12 +38,7 @@ public class BaseCropBlock extends BasePlantBlock { private final Item drop; public BaseCropBlock(Item drop, Block... terrain) { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.HOES) - .breakByHand(true) - .sound(SoundType.GRASS) - .randomTicks() - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.HOES).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission()); this.drop = drop; this.terrain = terrain; this.registerDefaultState(defaultBlockState().setValue(AGE, 0)); @@ -57,7 +51,7 @@ public class BaseCropBlock extends BasePlantBlock { @Override protected boolean isTerrain(BlockState state) { - for (Block block: terrain) { + for (Block block : terrain) { if (state.is(block)) { return true; } @@ -106,7 +100,7 @@ public class BaseCropBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return state.getValue(AGE) < 3; } - + @Override @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { diff --git a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java index 1c2c6245..c903f642 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -23,6 +16,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.DoorHingeSide; import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -30,25 +24,29 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModelProvider { public BaseDoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion()); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { if (state.getValue(HALF) == DoubleBlockHalf.LOWER) return Collections.singletonList(new ItemStack(this.asItem())); - else - return Collections.emptyList(); + else return Collections.emptyList(); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { @@ -64,11 +62,12 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel case TOP: pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP, resourceLocation); break; - default: break; + default: + break; } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -81,23 +80,27 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel case EAST: if (hinge && open) { rotation = BlockModelRotation.X0_Y90; - } else if (open) { + } + else if (open) { rotation = BlockModelRotation.X0_Y270; } break; case SOUTH: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y90; - } else if (hinge) { + } + else if (hinge) { rotation = BlockModelRotation.X0_Y180; } break; case WEST: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y180; - } else if (hinge) { + } + else if (hinge) { rotation = BlockModelRotation.X0_Y270; - } else { + } + else { rotation = BlockModelRotation.X0_Y90; } break; @@ -105,17 +108,17 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel default: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y270; - } else if (!hinge) { + } + else if (!hinge) { rotation = BlockModelRotation.X0_Y180; } break; } - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_" + doorType); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + doorType); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); } - + protected DoorType getDoorType(BlockState blockState) { boolean isHinge = isHinge(blockState.getValue(HINGE), blockState.getValue(OPEN)); switch (blockState.getValue(HALF)) { @@ -128,34 +131,30 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel } return DoorType.BOTTOM; } - + private boolean isHinge(DoorHingeSide hingeSide, boolean open) { boolean isHinge = hingeSide == DoorHingeSide.RIGHT; return isHinge && !open || !isHinge && open; } - + protected enum DoorType implements StringRepresentable { - BOTTOM_HINGE("bottom_hinge"), - TOP_HINGE("top_hinge"), - BOTTOM("bottom"), - TOP("top"); - + BOTTOM_HINGE("bottom_hinge"), TOP_HINGE("top_hinge"), BOTTOM("bottom"), TOP("top"); + private final String name; - + DoorType(String name) { this.name = name; } - + public boolean isHinge() { - return this == BOTTOM_HINGE || - this == TOP_HINGE; + return this == BOTTOM_HINGE || this == TOP_HINGE; } - + @Override public String toString() { return getSerializedName(); } - + @Override public String getSerializedName() { return name; diff --git a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index 73f0ed6c..05bf1f15 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -1,10 +1,6 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Random; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -38,6 +34,9 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +import java.util.List; +import java.util.Random; + @SuppressWarnings("deprecation") public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); @@ -45,21 +44,12 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I public static final BooleanProperty TOP = BooleanProperty.create("top"); public BaseDoublePlantBlock() { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } public BaseDoublePlantBlock(int light) { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .lightLevel((state) -> state.getValue(TOP) ? light : 0) - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).lightLevel((state) -> state.getValue(TOP) ? light : 0).noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } @@ -67,18 +57,18 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(TOP, ROTATION); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { Vec3 vec3d = state.getOffset(view, pos); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -91,7 +81,7 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I BlockState up = world.getBlockState(pos.above()); return state.getValue(TOP) ? down.getBlock() == this : isTerrain(down) && (up.getBlock() == this); } - + protected abstract boolean isTerrain(BlockState state); @Override @@ -123,17 +113,17 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { return true; } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); diff --git a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java index 85adff6e..7c721437 100644 --- a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -20,12 +13,18 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FenceBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { private final Block parent; @@ -33,13 +32,13 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(source).noOcclusion()); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { @@ -47,7 +46,7 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_FENCE, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -62,27 +61,22 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_side"); + ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); + ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache); - + MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST)) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH)) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST)) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); builder.part(postId).add(); - + return builder.build(); } } diff --git a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index 925a3e45..ac6624ba 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -41,7 +41,7 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider public BaseFurnaceBlock(Block source) { super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0)); } - + @Override public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return new BaseFurnaceBlockEntity(blockPos, blockState); @@ -55,7 +55,7 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider player.awardStat(Stats.INTERACT_WITH_FURNACE); } } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -69,34 +69,34 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider textures.put("%front%", blockName + "_front_on"); textures.put("%glow%", blockName + "_glow"); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE_LIT, textures); - } else { + } + else { textures.put("%front%", blockName + "_front"); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE, textures); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { String lit = blockState.getValue(LIT) ? "_lit" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + lit); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + lit); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -110,13 +110,13 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider } return drop; } - + @Override @Nullable public BlockEntityTicker getTicker(Level level, BlockState blockState, BlockEntityType blockEntityType) { return createFurnaceTicker(level, blockEntityType, BaseBlockEntities.FURNACE); } - + @Nullable protected static BlockEntityTicker createFurnaceTicker(Level level, BlockEntityType blockEntityType, BlockEntityType blockEntityType2) { return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick); diff --git a/src/main/java/ru/bclib/blocks/BaseGateBlock.java b/src/main/java/ru/bclib/blocks/BaseGateBlock.java index d765ca2d..7b239a7e 100644 --- a/src/main/java/ru/bclib/blocks/BaseGateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseGateBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FenceGateBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { private final Block parent; @@ -31,19 +30,19 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider super(FabricBlockSettings.copyOf(source).noOcclusion()); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -52,23 +51,21 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider ResourceLocation parentId = Registry.BLOCK.getKey(parent); Optional pattern; if (inWall) { - pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN_WALL, parentId) : - PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); - } else { - pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN, parentId) : - PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId); + pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN_WALL, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); + } + else { + pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { boolean inWall = blockState.getValue(IN_WALL); boolean isOpen = blockState.getValue(OPEN); String state = "" + (inWall ? "_wall" : "") + (isOpen ? "_open" : "_closed"); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + state); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), true, false); } diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index 93939d8f..d5020846 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -1,10 +1,5 @@ package ru.bclib.blocks; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -31,6 +26,7 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -39,6 +35,9 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +import java.util.Map; +import java.util.Optional; + @SuppressWarnings("deprecation") public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; @@ -47,17 +46,17 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B protected static final VoxelShape WEST_SHAPE = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); protected static final VoxelShape SOUTH_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); protected static final VoxelShape NORTH_SHAPE = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); - + public BaseLadderBlock(Block block) { super(FabricBlockSettings.copyOf(block).noOcclusion()); } - + @Override protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(FACING); stateManager.add(WATERLOGGED); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return switch (state.getValue(FACING)) { @@ -67,32 +66,32 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B default -> NORTH_SHAPE; }; } - + private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) { BlockState blockState = world.getBlockState(pos); return !blockState.isSignalSource() && blockState.isFaceSturdy(world, pos, side); } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = state.getValue(FACING); return canPlaceOn(world, pos.relative(direction.getOpposite()), direction); } - + @Override - public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, - LevelAccessor world, BlockPos pos, BlockPos neighborPos) { + public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (facing.getOpposite() == state.getValue(FACING) && !state.canSurvive(world, pos)) { return Blocks.AIR.defaultBlockState(); - } else { + } + else { if (state.getValue(WATERLOGGED)) { world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); } - + return super.updateShape(state, facing, neighborState, world, pos, neighborPos); } } - + @Override public BlockState getStateForPlacement(BlockPlaceContext ctx) { BlockState blockState; @@ -102,13 +101,13 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B return null; } } - + blockState = defaultBlockState(); LevelReader worldView = ctx.getLevel(); BlockPos blockPos = ctx.getClickedPos(); FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); Direction[] directions = ctx.getNearestLookingDirections(); - + for (Direction direction : directions) { if (direction.getAxis().isHorizontal()) { blockState = blockState.setValue(FACING, direction.getOpposite()); @@ -117,43 +116,43 @@ public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, B } } } - + return null; } - + @Override public BlockState rotate(BlockState state, Rotation rotation) { return BlocksHelper.rotateHorizontal(state, rotation, FACING); } - + @Override public BlockState mirror(BlockState state, Mirror mirror) { return BlocksHelper.mirrorHorizontal(state, mirror, FACING); } - + @Override public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return ModelsHelper.createBlockItem(blockId); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_LADDER, blockId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 4e644f8e..e77d96c5 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,10 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; @@ -24,38 +20,27 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.MHelper; +import java.util.Collections; +import java.util.List; + public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { private final Block sapling; public BaseLeavesBlock(Block sapling, MaterialColor color) { - super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) - .mapColor(color) - .breakByTool(FabricToolTags.HOES) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).breakByHand(true).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); this.sapling = sapling; } public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { - super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) - .mapColor(color) - .luminance(light) - .breakByTool(FabricToolTags.HOES) - .breakByTool(FabricToolTags.SHEARS) - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).luminance(light).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); this.sapling = sapling; } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -72,7 +57,7 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, } return MHelper.RANDOM.nextInt(16) == 0 ? Lists.newArrayList(new ItemStack(sapling)) : Lists.newArrayList(); } - + @Override public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java index d4ecb9bf..d29ff46d 100644 --- a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -21,6 +14,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -28,17 +22,22 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, IRenderTyped { public BaseMetalBarsBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion()); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + public Optional getModelString(String block) { ResourceLocation blockId = Registry.BLOCK.getKey(this); if (block.contains("item")) { @@ -51,13 +50,13 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi return PatternsHelper.createJson(BasePatterns.BLOCK_BARS_SIDE, blockId); } } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return ModelsHelper.createBlockItem(resourceLocation); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -72,32 +71,25 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_side"); + ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); + ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache); - + ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - builder.part(postId).setCondition(state -> - !state.getValue(NORTH) && !state.getValue(EAST) && - !state.getValue(SOUTH) && !state.getValue(WEST)).add(); + builder.part(postId).setCondition(state -> !state.getValue(NORTH) && !state.getValue(EAST) && !state.getValue(SOUTH) && !state.getValue(WEST)).add(); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST)) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH)) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST)) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); - + builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + return builder.build(); } - + @Environment(EnvType.CLIENT) public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { if (direction.getAxis().isVertical() && stateFrom.getBlock() == this && !stateFrom.equals(state)) { @@ -105,7 +97,7 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi } return super.skipRendering(state, stateFrom, direction); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index 9f0bfaf2..ebf88679 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -1,9 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Random; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; @@ -23,22 +19,21 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.util.MHelper; +import java.util.Collections; +import java.util.List; + public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final Item dropItem; private final int minCount; private final int maxCount; public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { - super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) - .hardness(3F) - .resistance(9F) - .requiresCorrectToolForDrops() - .sound(SoundType.STONE), UniformInt.of(1, experience)); + super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND).hardness(3F).resistance(9F).requiresCorrectToolForDrops().sound(SoundType.STONE), UniformInt.of(1, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -56,14 +51,15 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { return Collections.singletonList(new ItemStack(dropItem, max)); } count = MHelper.randRange(min, max, MHelper.RANDOM); - } else { + } + else { count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM); } return Collections.singletonList(new ItemStack(dropItem, count)); } return Collections.emptyList(); } - + @Override public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BasePathBlock.java b/src/main/java/ru/bclib/blocks/BasePathBlock.java index 75060542..d39e1891 100644 --- a/src/main/java/ru/bclib/blocks/BasePathBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePathBlock.java @@ -1,14 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -28,16 +20,22 @@ import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @SuppressWarnings("deprecation") public class BasePathBlock extends BaseBlockNotFull { private static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 15, 16); - + private Block baseBlock; - + public BasePathBlock(Block source) { super(FabricBlockSettings.copyOf(source).isValidSpawn((state, world, pos, type) -> false)); this.baseBlock = Blocks.DIRT; @@ -72,7 +70,7 @@ public class BasePathBlock extends BaseBlockNotFull { public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -87,7 +85,7 @@ public class BasePathBlock extends BaseBlockNotFull { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PATH, textures); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index b3181e9d..c7818a90 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -1,10 +1,6 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Random; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -33,6 +29,9 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.List; +import java.util.Random; + @SuppressWarnings("deprecation") public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); @@ -46,45 +45,36 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender } public BasePlantBlock(boolean replaceable) { - super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); } public BasePlantBlock(boolean replaceable, int light) { - super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.GRASS) - .noCollission()); + super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission()); } public BasePlantBlock(Properties settings) { super(settings); } - + protected abstract boolean isTerrain(BlockState state); - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { Vec3 vec3d = state.getOffset(view, pos); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); return isTerrain(down); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -110,17 +100,17 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { return true; } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); diff --git a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java index e78a0189..89749c6e 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java @@ -1,7 +1,5 @@ package ru.bclib.blocks; -import java.util.Random; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -15,16 +13,13 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.Material; +import java.util.Random; + public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public BasePlantWithAgeBlock() { - this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .randomTicks() - .noCollission()); + this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission()); } public BasePlantWithAgeBlock(Properties settings) { @@ -53,7 +48,7 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { diff --git a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java index 9cd483f4..dd76e216 100644 --- a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.PressurePlateBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { private final Block parent; @@ -31,19 +30,19 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM super(rule, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().strength(0.5F)); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { @@ -51,18 +50,18 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM Optional pattern; if (blockState.getValue(POWERED)) { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } else { + } + else { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { String state = blockState.getValue(POWERED) ? "_down" : "_up"; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + state); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createBlockSimple(modelId); } diff --git a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java index e5d3af50..d866c9d2 100644 --- a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -18,10 +11,16 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { public BaseRotatedPillarBlock(Properties settings) { super(settings); @@ -30,26 +29,26 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM public BaseRotatedPillarBlock(Block block) { super(FabricBlockSettings.copyOf(block)); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { Optional pattern = createBlockPattern(blockId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -57,7 +56,7 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createRotatedModel(modelId, blockState.getValue(AXIS)); } - + protected Optional createBlockPattern(ResourceLocation blockId) { return PatternsHelper.createBlockPillar(blockId); } diff --git a/src/main/java/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index 5eeb16a0..98ed4864 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -1,10 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -42,23 +37,22 @@ import net.minecraft.world.level.material.Fluids; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ISpetialItem; import ru.bclib.util.BlocksHelper; +import java.util.Collections; +import java.util.List; + @SuppressWarnings("deprecation") public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem { public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); - private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] { - Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), - Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), - Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), - Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D) - }; - + private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] {Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D)}; + private final Block parent; public BaseSignBlock(Block source) { @@ -66,17 +60,17 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe this.registerDefaultState(this.stateDefinition.any().setValue(ROTATION, 0).setValue(FLOOR, false).setValue(WATERLOGGED, false)); this.parent = source; } - + @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { builder.add(ROTATION, FLOOR, WATERLOGGED); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return state.getValue(FLOOR) ? SHAPE : WALL_SHAPES[state.getValue(ROTATION) >> 2]; } - + @Override public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return new BaseSignBlockEntity(blockPos, blockState); @@ -90,13 +84,14 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe if (!world.isClientSide) { sign.setAllowedPlayerEditor(placer.getUUID()); ((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos)); - } else { + } + else { sign.setEditable(true); } } } } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (state.getValue(WATERLOGGED)) { @@ -107,7 +102,7 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe } return super.updateShape(state, facing, neighborState, world, pos, neighborPos); } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { if (!state.getValue(FLOOR)) { @@ -118,21 +113,20 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe return world.getBlockState(pos.below()).getMaterial().isSolid(); } } - + @Override public BlockState getStateForPlacement(BlockPlaceContext ctx) { if (ctx.getClickedFace() == Direction.UP) { FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); - return this.defaultBlockState().setValue(FLOOR, true) - .setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15) - .setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); - } else if (ctx.getClickedFace() != Direction.DOWN) { + return this.defaultBlockState().setValue(FLOOR, true).setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15).setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + } + else if (ctx.getClickedFace() != Direction.DOWN) { BlockState blockState = this.defaultBlockState(); FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); LevelReader worldView = ctx.getLevel(); BlockPos blockPos = ctx.getClickedPos(); Direction[] directions = ctx.getNearestLookingDirections(); - + for (Direction direction : directions) { if (direction.getAxis().isHorizontal()) { Direction dir = direction.getOpposite(); @@ -144,22 +138,22 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe } } } - + return null; } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { ResourceLocation parentId = Registry.BLOCK.getKey(parent); return ModelsHelper.createBlockEmpty(parentId); } - + @Override public BlockState rotate(BlockState state, Rotation rotation) { return state.setValue(ROTATION, rotation.rotate((Integer) state.getValue(ROTATION), 16)); } - + @Override public BlockState mirror(BlockState state, Mirror mirror) { return state.setValue(ROTATION, mirror.mirror((Integer) state.getValue(ROTATION), 16)); @@ -169,24 +163,24 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { // TODO Auto-generated method stub return super.canPlaceLiquid(world, pos, state, fluid); } - + @Override public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { // TODO Auto-generated method stub return super.placeLiquid(world, pos, state, fluidState); } - + @Override public int getStackSize() { return 16; } - + @Override public boolean canPlaceOnWater() { return false; diff --git a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java index 73c2e109..4d949ca5 100644 --- a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -21,11 +14,17 @@ import net.minecraft.world.level.block.SlabBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { private final Block parent; @@ -33,19 +32,19 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(source)); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -53,18 +52,18 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { Optional pattern; if (blockState.getValue(TYPE) == SlabType.DOUBLE) { pattern = PatternsHelper.createBlockSimple(parentId); - } else { + } + else { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SLAB, parentId); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { SlabType type = blockState.getValue(TYPE); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_" + type); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + type); registerBlockModel(stateId, modelId, blockState, modelCache); if (type == SlabType.TOP) { return ModelsHelper.createMultiVariant(modelId, BlockModelRotation.X180_Y0.getRotation(), true); diff --git a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java index 2f057e78..5c0c176c 100644 --- a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -22,11 +15,17 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.level.block.state.properties.StairsShape; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseStairsBlock extends StairBlock implements BlockModelProvider { private final Block parent; @@ -41,13 +40,13 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -68,7 +67,7 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -77,21 +76,21 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { switch (shape) { case INNER_LEFT: case INNER_RIGHT: - state = "_inner"; break; + state = "_inner"; + break; case OUTER_LEFT: case OUTER_RIGHT: - state = "_outer"; break; + state = "_outer"; + break; default: state = ""; } ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); registerBlockModel(stateId, modelId, blockState, modelCache); - + boolean isTop = blockState.getValue(HALF) == Half.TOP; - boolean isLeft = shape == StairsShape.INNER_LEFT || - shape == StairsShape.OUTER_LEFT; - boolean isRight = shape == StairsShape.INNER_RIGHT || - shape == StairsShape.OUTER_RIGHT; + boolean isLeft = shape == StairsShape.INNER_LEFT || shape == StairsShape.OUTER_LEFT; + boolean isRight = shape == StairsShape.INNER_RIGHT || shape == StairsShape.OUTER_RIGHT; int y = 0; int x = isTop ? 180 : 0; switch (blockState.getValue(FACING)) { diff --git a/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java index aabc865b..6c6bf59b 100644 --- a/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java @@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.level.block.Block; public class BaseStoneButtonBlock extends BaseButtonBlock { - + public BaseStoneButtonBlock(Block source) { super(source, FabricBlockSettings.copyOf(source).noOcclusion(), false); } - + @Override protected SoundEvent getSound(boolean clicked) { return clicked ? SoundEvents.STONE_BUTTON_CLICK_ON : SoundEvents.STONE_BUTTON_CLICK_OFF; diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index fd0537c1..5516246e 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -1,15 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - -import org.jetbrains.annotations.Nullable; - import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -41,14 +32,21 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.sound.BlockSounds; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + @SuppressWarnings("deprecation") public class BaseTerrainBlock extends BaseBlock { - + private final Block baseBlock; private Block pathBlock; @@ -60,11 +58,11 @@ public class BaseTerrainBlock extends BaseBlock { public void setPathBlock(Block roadBlock) { this.pathBlock = roadBlock; } - + public Block getBaseBlock() { return baseBlock; } - + @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { if (pathBlock != null && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) { @@ -95,7 +93,7 @@ public class BaseTerrainBlock extends BaseBlock { world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); } } - + public boolean canStay(BlockState state, LevelReader worldView, BlockPos pos) { BlockPos blockPos = pos.above(); BlockState blockState = worldView.getBlockState(blockPos); @@ -116,7 +114,7 @@ public class BaseTerrainBlock extends BaseBlock { public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -131,7 +129,7 @@ public class BaseTerrainBlock extends BaseBlock { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TOP_SIDE_BOTTOM, textures); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { diff --git a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java index b0167f0e..fd2c4d5b 100644 --- a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java @@ -1,13 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -21,6 +13,7 @@ import net.minecraft.world.level.block.TrapDoorBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -28,11 +21,17 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, BlockModelProvider { public BaseTrapdoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion()); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -43,19 +42,20 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { String name = resourceLocation.getPath(); Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TRAPDOOR, new HashMap() { private static final long serialVersionUID = 1L; + { put("%modid%", resourceLocation.getNamespace()); put("%texture%", name); @@ -64,7 +64,7 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl }); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -87,7 +87,8 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl case WEST: y = (isTop && isOpen) ? 90 : 270; break; - default: break; + default: + break; } BlockModelRotation rotation = BlockModelRotation.by(x, y); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); diff --git a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java index 2254146b..50201937 100644 --- a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java @@ -17,20 +17,11 @@ import net.minecraft.world.level.material.Material; public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock implements LiquidBlockContainer { public BaseUnderwaterWallPlantBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); } public BaseUnderwaterWallPlantBlock(int light) { - super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.WET_GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission()); } public BaseUnderwaterWallPlantBlock(Properties settings) { @@ -41,7 +32,7 @@ public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock im public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { return false; } - + @Override public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { return false; diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 108dc183..3437a49b 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -1,10 +1,6 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Random; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -37,6 +33,9 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; +import java.util.List; +import java.util.Random; + @SuppressWarnings("deprecation") public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; @@ -51,12 +50,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon } public BaseVineBlock(int light, boolean bottomOnly) { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light) - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light).noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM)); } @@ -64,13 +58,13 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(SHAPE); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { Vec3 vec3d = state.getOffset(view, pos); return VOXEL_SHAPE.move(vec3d.x, vec3d.y, vec3d.z); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; @@ -79,7 +73,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon public boolean canGenerate(BlockState state, LevelReader world, BlockPos pos) { return isSupport(state, world, pos); } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { return isSupport(state, world, pos); @@ -89,17 +83,15 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon BlockState up = world.getBlockState(pos.above()); return up.is(this) || up.is(BlockTags.LEAVES) || canSupportCenter(world, pos.above(), Direction.DOWN); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { return Blocks.AIR.defaultBlockState(); } else { - if (world.getBlockState(pos.below()).getBlock() != this) - return state.setValue(SHAPE, TripleShape.BOTTOM); - else if (world.getBlockState(pos.above()).getBlock() != this) - return state.setValue(SHAPE, TripleShape.TOP); + if (world.getBlockState(pos.below()).getBlock() != this) return state.setValue(SHAPE, TripleShape.BOTTOM); + else if (world.getBlockState(pos.above()).getBlock() != this) return state.setValue(SHAPE, TripleShape.TOP); return state.setValue(SHAPE, TripleShape.MIDDLE); } } @@ -119,7 +111,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { while (world.getBlockState(pos).getBlock() == this) { @@ -127,7 +119,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon } return world.getBlockState(pos).isAir(); } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { while (world.getBlockState(pos).getBlock() == this) { @@ -135,7 +127,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon } return world.isEmptyBlock(pos); } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { while (world.getBlockState(pos).getBlock() == this) { diff --git a/src/main/java/ru/bclib/blocks/BaseWallBlock.java b/src/main/java/ru/bclib/blocks/BaseWallBlock.java index 031f4d31..682bea1e 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -21,11 +14,17 @@ import net.minecraft.world.level.block.WallBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.WallSide; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseWallBlock extends WallBlock implements BlockModelProvider { private final Block parent; @@ -34,13 +33,13 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(source).noOcclusion()); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { @@ -48,7 +47,7 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_WALL, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -66,37 +65,28 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_side"); - ResourceLocation sideTallId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + "_side_tall"); + ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); + ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); + ResourceLocation sideTallId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side_tall"); registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache); registerBlockModel(sideTallId, sideTallId, blockState, modelCache); - + ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); builder.part(sideId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.LOW).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); + builder.part(sideId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); builder.part(sideTallId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideTallId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); + builder.part(sideTallId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); + builder.part(sideTallId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); builder.part(postId).setCondition(state -> state.getValue(UP)).add(); - + return builder.build(); } } diff --git a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java index 9adb0c91..5a398081 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java @@ -1,10 +1,7 @@ package ru.bclib.blocks; -import java.util.EnumMap; - import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -28,29 +25,18 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.util.BlocksHelper; +import java.util.EnumMap; + public abstract class BaseWallPlantBlock extends BasePlantBlock { - private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of( - Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16), - Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8), - Direction.WEST, Block.box(8, 1, 1, 16, 15, 15), - Direction.EAST, Block.box(0, 1, 1, 8, 15, 15))); + private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of(Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16), Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8), Direction.WEST, Block.box(8, 1, 1, 16, 15, 15), Direction.EAST, Block.box(0, 1, 1, 8, 15, 15))); public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public BaseWallPlantBlock() { - this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); } public BaseWallPlantBlock(int light) { - this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.GRASS) - .noCollission()); + this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission()); } public BaseWallPlantBlock(Properties settings) { @@ -61,17 +47,17 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(FACING); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPES.get(state.getValue(FACING)); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.NONE; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = state.getValue(FACING); @@ -101,7 +87,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { } return null; } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -117,7 +103,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { public BlockState rotate(BlockState state, Rotation rotation) { return BlocksHelper.rotateHorizontal(state, rotation, FACING); } - + @Override @SuppressWarnings("deprecation") public BlockState mirror(BlockState state, Mirror mirror) { diff --git a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java index 28bbe68e..20b2f8f7 100644 --- a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java @@ -1,12 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -19,11 +12,17 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.WeightedPressurePlateBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { private final Block parent; @@ -31,19 +30,19 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement super(15, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F)); this.parent = source; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { @@ -51,18 +50,18 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement Optional pattern; if (blockState.getValue(POWER) > 0) { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } else { + } + else { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { String state = blockState.getValue(POWER) > 0 ? "_down" : "_up"; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + state); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createBlockSimple(modelId); } diff --git a/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java index daab12c0..3d92013b 100644 --- a/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java @@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.level.block.Block; public class BaseWoodenButtonBlock extends BaseButtonBlock { - + public BaseWoodenButtonBlock(Block source) { super(source, FabricBlockSettings.copyOf(source).strength(0.5F, 0.5F).noOcclusion(), true); } - + @Override protected SoundEvent getSound(boolean clicked) { return clicked ? SoundEvents.WOODEN_BUTTON_CLICK_ON : SoundEvents.WOODEN_BUTTON_CLICK_OFF; diff --git a/src/main/java/ru/bclib/blocks/BlockProperties.java b/src/main/java/ru/bclib/blocks/BlockProperties.java index 7bf55492..b6a71150 100644 --- a/src/main/java/ru/bclib/blocks/BlockProperties.java +++ b/src/main/java/ru/bclib/blocks/BlockProperties.java @@ -24,9 +24,7 @@ public class BlockProperties { public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); public enum TripleShape implements StringRepresentable { - TOP("top", 0), - MIDDLE("middle", 1), - BOTTOM("bottom", 2); + TOP("top", 0), MIDDLE("middle", 1), BOTTOM("bottom", 2); private final String name; private final int index; @@ -35,7 +33,7 @@ public class BlockProperties { this.name = name; this.index = index; } - + @Override public String getSerializedName() { return name; @@ -56,18 +54,14 @@ public class BlockProperties { } public enum PentaShape implements StringRepresentable { - BOTTOM("bottom"), - PRE_BOTTOM("pre_bottom"), - MIDDLE("middle"), - PRE_TOP("pre_top"), - TOP("top"); + BOTTOM("bottom"), PRE_BOTTOM("pre_bottom"), MIDDLE("middle"), PRE_TOP("pre_top"), TOP("top"); private final String name; PentaShape(String name) { this.name = name; } - + @Override public String getSerializedName() { return name; diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 38548c2f..42c727b6 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -1,13 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Random; - -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -26,10 +18,12 @@ import net.minecraft.world.level.block.SaplingBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; @@ -37,65 +31,57 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Random; + @SuppressWarnings("deprecation") public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); - + public FeatureSaplingBlock() { - super(null, FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks()); + super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).instabreak().sound(SoundType.GRASS).randomTicks()); } - + public FeatureSaplingBlock(int light) { - super(null, FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .luminance(light) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks()); + super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).luminance(light).instabreak().sound(SoundType.GRASS).randomTicks()); } - + protected abstract Feature getFeature(); @Override public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { - if (!canSurvive(state, world, pos)) - return Blocks.AIR.defaultBlockState(); - else - return state; + if (!canSurvive(state, world, pos)) return Blocks.AIR.defaultBlockState(); + else return state; } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return random.nextInt(16) == 0; } - + @Override public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null); getFeature().place(context); } - + @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { this.tick(state, world, pos, random); } - + @Override public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { super.tick(state, world, pos, random); @@ -103,18 +89,18 @@ public abstract class FeatureSaplingBlock extends SaplingBlock implements IRende performBonemeal(world, random, pos, state); } } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return ModelsHelper.createBlockItem(resourceLocation); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index ac46338c..8fe7c375 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -9,28 +9,13 @@ import ru.bclib.interfaces.IRenderTyped; public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped { public SimpleLeavesBlock(MaterialColor color) { - super(FabricBlockSettings.of(Material.LEAVES) - .strength(0.2F) - .mapColor(color) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.of(Material.LEAVES).strength(0.2F).mapColor(color).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); } public SimpleLeavesBlock(MaterialColor color, int light) { - super(FabricBlockSettings.of(Material.LEAVES) - .luminance(light) - .mapColor(color) - .strength(0.2F) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.of(Material.LEAVES).luminance(light).mapColor(color).strength(0.2F).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; diff --git a/src/main/java/ru/bclib/blocks/StalactiteBlock.java b/src/main/java/ru/bclib/blocks/StalactiteBlock.java index 50401565..11ae5224 100644 --- a/src/main/java/ru/bclib/blocks/StalactiteBlock.java +++ b/src/main/java/ru/bclib/blocks/StalactiteBlock.java @@ -1,10 +1,5 @@ package ru.bclib.blocks; -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -37,29 +32,33 @@ import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.Map; +import java.util.Optional; + @SuppressWarnings("deprecation") public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped { public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; public static final IntegerProperty SIZE = BlockProperties.SIZE; private static final VoxelShape[] SHAPES; - + public StalactiteBlock(Block source) { super(FabricBlockSettings.copy(source).noOcclusion()); this.registerDefaultState(getStateDefinition().any().setValue(SIZE, 0).setValue(IS_FLOOR, true).setValue(WATERLOGGED, false)); } - + @Override protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(WATERLOGGED, IS_FLOOR, SIZE); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPES[state.getValue(SIZE)]; @@ -95,7 +94,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg } } } - + @Override public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { boolean hasUp = isThis(world, pos.above()); @@ -183,7 +182,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg } return state; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { int size = state.getValue(SIZE); @@ -208,22 +207,21 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS_SHADED, resourceLocation); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { BlockModelRotation rotation = blockState.getValue(IS_FLOOR) ? BlockModelRotation.X0_Y0 : BlockModelRotation.X180_Y0; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - stateId.getPath() + "_" + blockState.getValue(SIZE)); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), stateId.getPath() + "_" + blockState.getValue(SIZE)); registerBlockModel(modelId, modelId, blockState, modelCache); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); } - + @Override public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { return false; } - + @Override public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { return false; @@ -233,12 +231,12 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg public FluidState getFluidState(BlockState state) { return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + static { float end = 2F / 8F; float start = 5F / 8F; diff --git a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java index 252ec776..e04b13c3 100644 --- a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java @@ -1,15 +1,7 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - -import org.jetbrains.annotations.Nullable; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -34,11 +26,17 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.phys.BlockHitResult; +import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + public class TripleTerrainBlock extends BaseTerrainBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; @@ -46,7 +44,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { super(baseBlock, baseBlock.defaultMaterialColor()); this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); } - + public TripleTerrainBlock(Block baseBlock, MaterialColor color) { super(baseBlock, color); this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); @@ -63,7 +61,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { TripleShape shape = dir == Direction.UP ? TripleShape.BOTTOM : dir == Direction.DOWN ? TripleShape.TOP : TripleShape.MIDDLE; return defaultBlockState().setValue(SHAPE, shape); } - + @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { TripleShape shape = state.getValue(SHAPE); @@ -78,7 +76,8 @@ public class TripleTerrainBlock extends BaseTerrainBlock { TripleShape shape = state.getValue(SHAPE); if (shape == TripleShape.BOTTOM) { super.randomTick(state, world, pos, random); - } else if (random.nextInt(16) == 0) { + } + else if (random.nextInt(16) == 0) { boolean bottom = canStayBottom(world, pos); if (shape == TripleShape.TOP) { if (!bottom) { @@ -89,9 +88,11 @@ public class TripleTerrainBlock extends BaseTerrainBlock { boolean top = canStay(state, world, pos) || isMiddle(world.getBlockState(pos.above())); if (!top && !bottom) { world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); - } else if (top && !bottom) { + } + else if (top && !bottom) { world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.BOTTOM)); - } else if (!top) { + } + else if (!top) { world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.TOP)); } } @@ -103,19 +104,21 @@ public class TripleTerrainBlock extends BaseTerrainBlock { BlockState blockState = world.getBlockState(blockPos); if (isMiddle(blockState)) { return true; - } else if (blockState.getFluidState().getAmount() == 8) { + } + else if (blockState.getFluidState().getAmount() == 8) { return false; - } else { + } + else { return !blockState.isFaceSturdy(world, blockPos, Direction.UP); } } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -124,7 +127,8 @@ public class TripleTerrainBlock extends BaseTerrainBlock { if (isMiddle(blockState)) { ResourceLocation topId = new ResourceLocation(blockId.getNamespace(), path + "_top"); pattern = PatternsHelper.createBlockSimple(topId); - } else { + } + else { Map textures = Maps.newHashMap(); textures.put("%top%", "betterend:block/" + path + "_top"); textures.put("%side%", "betterend:block/" + path + "_side"); @@ -133,14 +137,13 @@ public class TripleTerrainBlock extends BaseTerrainBlock { } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { boolean isMiddle = isMiddle(blockState); String middle = isMiddle ? "_middle" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), - "block/" + stateId.getPath() + middle); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + middle); registerBlockModel(stateId, modelId, blockState, modelCache); if (isMiddle) { List variants = Lists.newArrayList(); @@ -148,17 +151,13 @@ public class TripleTerrainBlock extends BaseTerrainBlock { variants.add(new Variant(modelId, rotation.getRotation(), false, 1)); } return new MultiVariant(variants); - } else if (blockState.getValue(SHAPE) == TripleShape.TOP) { - return new MultiVariant(Lists.newArrayList( - new Variant(modelId, BlockModelRotation.X180_Y0.getRotation(), false, 1), - new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), - new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), - new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1) - )); + } + else if (blockState.getValue(SHAPE) == TripleShape.TOP) { + return new MultiVariant(Lists.newArrayList(new Variant(modelId, BlockModelRotation.X180_Y0.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1))); } return ModelsHelper.createRandomTopModel(modelId); } - + protected boolean isMiddle(BlockState blockState) { return blockState.is(this) && blockState.getValue(SHAPE) == TripleShape.MIDDLE; } diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index 4d168107..dd92f183 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -1,10 +1,6 @@ package ru.bclib.blocks; -import java.util.List; -import java.util.Random; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -37,42 +33,36 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.List; +import java.util.Random; + @SuppressWarnings("deprecation") public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public UnderwaterPlantBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); } public UnderwaterPlantBlock(int light) { - super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.WET_GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission()); } public UnderwaterPlantBlock(Properties settings) { super(settings); } - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { Vec3 vec3d = state.getOffset(view, pos); return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -81,7 +71,7 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I } protected abstract boolean isTerrain(BlockState state); - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -108,28 +98,28 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { return true; } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); world.addFreshEntity(item); } - + @Override public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { return false; } - + @Override public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { return false; diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java index 8b6499a2..9855d9d2 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java @@ -1,7 +1,5 @@ package ru.bclib.blocks; -import java.util.Random; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -14,16 +12,13 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.Material; +import java.util.Random; + public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public UnderwaterPlantWithAgeBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .randomTicks() - .noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).randomTicks().noCollission()); } @Override diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index 0773a45b..92941bbf 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -1,9 +1,6 @@ package ru.bclib.blocks; -import java.util.List; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -29,25 +26,23 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; +import java.util.List; + @SuppressWarnings("deprecation") public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); public UpDownPlantBlock() { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); } - + protected abstract boolean isTerrain(BlockState state); - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -58,7 +53,7 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRend protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) { return canSupportCenter(world, pos.above(), Direction.UP); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { diff --git a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java index 5e910e70..4f483977 100644 --- a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java +++ b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java @@ -1,9 +1,6 @@ package ru.bclib.blocks; -import java.util.List; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -15,16 +12,11 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.storage.loot.LootContext; +import java.util.List; + public abstract class WallMushroomBlock extends BaseWallPlantBlock { public WallMushroomBlock(int light) { - super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.AXES) - .breakByHand(true) - .luminance(light) - .hardness(0.2F) - .sound(SoundType.GRASS) - .sound(SoundType.WOOD) - .noCollission()); + super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.AXES).breakByHand(true).luminance(light).hardness(0.2F).sound(SoundType.GRASS).sound(SoundType.WOOD).noCollission()); } @Override diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 5b6249d6..c281553e 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -23,10 +23,8 @@ public class BCLibClient implements ClientModInitializer { Registry.BLOCK.forEach(block -> { if (block instanceof IRenderTyped) { BCLRenderLayer layer = ((IRenderTyped) block).getRenderLayer(); - if (layer == BCLRenderLayer.CUTOUT) - BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); - else if (layer == BCLRenderLayer.TRANSLUCENT) - BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); + if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); + else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); } }); } diff --git a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java index 89954126..22121169 100644 --- a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java +++ b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java @@ -45,109 +45,108 @@ public class BlockSignEditScreen extends Screen { Arrays.fill(strings, ""); }); private SignRenderer.SignModel model; - + public BlockSignEditScreen(BaseSignBlockEntity sign) { super(new TranslatableComponent("sign.edit")); this.sign = sign; } - + protected void init() { //set up a default model model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); - + minecraft.keyboardHandler.setSendRepeatsToGui(true); - this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, - (buttonWidget) -> { - this.finishEditing(); - })); + this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, (buttonWidget) -> { + this.finishEditing(); + })); this.sign.setEditable(false); this.selectionManager = new TextFieldHelper(() -> { return this.text[this.currentRow]; }, (string) -> { this.text[this.currentRow] = string; this.sign.setMessage(this.currentRow, new TextComponent(string)); - }, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), - (string) -> { - return this.minecraft.font.width(string) <= 90; - }); + }, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), (string) -> { + return this.minecraft.font.width(string) <= 90; + }); } - + public void removed() { minecraft.keyboardHandler.setSendRepeatsToGui(false); ClientPacketListener clientPlayNetworkHandler = this.minecraft.getConnection(); if (clientPlayNetworkHandler != null) { - clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], - this.text[2], this.text[3])); + clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], this.text[2], this.text[3])); } - + this.sign.setEditable(true); } - + public void tick() { ++this.ticksSinceOpened; if (!this.sign.getType().isValid(this.sign.getBlockState())) { this.finishEditing(); } } - + private void finishEditing() { this.sign.setChanged(); this.minecraft.setScreen((Screen) null); } - + public boolean charTyped(char chr, int keyCode) { this.selectionManager.charTyped(chr); return true; } - + public void onClose() { this.finishEditing(); } - + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (keyCode == 265) { this.currentRow = this.currentRow - 1 & 3; this.selectionManager.setCursorToEnd(); return true; - } else if (keyCode != 264 && keyCode != 257 && keyCode != 335) { + } + else if (keyCode != 264 && keyCode != 257 && keyCode != 335) { return selectionManager.keyPressed(keyCode) || super.keyPressed(keyCode, scanCode, modifiers); - } else { + } + else { this.currentRow = this.currentRow + 1 & 3; this.selectionManager.setCursorToEnd(); return true; } } - + public void render(PoseStack matrices, int mouseX, int mouseY, float delta) { Lighting.setupForFlatItems(); this.renderBackground(matrices); GuiComponent.drawCenteredString(matrices, this.font, this.title, this.width / 2, 40, 16777215); matrices.pushPose(); matrices.translate((double) (this.width / 2), 0.0D, 50.0D); - + matrices.scale(93.75F, -93.75F, 93.75F); matrices.translate(0.0D, -1.3125D, 0.0D); BlockState blockState = this.sign.getBlockState(); boolean bl = blockState.getValue(BaseSignBlock.FLOOR); - + if (!bl) { matrices.translate(0.0D, -0.3125D, 0.0D); } - + boolean bl2 = this.ticksSinceOpened / 6 % 2 == 0; - + matrices.pushPose(); matrices.scale(0.6666667F, -0.6666667F, -0.6666667F); MultiBufferSource.BufferSource immediate = minecraft.renderBuffers().bufferSource(); VertexConsumer vertexConsumer = BaseSignBlockEntityRenderer.getConsumer(immediate, blockState.getBlock()); model.root.getChild("sign").render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); - + if (bl) { model.stick.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); } - + matrices.popPose(); - + matrices.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); matrices.scale(0.010416667F, -0.010416667F, 0.010416667F); int i = this.sign.getColor().getTextColor(); @@ -155,7 +154,7 @@ public class BlockSignEditScreen extends Screen { int k = this.selectionManager.getSelectionPos(); int l = this.currentRow * 10 - this.text.length * 5; Matrix4f matrix4f = matrices.last().pose(); - + int m; String string2; int s; @@ -166,29 +165,25 @@ public class BlockSignEditScreen extends Screen { if (this.font.isBidirectional()) { string2 = this.font.bidirectionalShaping(string2); } - + float n = (float) (-this.minecraft.font.width(string2) / 2); - this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, - immediate, false, 0, 15728880, false); + this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, immediate, false, 0, 15728880, false); if (m == this.currentRow && j >= 0 && bl2) { - s = this.minecraft.font - .width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); + s = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); t = s - this.minecraft.font.width(string2) / 2; if (j >= string2.length()) { - this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, - 0, 15728880, false); + this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, 0, 15728880, false); } } } } - + immediate.endBatch(); - + for (m = 0; m < this.text.length; ++m) { string2 = this.text[m]; if (string2 != null && m == this.currentRow && j >= 0) { - int r = this.minecraft.font - .width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); + int r = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); s = r - this.minecraft.font.width(string2) / 2; if (bl2 && j < string2.length()) { int var31 = l - 1; @@ -196,14 +191,12 @@ public class BlockSignEditScreen extends Screen { this.minecraft.font.getClass(); fill(matrices, s, var31, var10003, l + 9, -16777216 | i); } - + if (k != j) { t = Math.min(j, k); int u = Math.max(j, k); - int v = this.minecraft.font.width(string2.substring(0, t)) - - this.minecraft.font.width(string2) / 2; - int w = this.minecraft.font.width(string2.substring(0, u)) - - this.minecraft.font.width(string2) / 2; + int v = this.minecraft.font.width(string2.substring(0, t)) - this.minecraft.font.width(string2) / 2; + int w = this.minecraft.font.width(string2.substring(0, u)) - this.minecraft.font.width(string2) / 2; int x = Math.min(v, w); int y = Math.max(v, w); Tesselator tessellator = Tesselator.getInstance(); @@ -225,7 +218,7 @@ public class BlockSignEditScreen extends Screen { } } } - + matrices.popPose(); Lighting.setupFor3DItems(); super.render(matrices, mouseX, mouseY, delta); diff --git a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java index ec5bf62d..bdea5197 100644 --- a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java +++ b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java @@ -2,90 +2,67 @@ package ru.bclib.client.models; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; -import net.minecraft.client.model.geom.builders.*; +import net.minecraft.client.model.geom.builders.CubeDeformation; +import net.minecraft.client.model.geom.builders.CubeListBuilder; +import net.minecraft.client.model.geom.builders.LayerDefinition; +import net.minecraft.client.model.geom.builders.MeshDefinition; +import net.minecraft.client.model.geom.builders.PartDefinition; public class BaseChestBlockModel { - public final ModelPart partA; - public final ModelPart partC; - public final ModelPart partB; - public final ModelPart partRightA; - public final ModelPart partRightC; - public final ModelPart partRightB; - public final ModelPart partLeftA; - public final ModelPart partLeftC; - public final ModelPart partLeftB; - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - CubeDeformation deformation_partC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partC", CubeListBuilder.create() - .texOffs(0, 19) - .addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), - PartPose.ZERO); - - CubeDeformation deformation_partA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partA", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), - PartPose.offset(0.0f, 9.0f, 1.0f)); - - CubeDeformation deformation_partB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partB", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), - PartPose.offset(0.0f, 8.0f, 0.0f)); - - CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create() - .texOffs(0, 19) - .addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), - PartPose.ZERO); - - CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), - PartPose.offset(0.0f, 9.0f, 1.0f)); - - CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); - PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), - PartPose.offset(0.0f, 8.0f, 0.0f)); - - CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create() - .texOffs(0, 19) - .addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), - PartPose.ZERO); - - CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), - PartPose.offset(0.0f, 9.0f, 1.0f)); - - CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create() - .texOffs(0, 0) - .addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), - PartPose.offset(0.0f, 8.0f, 0.0f)); - - return LayerDefinition.create(modelData, 64, 64); - } - - public BaseChestBlockModel(ModelPart modelPart) { - super(); - - partC = modelPart.getChild("partC"); - partA = modelPart.getChild("partA"); - partB = modelPart.getChild("partB"); - partRightC = modelPart.getChild("partRightC"); - partRightA = modelPart.getChild("partRightA"); - partRightB = modelPart.getChild("partRightB"); - partLeftC = modelPart.getChild("partLeftC"); - partLeftA = modelPart.getChild("partLeftA"); - partLeftB = modelPart.getChild("partLeftB"); - } + public final ModelPart partA; + public final ModelPart partC; + public final ModelPart partB; + public final ModelPart partRightA; + public final ModelPart partRightC; + public final ModelPart partRightB; + public final ModelPart partLeftA; + public final ModelPart partLeftC; + public final ModelPart partLeftB; + + public static LayerDefinition getTexturedModelData() { + MeshDefinition modelData = new MeshDefinition(); + PartDefinition modelPartData = modelData.getRoot(); + CubeDeformation deformation_partC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), PartPose.ZERO); + + CubeDeformation deformation_partA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partB = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partB", CubeListBuilder.create().texOffs(0, 0).addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), PartPose.offset(0.0f, 8.0f, 0.0f)); + + CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), PartPose.ZERO); + + CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); + PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create().texOffs(0, 0).addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), PartPose.offset(0.0f, 8.0f, 0.0f)); + + CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create().texOffs(0, 19).addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), PartPose.ZERO); + + CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), PartPose.offset(0.0f, 9.0f, 1.0f)); + + CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f); + modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), PartPose.offset(0.0f, 8.0f, 0.0f)); + + return LayerDefinition.create(modelData, 64, 64); + } + + public BaseChestBlockModel(ModelPart modelPart) { + super(); + + partC = modelPart.getChild("partC"); + partA = modelPart.getChild("partA"); + partB = modelPart.getChild("partB"); + partRightC = modelPart.getChild("partRightC"); + partRightA = modelPart.getChild("partRightA"); + partRightB = modelPart.getChild("partRightB"); + partLeftC = modelPart.getChild("partLeftC"); + partLeftA = modelPart.getChild("partLeftA"); + partLeftB = modelPart.getChild("partLeftB"); + } } diff --git a/src/main/java/ru/bclib/client/models/BasePatterns.java b/src/main/java/ru/bclib/client/models/BasePatterns.java index 575e3b27..5d3442a8 100644 --- a/src/main/java/ru/bclib/client/models/BasePatterns.java +++ b/src/main/java/ru/bclib/client/models/BasePatterns.java @@ -57,5 +57,5 @@ public class BasePatterns { public final static ResourceLocation ITEM_GENERATED = BCLib.makeID("patterns/item/pattern_item_generated.json"); public final static ResourceLocation ITEM_HANDHELD = BCLib.makeID("patterns/item/pattern_item_handheld.json"); public final static ResourceLocation ITEM_SPAWN_EGG = BCLib.makeID("patterns/item/pattern_item_spawn_egg.json"); - + } diff --git a/src/main/java/ru/bclib/client/models/BlockModelProvider.java b/src/main/java/ru/bclib/client/models/BlockModelProvider.java index e139a923..9c4b2da9 100644 --- a/src/main/java/ru/bclib/client/models/BlockModelProvider.java +++ b/src/main/java/ru/bclib/client/models/BlockModelProvider.java @@ -1,34 +1,33 @@ package ru.bclib.client.models; -import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION; - -import java.util.Map; -import java.util.Optional; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; +import java.util.Map; +import java.util.Optional; + +import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION; + public interface BlockModelProvider extends ItemModelProvider { @Environment(EnvType.CLIENT) default @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { Optional pattern = PatternsHelper.createBlockSimple(resourceLocation); return ModelsHelper.fromPattern(pattern); } - + @Environment(EnvType.CLIENT) default UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createBlockSimple(modelId); } - + @Environment(EnvType.CLIENT) default void registerBlockModel(ResourceLocation stateId, ResourceLocation modelId, BlockState blockState, Map modelCache) { if (!modelCache.containsKey(modelId)) { @@ -36,7 +35,8 @@ public interface BlockModelProvider extends ItemModelProvider { if (model != null) { model.name = modelId.toString(); modelCache.put(modelId, model); - } else { + } + else { BCLib.LOGGER.warning("Error loading model: {}", modelId); modelCache.put(modelId, modelCache.get(MISSING_MODEL_LOCATION)); } diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index f7bdec4d..8e9b2382 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -1,12 +1,7 @@ package ru.bclib.client.models; -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - import com.google.common.collect.Lists; import com.mojang.math.Transformation; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -22,39 +17,43 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + @Environment(EnvType.CLIENT) public class ModelsHelper { public static BlockModel fromPattern(Optional pattern) { return pattern.map(BlockModel::fromString).orElse(null); } - + public static BlockModel createItemModel(ResourceLocation resourceLocation) { return fromPattern(PatternsHelper.createItemGenerated(resourceLocation)); } - + public static BlockModel createHandheldItem(ResourceLocation resourceLocation) { return fromPattern(PatternsHelper.createItemHandheld(resourceLocation)); } - + public static BlockModel createBlockItem(ResourceLocation resourceLocation) { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_BLOCK, resourceLocation); return fromPattern(pattern); } - + public static BlockModel createBlockEmpty(ResourceLocation resourceLocation) { Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_EMPTY, resourceLocation); return fromPattern(pattern); } - + public static MultiVariant createMultiVariant(ResourceLocation resourceLocation, Transformation transform, boolean uvLock) { Variant variant = new Variant(resourceLocation, transform, uvLock, 1); return new MultiVariant(Lists.newArrayList(variant)); } - + public static MultiVariant createBlockSimple(ResourceLocation resourceLocation) { return createMultiVariant(resourceLocation, Transformation.identity(), false); } - + public static MultiVariant createFacingModel(ResourceLocation resourceLocation, Direction facing, boolean uvLock, boolean inverted) { if (inverted) { facing = facing.getOpposite(); @@ -62,45 +61,45 @@ public class ModelsHelper { BlockModelRotation rotation = BlockModelRotation.by(0, (int) facing.toYRot()); return createMultiVariant(resourceLocation, rotation.getRotation(), uvLock); } - + public static MultiVariant createRotatedModel(ResourceLocation resourceLocation, Direction.Axis axis) { BlockModelRotation rotation = BlockModelRotation.X0_Y0; switch (axis) { - case X: rotation = BlockModelRotation.X90_Y90; break; - case Z: rotation = BlockModelRotation.X90_Y0; break; - default: break; + case X: + rotation = BlockModelRotation.X90_Y90; + break; + case Z: + rotation = BlockModelRotation.X90_Y0; + break; + default: + break; } return createMultiVariant(resourceLocation, rotation.getRotation(), false); } - + public static MultiVariant createRandomTopModel(ResourceLocation resourceLocation) { - return new MultiVariant(Lists.newArrayList( - new Variant(resourceLocation, Transformation.identity(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1) - )); + return new MultiVariant(Lists.newArrayList(new Variant(resourceLocation, Transformation.identity(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1))); } - + public static class MultiPartBuilder { - + private final static MultiPartBuilder BUILDER = new MultiPartBuilder(); - + public static MultiPartBuilder create(StateDefinition stateDefinition) { BUILDER.stateDefinition = stateDefinition; BUILDER.modelParts.clear(); return BUILDER; } - + private final List modelParts = Lists.newArrayList(); private StateDefinition stateDefinition; - + private MultiPartBuilder() {} - + public ModelPart part(ResourceLocation modelId) { return new ModelPart(modelId); } - + public MultiPart build() { if (modelParts.size() > 0) { List selectors = Lists.newArrayList(); @@ -113,32 +112,32 @@ public class ModelsHelper { } throw new IllegalStateException("At least one model part need to be created."); } - + public class ModelPart { private final ResourceLocation modelId; private Transformation transform = Transformation.identity(); private Condition condition = Condition.TRUE; private boolean uvLock = false; - + private ModelPart(ResourceLocation modelId) { this.modelId = modelId; } - + public ModelPart setCondition(Function condition) { this.condition = stateDefinition -> condition::apply; return this; } - + public ModelPart setTransformation(Transformation transform) { this.transform = transform; return this; } - + public ModelPart setUVLock(boolean value) { this.uvLock = value; return this; } - + public void add() { modelParts.add(this); } diff --git a/src/main/java/ru/bclib/client/models/PatternsHelper.java b/src/main/java/ru/bclib/client/models/PatternsHelper.java index 771b7d80..134e59c9 100644 --- a/src/main/java/ru/bclib/client/models/PatternsHelper.java +++ b/src/main/java/ru/bclib/client/models/PatternsHelper.java @@ -1,5 +1,10 @@ package ru.bclib.client.models; +import com.google.common.collect.Maps; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -8,58 +13,52 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; -import com.google.common.collect.Maps; - -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; - public class PatternsHelper { public static Optional createItemGenerated(ResourceLocation itemId) { return createJson(BasePatterns.ITEM_GENERATED, itemId); } - + public static Optional createItemHandheld(ResourceLocation itemId) { return createJson(BasePatterns.ITEM_HANDHELD, itemId); } - + public static Optional createBlockSimple(ResourceLocation blockId) { return createJson(BasePatterns.BLOCK_BASE, blockId); } - + public static Optional createBlockEmpty(ResourceLocation blockId) { return createJson(BasePatterns.BLOCK_EMPTY, blockId); } - + public static Optional createBlockPillar(ResourceLocation blockId) { return createJson(BasePatterns.BLOCK_PILLAR, blockId); } - + public static Optional createBlockBottomTop(ResourceLocation blockId) { return createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); } - + public static Optional createBlockColored(ResourceLocation blockId) { return createJson(BasePatterns.BLOCK_COLORED, blockId); } - + public static Optional createJson(ResourceLocation patternId, ResourceLocation blockId) { Map textures = Maps.newHashMap(); textures.put("%modid%", blockId.getNamespace()); textures.put("%texture%", blockId.getPath()); return createJson(patternId, textures); } - + public static Optional createJson(ResourceLocation patternId, Map textures) { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); try (InputStream input = resourceManager.getResource(patternId).getInputStream()) { - String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)) - .lines().collect(Collectors.joining()); + String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().collect(Collectors.joining()); for (Map.Entry texture : textures.entrySet()) { json = json.replace(texture.getKey(), texture.getValue()); } return Optional.of(json); - } catch (Exception ex) { + } + catch (Exception ex) { return Optional.empty(); } } diff --git a/src/main/java/ru/bclib/client/render/BCLRenderLayer.java b/src/main/java/ru/bclib/client/render/BCLRenderLayer.java index 3846d7d6..796edfa5 100644 --- a/src/main/java/ru/bclib/client/render/BCLRenderLayer.java +++ b/src/main/java/ru/bclib/client/render/BCLRenderLayer.java @@ -1,6 +1,5 @@ package ru.bclib.client.render; public enum BCLRenderLayer { - CUTOUT, - TRANSLUCENT; + CUTOUT, TRANSLUCENT; } diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 96d59f04..ab661e2c 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -18,7 +18,11 @@ import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.AbstractChestBlock; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.ChestBlock; +import net.minecraft.world.level.block.DoubleBlockCombiner; import net.minecraft.world.level.block.DoubleBlockCombiner.NeighborCombineResult; import net.minecraft.world.level.block.entity.ChestBlockEntity; import net.minecraft.world.level.block.state.BlockState; @@ -32,17 +36,18 @@ import java.util.HashMap; public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); private static final RenderType[] defaultLayer; - + private static final int ID_NORMAL = 0; private static final int ID_LEFT = 1; private static final int ID_RIGHT = 2; - + private final BaseChestBlockModel chestModel; + public BaseChestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { super(); chestModel = new BaseChestBlockModel(BaseChestBlockModel.getTexturedModelData().bakeRoot()); } - + public void render(BaseChestBlockEntity entity, float tickDelta, PoseStack matrices, MultiBufferSource vertexConsumers, int light, int overlay) { Level world = entity.getLevel(); boolean worldExists = world != null; @@ -54,40 +59,42 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer propertySource; - + matrices.pushPose(); matrices.translate(0.5D, 0.5D, 0.5D); matrices.mulPose(Vector3f.YP.rotationDegrees(-f)); matrices.translate(-0.5D, -0.5D, -0.5D); - + if (worldExists) { propertySource = abstractChestBlock.combine(blockState, world, entity.getBlockPos(), true); - } else { + } + else { propertySource = DoubleBlockCombiner.Combiner::acceptNone; } - + float pitch = ((Float2FloatFunction) propertySource.apply(ChestBlock.opennessCombiner(entity))).get(tickDelta); pitch = 1.0F - pitch; pitch = 1.0F - pitch * pitch * pitch; - @SuppressWarnings({ "unchecked", "rawtypes" }) - int blockLight = ((Int2IntFunction) propertySource.apply(new BrightnessCombiner())).applyAsInt(light); - + @SuppressWarnings({"unchecked", "rawtypes"}) int blockLight = ((Int2IntFunction) propertySource.apply(new BrightnessCombiner())).applyAsInt(light); + VertexConsumer vertexConsumer = getConsumer(vertexConsumers, block, chestType); - + if (isDouble) { if (chestType == ChestType.LEFT) { renderParts(matrices, vertexConsumer, chestModel.partLeftA, chestModel.partLeftB, chestModel.partLeftC, pitch, blockLight, overlay); - } else { + } + else { renderParts(matrices, vertexConsumer, chestModel.partRightA, chestModel.partRightB, chestModel.partRightC, pitch, blockLight, overlay); } - } else { + } + else { renderParts(matrices, vertexConsumer, chestModel.partA, chestModel.partB, chestModel.partC, pitch, blockLight, overlay); } - + matrices.popPose(); } } - + private void renderParts(PoseStack matrices, VertexConsumer vertices, ModelPart modelPart, ModelPart modelPart2, ModelPart modelPart3, float pitch, int light, int overlay) { modelPart.xRot = -(pitch * 1.5707964F); modelPart2.xRot = modelPart.xRot; @@ -95,7 +102,7 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer layers[ID_LEFT]; @@ -103,28 +110,20 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer layers[ID_NORMAL]; }; } - + public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) { RenderType[] layers = LAYERS.getOrDefault(block, defaultLayer); return provider.getBuffer(getChestTexture(chestType, layers)); } - + public static void registerRenderLayer(Block block) { ResourceLocation blockId = Registry.BLOCK.getKey(block); String modId = blockId.getNamespace(); String path = blockId.getPath(); - LAYERS.put(block, new RenderType[] { - RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + ".png")), - RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_left.png")), - RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_right.png")) - }); + LAYERS.put(block, new RenderType[] {RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + ".png")), RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_left.png")), RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + "_right.png"))}); } - + static { - defaultLayer = new RenderType[] { - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal.png")), - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_left.png")), - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_right.png")) - }; + defaultLayer = new RenderType[] {RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal.png")), RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_left.png")), RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_right.png"))}; } } diff --git a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java index 6d26f1d6..3fb6af43 100644 --- a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java @@ -39,42 +39,42 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { - List list = this.font.split(component, 90); - return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); - }); + + FormattedCharSequence[] formattedCharSequences = signBlockEntity.getRenderMessages(Minecraft.getInstance().isTextFilteringEnabled(), (component) -> { + List list = this.font.split(component, 90); + return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); + }); int drawColor; boolean drawOutlined; int drawLight; @@ -99,57 +98,58 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { return new ConfigKey(id.getPath(), id.getNamespace(), category); diff --git a/src/main/java/ru/bclib/config/Config.java b/src/main/java/ru/bclib/config/Config.java index 968c45d7..a1df5824 100644 --- a/src/main/java/ru/bclib/config/Config.java +++ b/src/main/java/ru/bclib/config/Config.java @@ -1,7 +1,6 @@ package ru.bclib.config; import org.jetbrains.annotations.Nullable; - import ru.bclib.BCLib; import ru.bclib.config.ConfigKeeper.BooleanEntry; import ru.bclib.config.ConfigKeeper.Entry; @@ -55,14 +54,15 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } catch (NullPointerException ex) { + } + catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; } protected int getInt(ConfigKey key, int defaultValue) { - Integer val = keeper.getValue(key, IntegerEntry.class); + Integer val = keeper.getValue(key, IntegerEntry.class); if (val == null) { IntegerEntry entry = keeper.registerEntry(key, new IntegerEntry(defaultValue)); return entry.getValue(); @@ -71,7 +71,7 @@ public abstract class Config { } protected int getInt(ConfigKey key) { - Integer val = keeper.getValue(key, IntegerEntry.class); + Integer val = keeper.getValue(key, IntegerEntry.class); return val != null ? val : 0; } @@ -81,7 +81,8 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } catch (NullPointerException ex) { + } + catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -93,7 +94,8 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } catch (NullPointerException | ClassCastException ex) { + } + catch (NullPointerException | ClassCastException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -119,7 +121,8 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } catch (NullPointerException ex) { + } + catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -145,7 +148,8 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } catch (NullPointerException ex) { + } + catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; diff --git a/src/main/java/ru/bclib/config/ConfigKeeper.java b/src/main/java/ru/bclib/config/ConfigKeeper.java index 0fc7f049..841e7d27 100644 --- a/src/main/java/ru/bclib/config/ConfigKeeper.java +++ b/src/main/java/ru/bclib/config/ConfigKeeper.java @@ -1,45 +1,43 @@ package ru.bclib.config; +import com.google.common.collect.Maps; +import com.google.common.reflect.TypeToken; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.minecraft.util.GsonHelper; +import org.jetbrains.annotations.Nullable; +import ru.bclib.util.JsonFactory; + import java.lang.reflect.Type; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; -import org.jetbrains.annotations.Nullable; - -import com.google.common.collect.Maps; -import com.google.common.reflect.TypeToken; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import net.minecraft.util.GsonHelper; -import ru.bclib.util.JsonFactory; - public final class ConfigKeeper { private final Map> configEntries = Maps.newHashMap(); private final JsonObject configObject; private final ConfigWriter writer; - + private boolean changed = false; - + public ConfigKeeper(String modID, String group) { this.writer = new ConfigWriter(modID, group); this.configObject = writer.load(); } - + public void save() { if (!changed) return; this.writer.save(); this.changed = false; } - + private > void initializeEntry(ConfigKey key, E entry) { if (configObject == null) { return; } String[] path = key.getPath(); JsonObject obj = configObject; - + if (!key.isRoot()) { for (String group : path) { JsonElement element = obj.get(group); @@ -50,13 +48,13 @@ public final class ConfigKeeper { obj = element.getAsJsonObject(); } } - + String paramKey = key.getEntry(); paramKey += " [default: " + entry.getDefault() + "]"; - + this.changed |= entry.setLocation(obj, paramKey); } - + private > void storeValue(E entry, T value) { if (configObject == null) { return; @@ -66,14 +64,14 @@ public final class ConfigKeeper { entry.toJson(value); this.changed = true; } - + private > T getValue(E entry) { if (!entry.hasLocation()) { return entry.getDefault(); } return entry.fromJson(); } - + @Nullable public > E getEntry(ConfigKey key, Class type) { Entry entry = this.configEntries.get(key); @@ -82,7 +80,7 @@ public final class ConfigKeeper { } return null; } - + @Nullable public > T getValue(ConfigKey key, Class type) { Entry entry = this.getEntry(key, type); @@ -91,7 +89,7 @@ public final class ConfigKeeper { } return entry.getValue(); } - + public > E registerEntry(ConfigKey key, E entry) { entry.setWriter(value -> this.storeValue(entry, value)); entry.setReader(() -> { @@ -101,119 +99,119 @@ public final class ConfigKeeper { this.configEntries.put(key, entry); return entry; } - + public static class BooleanEntry extends Entry { - + public BooleanEntry(Boolean defaultValue) { super(defaultValue); } - + @Override public Boolean fromJson() { return GsonHelper.getAsBoolean(location, key, defaultValue); } - + @Override public void toJson(Boolean value) { this.location.addProperty(key, value); } } - + public static class FloatEntry extends Entry { - + public FloatEntry(Float defaultValue) { super(defaultValue); } - + @Override public Float fromJson() { return GsonHelper.getAsFloat(location, key, defaultValue); } - + @Override public void toJson(Float value) { this.location.addProperty(key, value); } } - + public static class FloatRange extends RangeEntry { - + public FloatRange(Float defaultValue, float minVal, float maxVal) { super(defaultValue, minVal, maxVal); } - + @Override public Float fromJson() { return GsonHelper.getAsFloat(location, key, defaultValue); } - + @Override public void toJson(Float value) { this.location.addProperty(key, value); } } - + public static class IntegerEntry extends Entry { - + public IntegerEntry(Integer defaultValue) { super(defaultValue); } - + @Override public Integer getDefault() { return this.defaultValue; } - + @Override public Integer fromJson() { return GsonHelper.getAsInt(location, key, defaultValue); } - + @Override public void toJson(Integer value) { this.location.addProperty(key, value); } } - + public static class IntegerRange extends RangeEntry { - + public IntegerRange(Integer defaultValue, int minVal, int maxVal) { super(defaultValue, minVal, maxVal); } - + @Override public Integer fromJson() { return GsonHelper.getAsInt(location, key, defaultValue); } - + @Override public void toJson(Integer value) { this.location.addProperty(key, value); } } - + public static class StringEntry extends Entry { - + public StringEntry(String defaultValue) { super(defaultValue); } - + @Override public String fromJson() { return GsonHelper.getAsString(location, key, defaultValue); } - + @Override public void toJson(String value) { this.location.addProperty(key, value); } - + } - + public static class EnumEntry> extends Entry { - + private final Type type; - + public EnumEntry(T defaultValue) { super(defaultValue); TypeToken token = new TypeToken() { @@ -221,71 +219,71 @@ public final class ConfigKeeper { }; this.type = token.getType(); } - + @Override public T getDefault() { return this.defaultValue; } - + @Override public T fromJson() { return JsonFactory.GSON.fromJson(location.get(key), type); } - + @Override public void toJson(T value) { location.addProperty(key, JsonFactory.GSON.toJson(value, type)); } } - + public static abstract class RangeEntry> extends Entry { - + private final T min, max; - + public RangeEntry(T defaultValue, T minVal, T maxVal) { super(defaultValue); this.min = minVal; this.max = maxVal; } - + @Override public void setValue(T value) { super.setValue(value.compareTo(min) < 0 ? min : value.compareTo(max) > 0 ? max : value); } - + public T minValue() { return this.min; } - + public T maxValue() { return this.max; } } - + public static abstract class Entry { - + protected final T defaultValue; protected Consumer writer; protected Supplier reader; protected JsonObject location; protected String key; - + public abstract T fromJson(); - + public abstract void toJson(T value); - + public Entry(T defaultValue) { this.defaultValue = defaultValue; } - + protected void setWriter(Consumer writer) { this.writer = writer; } - + protected void setReader(Supplier reader) { this.reader = reader; } - + protected boolean setLocation(JsonObject location, String key) { this.location = location; this.key = key; @@ -295,24 +293,23 @@ public final class ConfigKeeper { } return false; } - + protected boolean hasLocation() { - return this.location != null && - this.key != null; + return this.location != null && this.key != null; } - + public T getValue() { return this.reader.get(); } - + public void setValue(T value) { this.writer.accept(value); } - + public T getDefault() { return this.defaultValue; } - + public void setDefault() { this.setValue(defaultValue); } diff --git a/src/main/java/ru/bclib/config/ConfigKey.java b/src/main/java/ru/bclib/config/ConfigKey.java index ed8b570d..88b2083b 100644 --- a/src/main/java/ru/bclib/config/ConfigKey.java +++ b/src/main/java/ru/bclib/config/ConfigKey.java @@ -17,11 +17,11 @@ public class ConfigKey { public ConfigKey(String entry, ResourceLocation path) { this(entry, path.getNamespace(), path.getPath()); } - + public String[] getPath() { return path; } - + public String getEntry() { return entry; } @@ -29,7 +29,7 @@ public class ConfigKey { public boolean isRoot() { return root; } - + @Override public int hashCode() { final int prime = 31; @@ -38,7 +38,7 @@ public class ConfigKey { result = prime * result + entry.hashCode(); return result; } - + @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/src/main/java/ru/bclib/config/ConfigWriter.java b/src/main/java/ru/bclib/config/ConfigWriter.java index ed4e125b..5884641d 100644 --- a/src/main/java/ru/bclib/config/ConfigWriter.java +++ b/src/main/java/ru/bclib/config/ConfigWriter.java @@ -1,20 +1,19 @@ package ru.bclib.config; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.fabricmc.loader.api.FabricLoader; +import ru.bclib.util.JsonFactory; + import java.io.File; import java.nio.file.Path; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import net.fabricmc.loader.api.FabricLoader; -import ru.bclib.util.JsonFactory; - public class ConfigWriter { private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); - + private final File configFile; private JsonObject configObject; - + public ConfigWriter(String modID, String configFile) { this.configFile = new File(new File(GAME_CONFIG_DIR.toFile(), modID), configFile + ".json"); File parent = this.configFile.getParentFile(); @@ -23,38 +22,38 @@ public class ConfigWriter { } this.load(); } - + public JsonObject getConfig() { return configObject; } - + public void save() { if (configObject == null) { return; } save(configFile, configObject); } - + public JsonObject load() { if (configObject == null) { configObject = load(configFile); } return configObject; } - + public void save(JsonElement config) { this.configObject = config.getAsJsonObject(); save(configFile, config); } - + public static JsonObject load(File configFile) { return JsonFactory.getJsonObject(configFile); } - + public static void save(File configFile, JsonElement config) { JsonFactory.storeJson(configFile, config); } - + public static String scrubFileName(String input) { input = input.replaceAll("[/\\ ]+", "_"); input = input.replaceAll("[,:&\"\\|\\<\\>\\?\\*]", "_"); diff --git a/src/main/java/ru/bclib/config/IdConfig.java b/src/main/java/ru/bclib/config/IdConfig.java index 379d8551..cc8f8330 100644 --- a/src/main/java/ru/bclib/config/IdConfig.java +++ b/src/main/java/ru/bclib/config/IdConfig.java @@ -1,14 +1,13 @@ package ru.bclib.config; -import java.util.function.BiFunction; - -import org.jetbrains.annotations.Nullable; - import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.IntegerRange; +import java.util.function.BiFunction; + public class IdConfig extends Config { protected final BiFunction keyFactory; @@ -16,48 +15,48 @@ public class IdConfig extends Config { super(modID, group); this.keyFactory = keyFactory; } - + @Override protected void registerEntries() {} - + protected ConfigKey createKey(ResourceLocation id, String key) { return this.keyFactory.apply(id, key); } - + @Nullable public > E getEntry(ResourceLocation id, String key, Class type) { return this.getEntry(createKey(id, key), type); } - + @Nullable public > T getDefault(ResourceLocation id, String key, Class type) { return this.getDefault(createKey(id, key), type); } - + public String getString(ResourceLocation id, String key, String defaultValue) { return this.getString(createKey(id, key), defaultValue); } - + public String getString(ResourceLocation id, String key) { return this.getString(createKey(id, key)); } - + public boolean setString(ResourceLocation id, String key, String value) { return this.setString(createKey(id, key), value); } - + public int getInt(ResourceLocation id, String key, int defaultValue) { return this.getInt(createKey(id, key), defaultValue); } - + public int getInt(ResourceLocation id, String key) { return this.getInt(createKey(id, key)); } - + public boolean setInt(ResourceLocation id, String key, int value) { return this.setInt(createKey(id, key), value); } - + public boolean setRangedInt(ResourceLocation id, String key, int value) { return this.setRanged(createKey(id, key), value, IntegerRange.class); } @@ -65,27 +64,27 @@ public class IdConfig extends Config { public boolean setRangedFloat(ResourceLocation id, String key, float value) { return this.setRanged(createKey(id, key), value, FloatRange.class); } - + public float getFloat(ResourceLocation id, String key, float defaultValue) { return this.getFloat(createKey(id, key), defaultValue); } - + public float getFloat(ResourceLocation id, String key) { return this.getFloat(createKey(id, key)); } - + public boolean setFloat(ResourceLocation id, String key, float value) { return this.setFloat(createKey(id, key), value); } - + public boolean getBoolean(ResourceLocation id, String key, boolean defaultValue) { return this.getBoolean(createKey(id, key), defaultValue); } - + public boolean getBoolean(ResourceLocation id, String key) { return this.getBoolean(createKey(id, key)); } - + public boolean setBoolean(ResourceLocation id, String key, boolean value) { return this.setBoolean(createKey(id, key), value); } diff --git a/src/main/java/ru/bclib/config/PathConfig.java b/src/main/java/ru/bclib/config/PathConfig.java index 3f7bc3e9..da3c1d49 100644 --- a/src/main/java/ru/bclib/config/PathConfig.java +++ b/src/main/java/ru/bclib/config/PathConfig.java @@ -1,17 +1,16 @@ package ru.bclib.config; import org.jetbrains.annotations.Nullable; - import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.IntegerRange; public class PathConfig extends Config { - + public PathConfig(String modID, String group) { super(modID, group); } - + @Override protected void registerEntries() {} @@ -27,36 +26,36 @@ public class PathConfig extends Config { public > E getEntry(String category, String key, Class type) { return this.getEntry(createKey(category, key), type); } - + @Nullable public > T getDefault(String category, String key, Class type) { return this.getDefault(createKey(category, key), type); } - + public String getString(String category, String key, String defaultValue) { return this.getString(createKey(category, key), defaultValue); } - + public String getString(String category, String key) { return this.getString(createKey(category, key)); } - + public boolean setString(String category, String key, String value) { return this.setString(createKey(category, key), value); } - + public int getInt(String category, String key, int defaultValue) { return this.getInt(createKey(category, key), defaultValue); } - + public int getInt(String category, String key) { return this.getInt(createKey(category, key)); } - + public boolean setInt(String category, String key, int value) { return this.setInt(createKey(category, key), value); } - + public boolean setRangedInt(String category, String key, int value) { return this.setRanged(createKey(category, key), value, IntegerRange.class); } @@ -64,27 +63,27 @@ public class PathConfig extends Config { public boolean setRangedFloat(String category, String key, float value) { return this.setRanged(createKey(category, key), value, FloatRange.class); } - + public float getFloat(String category, String key, float defaultValue) { return this.getFloat(createKey(category, key), defaultValue); } - + public float getFloat(String category, String key) { return this.getFloat(createKey(category, key)); } - + public boolean setFloat(String category, String key, float value) { return this.setFloat(createKey(category, key), value); } - + public boolean getBoolean(String category, String key, boolean defaultValue) { return this.getBoolean(createKey(category, key), defaultValue); } - + public boolean getBoolean(String category, String key) { return this.getBoolean(createKey(category, key)); } - + public boolean setBoolean(String category, String key, boolean value) { return this.setBoolean(createKey(category, key), value); } @@ -94,27 +93,27 @@ public class PathConfig extends Config { public String getStringRoot(String key, String defaultValue) { return this.getString(createKey(key), defaultValue); } - + public String getStringRoot(String key) { return this.getString(createKey(key)); } - + public boolean setStringRoot(String key, String value) { return this.setString(createKey(key), value); } - + public int getIntRoot(String key, int defaultValue) { return this.getInt(createKey(key), defaultValue); } - + public int getIntRoot(String key) { return this.getInt(createKey(key)); } - + public boolean setIntRoot(String key, int value) { return this.setInt(createKey(key), value); } - + public boolean setRangedIntRoot(String key, int value) { return this.setRanged(createKey(key), value, IntegerRange.class); } @@ -122,27 +121,27 @@ public class PathConfig extends Config { public boolean setRangedFloatRoot(String key, float value) { return this.setRanged(createKey(key), value, FloatRange.class); } - + public float getFloatRoot(String key, float defaultValue) { return this.getFloat(createKey(key), defaultValue); } - + public float getFloatRoot(String key) { return this.getFloat(createKey(key)); } - + public boolean setFloatRoot(String key, float value) { return this.setFloat(createKey(key), value); } - + public boolean getBooleanRoot(String key, boolean defaultValue) { return this.getBoolean(createKey(key), defaultValue); } - + public boolean getBooleanRoot(String key) { return this.getBoolean(createKey(key)); } - + public boolean setBooleanRoot(String key, boolean value) { return this.setBoolean(createKey(key), value); } diff --git a/src/main/java/ru/bclib/integration/ModIntegration.java b/src/main/java/ru/bclib/integration/ModIntegration.java index 69859df4..869edc61 100644 --- a/src/main/java/ru/bclib/integration/ModIntegration.java +++ b/src/main/java/ru/bclib/integration/ModIntegration.java @@ -1,10 +1,5 @@ package ru.bclib.integration; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - import net.fabricmc.fabric.api.tag.TagRegistry; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.Registry; @@ -25,6 +20,11 @@ import net.minecraft.world.level.levelgen.feature.Feature; import ru.bclib.BCLib; import ru.bclib.world.features.BCLFeature; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + public abstract class ModIntegration { private final String modID; @@ -45,7 +45,7 @@ public abstract class ModIntegration { public Item getItem(String name) { return Registry.ITEM.get(getID(name)); } - + public BlockState getDefaultState(String name) { return getBlock(name).defaultBlockState(); } @@ -178,7 +178,7 @@ public abstract class ModIntegration { public Object newInstance(Class cl, Object... args) { if (cl != null) { - for (Constructor constructor: cl.getConstructors()) { + for (Constructor constructor : cl.getConstructors()) { if (constructor.getParameterCount() == args.length) { try { return constructor.newInstance(args); diff --git a/src/main/java/ru/bclib/interfaces/IColorProvider.java b/src/main/java/ru/bclib/interfaces/IColorProvider.java index c9f2f8b6..b10ffe31 100644 --- a/src/main/java/ru/bclib/interfaces/IColorProvider.java +++ b/src/main/java/ru/bclib/interfaces/IColorProvider.java @@ -5,6 +5,6 @@ import net.minecraft.client.color.item.ItemColor; public interface IColorProvider { BlockColor getProvider(); - + ItemColor getItemProvider(); } diff --git a/src/main/java/ru/bclib/interfaces/ISpetialItem.java b/src/main/java/ru/bclib/interfaces/ISpetialItem.java index 33112bf7..e54e5d3c 100644 --- a/src/main/java/ru/bclib/interfaces/ISpetialItem.java +++ b/src/main/java/ru/bclib/interfaces/ISpetialItem.java @@ -2,5 +2,6 @@ package ru.bclib.interfaces; public interface ISpetialItem { boolean canPlaceOnWater(); + int getStackSize(); } diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index c1b36914..5abab41d 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -1,9 +1,5 @@ package ru.bclib.items; -import java.util.List; - -import org.jetbrains.annotations.Nullable; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -18,17 +14,20 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; import ru.bclib.client.models.ItemModelProvider; +import java.util.List; + public class BaseAnvilItem extends BlockItem implements ItemModelProvider { - + public final static String DESTRUCTION = "destruction"; - + public BaseAnvilItem(Block block, Properties properties) { super(block, properties); } - + @Override protected BlockState getPlacementState(BlockPlaceContext blockPlaceContext) { BlockState blockState = super.getPlacementState(blockPlaceContext); @@ -39,7 +38,7 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { } return blockState; } - + @Override @Environment(EnvType.CLIENT) public void appendHoverText(ItemStack itemStack, @Nullable Level level, List list, TooltipFlag tooltipFlag) { @@ -49,7 +48,7 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + l)); } } - + @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { diff --git a/src/main/java/ru/bclib/items/BaseArmorItem.java b/src/main/java/ru/bclib/items/BaseArmorItem.java index 805c2128..39e1cf00 100644 --- a/src/main/java/ru/bclib/items/BaseArmorItem.java +++ b/src/main/java/ru/bclib/items/BaseArmorItem.java @@ -1,10 +1,7 @@ package ru.bclib.items; -import java.util.UUID; - import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; - import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.ai.attributes.Attribute; import net.minecraft.world.entity.ai.attributes.AttributeModifier; @@ -13,17 +10,14 @@ import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; import ru.bclib.client.models.ItemModelProvider; +import java.util.UUID; + public class BaseArmorItem extends ArmorItem implements ItemModelProvider { - - protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] { - UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), - UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), - UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), - UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150") - }; - + + protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] {UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; + protected final Multimap defaultModifiers; - + public BaseArmorItem(ArmorMaterial material, EquipmentSlot equipmentSlot, Properties settings) { super(material, equipmentSlot, settings); this.defaultModifiers = HashMultimap.create(); @@ -34,12 +28,12 @@ public class BaseArmorItem extends ArmorItem implements ItemModelProvider { addAttributeModifier(Attributes.KNOCKBACK_RESISTANCE, new AttributeModifier(uuid, "Armor knockback resistance", knockbackResistance, AttributeModifier.Operation.ADDITION)); } } - + @Override public Multimap getDefaultAttributeModifiers(EquipmentSlot equipmentSlot) { return equipmentSlot == slot ? defaultModifiers : super.getDefaultAttributeModifiers(equipmentSlot); } - + protected void addAttributeModifier(Attribute attribute, AttributeModifier modifier) { if (defaultModifiers.containsKey(attribute)) { defaultModifiers.removeAll(attribute); diff --git a/src/main/java/ru/bclib/items/BaseDrinkItem.java b/src/main/java/ru/bclib/items/BaseDrinkItem.java index bb2216f2..e50818bd 100644 --- a/src/main/java/ru/bclib/items/BaseDrinkItem.java +++ b/src/main/java/ru/bclib/items/BaseDrinkItem.java @@ -17,22 +17,22 @@ public class BaseDrinkItem extends ModelProviderItem { public BaseDrinkItem(Properties settings) { super(settings); } - + @Override public int getUseDuration(ItemStack stack) { return 32; } - + @Override public UseAnim getUseAnimation(ItemStack stack) { return UseAnim.DRINK; } - + @Override public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { return ItemUtils.startUsingInstantly(world, user, hand); } - + @Override public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity user) { if (this.isEdible()) { @@ -45,15 +45,15 @@ public class BaseDrinkItem extends ModelProviderItem { CriteriaTriggers.CONSUME_ITEM.trigger(serverPlayerEntity, stack); serverPlayerEntity.awardStat(Stats.ITEM_USED.get(this)); } - + if (user instanceof Player && !((Player) user).getAbilities().instabuild) { stack.shrink(1); } - + if (!level.isClientSide) { user.removeAllEffects(); } - + return stack.isEmpty() ? new ItemStack(Items.GLASS_BOTTLE) : stack; } } diff --git a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java index 7badc6f9..6a221400 100644 --- a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java +++ b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java @@ -1,7 +1,5 @@ package ru.bclib.items; -import java.util.Optional; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -14,6 +12,8 @@ import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import java.util.Optional; + public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { super(type, primaryColor, secondaryColor, settings); diff --git a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java index 3836f161..92099882 100644 --- a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java @@ -20,7 +20,7 @@ public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemMo public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } - + @Override public int getMiningLevel(Tag tag, BlockState state, ItemStack stack, LivingEntity user) { if (tag.equals(FabricToolTags.AXES)) { diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index 10495c5a..ec084197 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -1,15 +1,6 @@ package ru.bclib.mixin.client; -import net.minecraft.world.level.material.FogType; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; - import net.minecraft.client.Camera; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.FogRenderer; @@ -21,7 +12,12 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.FogType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.BiomeAPI; import ru.bclib.util.BackgroundInfo; import ru.bclib.util.MHelper; diff --git a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java index a78291c5..99fe6e8f 100644 --- a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java @@ -1,26 +1,25 @@ package ru.bclib.mixin.client; -import java.util.Random; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EnchantmentTableBlock; import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.TagAPI; +import java.util.Random; + @Mixin(EnchantmentTableBlock.class) public abstract class EnchantingTableBlockMixin extends Block { public EnchantingTableBlockMixin(Properties settings) { super(settings); } - + @Inject(method = "animateTick", at = @At(value = "TAIL")) private void be_onRandomDisplayTick(BlockState state, Level world, BlockPos pos, Random random, CallbackInfo info) { for (int px = -2; px <= 2; ++px) { @@ -41,6 +40,6 @@ public abstract class EnchantingTableBlockMixin extends Block { } } } - + } } diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index bcad7100..cee9f054 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -1,16 +1,5 @@ package ru.bclib.mixin.client; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.multipart.MultiPart; @@ -24,10 +13,20 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.BCLib; import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ItemModelProvider; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @Mixin(ModelBakery.class) public abstract class ModelBakeryMixin { @Final @@ -36,10 +35,10 @@ public abstract class ModelBakeryMixin { @Final @Shadow private Map unbakedCache; - + @Shadow protected abstract void cacheAndQueueDependencies(ResourceLocation resourceLocation, UnbakedModel unbakedModel); - + @Inject(method = "loadModel", at = @At("HEAD"), cancellable = true) private void bclib_loadModels(ResourceLocation resourceLocation, CallbackInfo info) { if (resourceLocation instanceof ModelResourceLocation) { @@ -55,7 +54,8 @@ public abstract class ModelBakeryMixin { ItemModelProvider modelProvider = null; if (item instanceof ItemModelProvider) { modelProvider = (ItemModelProvider) item; - } else if (item instanceof BlockItem) { + } + else if (item instanceof BlockItem) { Block block = Registry.BLOCK.get(clearLoc); if (block instanceof ItemModelProvider) { modelProvider = (ItemModelProvider) block; @@ -67,21 +67,21 @@ public abstract class ModelBakeryMixin { model.name = itemLoc.toString(); cacheAndQueueDependencies(modelId, model); unbakedCache.put(itemLoc, model); - } else { + } + else { BCLib.LOGGER.warning("Error loading model: {}", itemLoc); } info.cancel(); } } - } else { + } + else { ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); if (!resourceManager.hasResource(stateLoc)) { Block block = Registry.BLOCK.get(clearLoc); if (block instanceof BlockModelProvider) { List possibleStates = block.getStateDefinition().getPossibleStates(); - Optional possibleState = possibleStates.stream() - .filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state))) - .findFirst(); + Optional possibleState = possibleStates.stream().filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state))).findFirst(); if (possibleState.isPresent()) { UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant(modelId, possibleState.get(), unbakedCache); if (modelVariant != null) { @@ -90,10 +90,12 @@ public abstract class ModelBakeryMixin { ResourceLocation stateId = BlockModelShaper.stateToModelLocation(clearLoc, state); cacheAndQueueDependencies(stateId, modelVariant); }); - } else { + } + else { cacheAndQueueDependencies(modelId, modelVariant); } - } else { + } + else { BCLib.LOGGER.warning("Error loading variant: {}", modelId); } info.cancel(); diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index 30ca8ef0..2d3a06d0 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -1,10 +1,5 @@ package ru.bclib.mixin.common; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Vec3i; @@ -16,6 +11,10 @@ import net.minecraft.world.level.biome.Biome.BiomeCategory; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; import ru.bclib.api.BonemealAPI; import ru.bclib.api.TagAPI; @@ -25,7 +24,7 @@ import ru.bclib.util.MHelper; @Mixin(BoneMealItem.class) public class BoneMealItemMixin { private static final MutableBlockPos bclib_BLOCK_POS = new MutableBlockPos(); - + @Inject(method = "useOn", at = @At("HEAD"), cancellable = true) private void bclib_onUse(UseOnContext context, CallbackInfoReturnable info) { Level world = context.getLevel(); @@ -134,7 +133,7 @@ public class BoneMealItemMixin { block = BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); return block == null ? null : block.defaultBlockState(); } - + private BlockState bclib_getNylium(Level world, BlockPos pos) { Vec3i[] offsets = MHelper.getOffsets(world.getRandom()); for (Vec3i dir : offsets) { diff --git a/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java b/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java index 81a2ba6c..9aad31dc 100644 --- a/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java @@ -1,10 +1,9 @@ package ru.bclib.mixin.common; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.ComposterBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(ComposterBlock.class) public interface ComposterBlockAccessor { diff --git a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java index d0af1dd8..c5595382 100644 --- a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java @@ -1,15 +1,5 @@ package ru.bclib.mixin.common; -import java.util.List; -import java.util.Random; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - import net.minecraft.core.Registry; import net.minecraft.world.Container; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -20,42 +10,51 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.EnchantmentInstance; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.TagAPI; +import java.util.List; +import java.util.Random; + @Mixin(EnchantmentMenu.class) public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { @Final @Shadow private Container enchantSlots; - + @Final @Shadow private ContainerLevelAccess access; - + @Final @Shadow private Random random; - + @Final @Shadow private DataSlot enchantmentSeed; - + @Shadow @Final public int[] costs; - + @Shadow @Final public int[] enchantClue; - + @Shadow @Final public int[] levelClue; - + protected EnchantmentMenuMixin(MenuType type, int syncId) { super(type, syncId); } - + @Inject(method = "slotsChanged", at = @At("HEAD"), cancellable = true) private void be_slotsChanged(Container inventory, CallbackInfo info) { if (inventory == this.enchantSlots) { @@ -63,7 +62,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { if (!itemStack.isEmpty() && itemStack.isEnchantable()) { this.access.execute((world, blockPos) -> { int i = 0; - + int j; for (j = -1; j <= 1; ++j) { for (int k = -1; k <= 1; ++k) { @@ -71,24 +70,24 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (k != 0 && j != 0) { if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } @@ -96,9 +95,9 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { } } } - + random.setSeed(enchantmentSeed.get()); - + for (j = 0; j < 3; ++j) { costs[j] = EnchantmentHelper.getEnchantmentCost(this.random, j, i, itemStack); enchantClue[j] = -1; @@ -107,7 +106,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { costs[j] = 0; } } - + for (j = 0; j < 3; ++j) { if (this.costs[j] > 0) { List list = this.getEnchantmentList(itemStack, j, this.costs[j]); @@ -118,7 +117,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { } } } - + broadcastChanges(); }); } @@ -132,7 +131,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { info.cancel(); } } - + @Shadow private List getEnchantmentList(ItemStack stack, int slot, int level) { return null; diff --git a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java index d54b39cc..ba18731a 100644 --- a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java @@ -1,16 +1,9 @@ package ru.bclib.mixin.common; -import net.minecraft.data.worldgen.Features; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -import java.util.Map; - @Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators") public interface FeatureDecoratorsAccessor { @Accessor("HEIGHTMAP_SQUARE") diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index 1cf79d29..fe2b5897 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -1,17 +1,5 @@ package ru.bclib.mixin.common; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; @@ -19,9 +7,20 @@ import net.minecraft.server.ServerResources; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.storage.WorldData; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; import ru.bclib.recipes.BCLRecipeManager; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + @Mixin(MinecraftServer.class) public class MinecraftServerMixin { @Shadow @@ -34,18 +33,18 @@ public class MinecraftServerMixin { @Final @Shadow protected WorldData worldData; - + @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) private void bcl_reloadResources(Collection collection, CallbackInfoReturnable> info) { bcl_injectRecipes(); } - + @Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true) private void bcl_loadLevel(CallbackInfo info) { bcl_injectRecipes(); BiomeAPI.initRegistry(MinecraftServer.class.cast(this)); } - + private void bcl_injectRecipes() { if (FabricLoader.getInstance().isModLoaded("kubejs")) { RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); diff --git a/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java b/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java index b0c8e3f4..ac5f7d11 100644 --- a/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java @@ -1,11 +1,10 @@ package ru.bclib.mixin.common; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - import net.minecraft.world.item.Item; import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.alchemy.PotionBrewing; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(PotionBrewing.class) public interface PotionBrewingAccessor { diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java index e3dece33..c17bfdfd 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java @@ -1,20 +1,19 @@ package ru.bclib.mixin.common; -import java.util.Map; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.Map; @Mixin(RecipeManager.class) public interface RecipeManagerAccessor { @Accessor("recipes") Map, Map>> bcl_getRecipes(); - + @Accessor("recipes") void bcl_setRecipes(Map, Map>> recipes); } \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java index 5c2092f6..07561ff4 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java @@ -1,20 +1,6 @@ package ru.bclib.mixin.common; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - import com.google.gson.JsonElement; - import net.minecraft.Util; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; @@ -24,23 +10,35 @@ import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.recipes.BCLRecipeManager; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + @Mixin(RecipeManager.class) public abstract class RecipeManagerMixin { @Shadow private Map, Map>> recipes; - + @Inject(method = "apply", at = @At(value = "RETURN")) private void be_apply(Map map, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo info) { recipes = BCLRecipeManager.getMap(recipes); } - + @Shadow private > Map> byType(RecipeType type) { return null; } - + /** * @author paulevs * @reason Remove conflicts with vanilla tags @@ -56,7 +54,7 @@ public abstract class RecipeManagerMixin { boolean b2 = v2.getId().getNamespace().equals("minecraft"); return b1 ^ b2 ? (b1 ? 1 : -1) : 0; }); - + return list.stream().flatMap((recipe) -> { return Util.toStream(type.tryMatch(recipe, world, inventory)); }).findFirst(); diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index ef881e4d..6a62af48 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -1,15 +1,5 @@ package ru.bclib.mixin.common; -import java.io.File; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.function.Supplier; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -22,10 +12,19 @@ import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.level.storage.WritableLevelData; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.BiomeAPI; import ru.bclib.api.DataFixerAPI; import ru.bclib.api.WorldDataAPI; +import java.io.File; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.function.Supplier; + @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level { private static String bcl_lastWorld = null; diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index ced2df40..0fa5be52 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -1,7 +1,5 @@ package ru.bclib.mixin.common; -import java.util.Map; - import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; import net.minecraft.tags.TagLoader; @@ -11,11 +9,13 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; import ru.bclib.util.TagHelper; +import java.util.Map; + @Mixin(TagLoader.class) public class TagLoaderMixin { @Shadow private String directory; - + @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) public Map be_modifyTags(Map tagsMap) { return TagHelper.apply(directory, tagsMap); diff --git a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java index d002334f..0c2ef0dd 100644 --- a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java +++ b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java @@ -3,7 +3,7 @@ package ru.bclib.noise; /* * OpenSimplex Noise in Java. * by Kurt Spencer - * + * * v1.1 (October 5, 2014) * - Added 2D and 4D implementations. * - Proper gradient sets for all dimensions, from a @@ -23,31 +23,31 @@ public class OpenSimplexNoise { private static final double SQUISH_CONSTANT_3D = 1.0 / 3; // (Math.sqrt(3+1)-1)/3; private static final double STRETCH_CONSTANT_4D = -0.138196601125011; // (1/Math.sqrt(4+1)-1)/4; private static final double SQUISH_CONSTANT_4D = 0.309016994374947; // (Math.sqrt(4+1)-1)/4; - + private static final double NORM_CONSTANT_2D = 47; private static final double NORM_CONSTANT_3D = 103; private static final double NORM_CONSTANT_4D = 30; - + private static final long DEFAULT_SEED = 0; - + private short[] perm; private short[] permGradIndex3D; - + public OpenSimplexNoise() { this(DEFAULT_SEED); } - + public OpenSimplexNoise(short[] perm) { this.perm = perm; permGradIndex3D = new short[256]; - + for (int i = 0; i < 256; i++) { // Since 3D has 24 gradients, simple bitmask won't work, so // precompute modulo array. permGradIndex3D[i] = (short) ((perm[i] % (gradients3D.length / 3)) * 3); } } - + // Initializes the class using a permutation array generated from a 64-bit // seed. // Generates a proper permutation (i.e. doesn't merely perform N successive @@ -57,60 +57,60 @@ public class OpenSimplexNoise { perm = new short[256]; permGradIndex3D = new short[256]; short[] source = new short[256]; - for (short i = 0; i < 256; i++) + for (short i = 0; i < 256; i++) { source[i] = i; + } seed = seed * 6364136223846793005l + 1442695040888963407l; seed = seed * 6364136223846793005l + 1442695040888963407l; seed = seed * 6364136223846793005l + 1442695040888963407l; for (int i = 255; i >= 0; i--) { seed = seed * 6364136223846793005l + 1442695040888963407l; int r = (int) ((seed + 31) % (i + 1)); - if (r < 0) - r += (i + 1); + if (r < 0) r += (i + 1); perm[i] = source[r]; permGradIndex3D[i] = (short) ((perm[i] % (gradients3D.length / 3)) * 3); source[r] = source[i]; } } - + // 2D OpenSimplex Noise. public double eval(double x, double y) { - + // Place input coordinates onto grid. double stretchOffset = (x + y) * STRETCH_CONSTANT_2D; double xs = x + stretchOffset; double ys = y + stretchOffset; - + // Floor to get grid coordinates of rhombus (stretched square) // super-cell origin. int xsb = fastFloor(xs); int ysb = fastFloor(ys); - + // Skew out to get actual coordinates of rhombus origin. We'll need // these later. double squishOffset = (xsb + ysb) * SQUISH_CONSTANT_2D; double xb = xsb + squishOffset; double yb = ysb + squishOffset; - + // Compute grid coordinates relative to rhombus origin. double xins = xs - xsb; double yins = ys - ysb; - + // Sum those together to get a value that determines which region we're // in. double inSum = xins + yins; - + // Positions relative to origin point. double dx0 = x - xb; double dy0 = y - yb; - + // We'll be defining these inside the next block and using them // afterwards. double dx_ext, dy_ext; int xsv_ext, ysv_ext; - + double value = 0; - + // Contribution (1,0) double dx1 = dx0 - 1 - SQUISH_CONSTANT_2D; double dy1 = dy0 - 0 - SQUISH_CONSTANT_2D; @@ -119,7 +119,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, dx1, dy1); } - + // Contribution (0,1) double dx2 = dx0 - 0 - SQUISH_CONSTANT_2D; double dy2 = dy0 - 1 - SQUISH_CONSTANT_2D; @@ -128,44 +128,49 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, dx2, dy2); } - + if (inSum <= 1) { // We're inside the triangle (2-Simplex) at (0,0) double zins = 1 - inSum; if (zins > xins || zins > yins) { // (0,0) is one of the closest two - // triangular vertices + // triangular vertices if (xins > yins) { xsv_ext = xsb + 1; ysv_ext = ysb - 1; dx_ext = dx0 - 1; dy_ext = dy0 + 1; - } else { + } + else { xsv_ext = xsb - 1; ysv_ext = ysb + 1; dx_ext = dx0 + 1; dy_ext = dy0 - 1; } - } else { // (1,0) and (0,1) are the closest two vertices. + } + else { // (1,0) and (0,1) are the closest two vertices. xsv_ext = xsb + 1; ysv_ext = ysb + 1; dx_ext = dx0 - 1 - 2 * SQUISH_CONSTANT_2D; dy_ext = dy0 - 1 - 2 * SQUISH_CONSTANT_2D; } - } else { // We're inside the triangle (2-Simplex) at (1,1) + } + else { // We're inside the triangle (2-Simplex) at (1,1) double zins = 2 - inSum; if (zins < xins || zins < yins) { // (0,0) is one of the closest two - // triangular vertices + // triangular vertices if (xins > yins) { xsv_ext = xsb + 2; ysv_ext = ysb + 0; dx_ext = dx0 - 2 - 2 * SQUISH_CONSTANT_2D; dy_ext = dy0 + 0 - 2 * SQUISH_CONSTANT_2D; - } else { + } + else { xsv_ext = xsb + 0; ysv_ext = ysb + 2; dx_ext = dx0 + 0 - 2 * SQUISH_CONSTANT_2D; dy_ext = dy0 - 2 - 2 * SQUISH_CONSTANT_2D; } - } else { // (1,0) and (0,1) are the closest two vertices. + } + else { // (1,0) and (0,1) are the closest two vertices. dx_ext = dx0; dy_ext = dy0; xsv_ext = xsb; @@ -176,71 +181,71 @@ public class OpenSimplexNoise { dx0 = dx0 - 1 - 2 * SQUISH_CONSTANT_2D; dy0 = dy0 - 1 - 2 * SQUISH_CONSTANT_2D; } - + // Contribution (0,0) or (1,1) double attn0 = 2 - dx0 * dx0 - dy0 * dy0; if (attn0 > 0) { attn0 *= attn0; value += attn0 * attn0 * extrapolate(xsb, ysb, dx0, dy0); } - + // Extra Vertex double attn_ext = 2 - dx_ext * dx_ext - dy_ext * dy_ext; if (attn_ext > 0) { attn_ext *= attn_ext; value += attn_ext * attn_ext * extrapolate(xsv_ext, ysv_ext, dx_ext, dy_ext); } - + return value / NORM_CONSTANT_2D; } - + // 3D OpenSimplex Noise. public double eval(double x, double y, double z) { - + // Place input coordinates on simplectic honeycomb. double stretchOffset = (x + y + z) * STRETCH_CONSTANT_3D; double xs = x + stretchOffset; double ys = y + stretchOffset; double zs = z + stretchOffset; - + // Floor to get simplectic honeycomb coordinates of rhombohedron // (stretched cube) super-cell origin. int xsb = fastFloor(xs); int ysb = fastFloor(ys); int zsb = fastFloor(zs); - + // Skew out to get actual coordinates of rhombohedron origin. We'll need // these later. double squishOffset = (xsb + ysb + zsb) * SQUISH_CONSTANT_3D; double xb = xsb + squishOffset; double yb = ysb + squishOffset; double zb = zsb + squishOffset; - + // Compute simplectic honeycomb coordinates relative to rhombohedral // origin. double xins = xs - xsb; double yins = ys - ysb; double zins = zs - zsb; - + // Sum those together to get a value that determines which region we're // in. double inSum = xins + yins + zins; - + // Positions relative to origin point. double dx0 = x - xb; double dy0 = y - yb; double dz0 = z - zb; - + // We'll be defining these inside the next block and using them // afterwards. double dx_ext0, dy_ext0, dz_ext0; double dx_ext1, dy_ext1, dz_ext1; int xsv_ext0, ysv_ext0, zsv_ext0; int xsv_ext1, ysv_ext1, zsv_ext1; - + double value = 0; if (inSum <= 1) { // We're inside the tetrahedron (3-Simplex) at (0,0,0) - + // Determine which two of (0,0,1), (0,1,0), (1,0,0) are closest. byte aPoint = 0x01; double aScore = xins; @@ -249,106 +254,115 @@ public class OpenSimplexNoise { if (aScore >= bScore && zins > bScore) { bScore = zins; bPoint = 0x04; - } else if (aScore < bScore && zins > aScore) { + } + else if (aScore < bScore && zins > aScore) { aScore = zins; aPoint = 0x04; } - + // Now we determine the two lattice points not part of the // tetrahedron that may contribute. // This depends on the closest two tetrahedral vertices, including // (0,0,0) double wins = 1 - inSum; if (wins > aScore || wins > bScore) { // (0,0,0) is one of the - // closest two tetrahedral - // vertices. + // closest two tetrahedral + // vertices. byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // closest + // vertex is the + // closest out + // of a and b. + if ((c & 0x01) == 0) { xsv_ext0 = xsb - 1; xsv_ext1 = xsb; dx_ext0 = dx0 + 1; dx_ext1 = dx0; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx_ext1 = dx0 - 1; } - + if ((c & 0x02) == 0) { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0; if ((c & 0x01) == 0) { ysv_ext1 -= 1; dy_ext1 += 1; - } else { + } + else { ysv_ext0 -= 1; dy_ext0 += 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1; } - + if ((c & 0x04) == 0) { zsv_ext0 = zsb; zsv_ext1 = zsb - 1; dz_ext0 = dz0; dz_ext1 = dz0 + 1; - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - 1; } - } else { // (0,0,0) is not one of the closest two tetrahedral - // vertices. + } + else { // (0,0,0) is not one of the closest two tetrahedral + // vertices. byte c = (byte) (aPoint | bPoint); // Our two extra vertices are - // determined by the closest - // two. - + // determined by the closest + // two. + if ((c & 0x01) == 0) { xsv_ext0 = xsb; xsv_ext1 = xsb - 1; dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_3D; dx_ext1 = dx0 + 1 - SQUISH_CONSTANT_3D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; } - + if ((c & 0x02) == 0) { ysv_ext0 = ysb; ysv_ext1 = ysb - 1; dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 + 1 - SQUISH_CONSTANT_3D; - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; } - + if ((c & 0x04) == 0) { zsv_ext0 = zsb; zsv_ext1 = zsb - 1; dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 + 1 - SQUISH_CONSTANT_3D; - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_3D; } } - + // Contribution (0,0,0) double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0; if (attn0 > 0) { attn0 *= attn0; value += attn0 * attn0 * extrapolate(xsb + 0, ysb + 0, zsb + 0, dx0, dy0, dz0); } - + // Contribution (1,0,0) double dx1 = dx0 - 1 - SQUISH_CONSTANT_3D; double dy1 = dy0 - 0 - SQUISH_CONSTANT_3D; @@ -358,7 +372,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, dx1, dy1, dz1); } - + // Contribution (0,1,0) double dx2 = dx0 - 0 - SQUISH_CONSTANT_3D; double dy2 = dy0 - 1 - SQUISH_CONSTANT_3D; @@ -368,7 +382,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, dx2, dy2, dz2); } - + // Contribution (0,0,1) double dx3 = dx2; double dy3 = dy1; @@ -378,9 +392,10 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, dx3, dy3, dz3); } - } else if (inSum >= 2) { // We're inside the tetrahedron (3-Simplex) at - // (1,1,1) - + } + else if (inSum >= 2) { // We're inside the tetrahedron (3-Simplex) at + // (1,1,1) + // Determine which two tetrahedral vertices are the closest, out of // (1,1,0), (1,0,1), (0,1,1) but not (1,1,1). byte aPoint = 0x06; @@ -390,99 +405,108 @@ public class OpenSimplexNoise { if (aScore <= bScore && zins < bScore) { bScore = zins; bPoint = 0x03; - } else if (aScore > bScore && zins < aScore) { + } + else if (aScore > bScore && zins < aScore) { aScore = zins; aPoint = 0x03; } - + // Now we determine the two lattice points not part of the // tetrahedron that may contribute. // This depends on the closest two tetrahedral vertices, including // (1,1,1) double wins = 3 - inSum; if (wins < aScore || wins < bScore) { // (1,1,1) is one of the - // closest two tetrahedral - // vertices. + // closest two tetrahedral + // vertices. byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // closest + // vertex is the + // closest out + // of a and b. + if ((c & 0x01) != 0) { xsv_ext0 = xsb + 2; xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_3D; dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_3D; } - + if ((c & 0x02) != 0) { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; if ((c & 0x01) != 0) { ysv_ext1 += 1; dy_ext1 -= 1; - } else { + } + else { ysv_ext0 += 1; dy_ext0 -= 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_3D; } - + if ((c & 0x04) != 0) { zsv_ext0 = zsb + 1; zsv_ext1 = zsb + 2; dz_ext0 = dz0 - 1 - 3 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 - 3 * SQUISH_CONSTANT_3D; - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_3D; } - } else { // (1,1,1) is not one of the closest two tetrahedral - // vertices. + } + else { // (1,1,1) is not one of the closest two tetrahedral + // vertices. byte c = (byte) (aPoint & bPoint); // Our two extra vertices are - // determined by the closest - // two. - + // determined by the closest + // two. + if ((c & 0x01) != 0) { xsv_ext0 = xsb + 1; xsv_ext1 = xsb + 2; dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; dx_ext1 = dx0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx0 - SQUISH_CONSTANT_3D; dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; } - + if ((c & 0x02) != 0) { ysv_ext0 = ysb + 1; ysv_ext1 = ysb + 2; dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy0 - SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; } - + if ((c & 0x04) != 0) { zsv_ext0 = zsb + 1; zsv_ext1 = zsb + 2; dz_ext0 = dz0 - 1 - SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz0 - SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; } } - + // Contribution (1,1,0) double dx3 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; double dy3 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; @@ -492,7 +516,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, dx3, dy3, dz3); } - + // Contribution (1,0,1) double dx2 = dx3; double dy2 = dy0 - 0 - 2 * SQUISH_CONSTANT_3D; @@ -502,7 +526,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, dx2, dy2, dz2); } - + // Contribution (0,1,1) double dx1 = dx0 - 0 - 2 * SQUISH_CONSTANT_3D; double dy1 = dy3; @@ -512,7 +536,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, dx1, dy1, dz1); } - + // Contribution (1,1,1) dx0 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; dy0 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; @@ -522,39 +546,42 @@ public class OpenSimplexNoise { attn0 *= attn0; value += attn0 * attn0 * extrapolate(xsb + 1, ysb + 1, zsb + 1, dx0, dy0, dz0); } - } else { // We're inside the octahedron (Rectified 3-Simplex) in - // between. + } + else { // We're inside the octahedron (Rectified 3-Simplex) in + // between. double aScore; byte aPoint; boolean aIsFurtherSide; double bScore; byte bPoint; boolean bIsFurtherSide; - + // Decide between point (0,0,1) and (1,1,0) as closest double p1 = xins + yins; if (p1 > 1) { aScore = p1 - 1; aPoint = 0x03; aIsFurtherSide = true; - } else { + } + else { aScore = 1 - p1; aPoint = 0x04; aIsFurtherSide = false; } - + // Decide between point (0,1,0) and (1,0,1) as closest double p2 = xins + zins; if (p2 > 1) { bScore = p2 - 1; bPoint = 0x05; bIsFurtherSide = true; - } else { + } + else { bScore = 1 - p2; bPoint = 0x02; bIsFurtherSide = false; } - + // The closest out of the two (1,0,0) and (0,1,1) will replace the // furthest out of the two decided above, if closer. double p3 = yins + zins; @@ -564,29 +591,32 @@ public class OpenSimplexNoise { aScore = score; aPoint = 0x06; aIsFurtherSide = true; - } else if (aScore > bScore && bScore < score) { + } + else if (aScore > bScore && bScore < score) { bScore = score; bPoint = 0x06; bIsFurtherSide = true; } - } else { + } + else { double score = 1 - p3; if (aScore <= bScore && aScore < score) { aScore = score; aPoint = 0x01; aIsFurtherSide = false; - } else if (aScore > bScore && bScore < score) { + } + else if (aScore > bScore && bScore < score) { bScore = score; bPoint = 0x01; bIsFurtherSide = false; } } - + // Where each of the two closest points are determines how the extra // two vertices are calculated. if (aIsFurtherSide == bIsFurtherSide) { if (aIsFurtherSide) { // Both closest points on (1,1,1) side - + // One of the two extra points is (1,1,1) dx_ext0 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; dy_ext0 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; @@ -594,7 +624,7 @@ public class OpenSimplexNoise { xsv_ext0 = xsb + 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb + 1; - + // Other extra point is based on the shared axis. byte c = (byte) (aPoint & bPoint); if ((c & 0x01) != 0) { @@ -604,14 +634,16 @@ public class OpenSimplexNoise { xsv_ext1 = xsb + 2; ysv_ext1 = ysb; zsv_ext1 = zsb; - } else if ((c & 0x02) != 0) { + } + else if ((c & 0x02) != 0) { dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 - 2 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; xsv_ext1 = xsb; ysv_ext1 = ysb + 2; zsv_ext1 = zsb; - } else { + } + else { dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 - 2 * SQUISH_CONSTANT_3D; @@ -619,8 +651,9 @@ public class OpenSimplexNoise { ysv_ext1 = ysb; zsv_ext1 = zsb + 2; } - } else {// Both closest points on (0,0,0) side - + } + else {// Both closest points on (0,0,0) side + // One of the two extra points is (0,0,0) dx_ext0 = dx0; dy_ext0 = dy0; @@ -628,7 +661,7 @@ public class OpenSimplexNoise { xsv_ext0 = xsb; ysv_ext0 = ysb; zsv_ext0 = zsb; - + // Other extra point is based on the omitted axis. byte c = (byte) (aPoint | bPoint); if ((c & 0x01) == 0) { @@ -638,14 +671,16 @@ public class OpenSimplexNoise { xsv_ext1 = xsb - 1; ysv_ext1 = ysb + 1; zsv_ext1 = zsb + 1; - } else if ((c & 0x02) == 0) { + } + else if ((c & 0x02) == 0) { dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext1 = dy0 + 1 - SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_3D; xsv_ext1 = xsb + 1; ysv_ext1 = ysb - 1; zsv_ext1 = zsb + 1; - } else { + } + else { dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; dz_ext1 = dz0 + 1 - SQUISH_CONSTANT_3D; @@ -654,16 +689,18 @@ public class OpenSimplexNoise { zsv_ext1 = zsb - 1; } } - } else { // One point on (0,0,0) side, one point on (1,1,1) side + } + else { // One point on (0,0,0) side, one point on (1,1,1) side byte c1, c2; if (aIsFurtherSide) { c1 = aPoint; c2 = bPoint; - } else { + } + else { c1 = bPoint; c2 = aPoint; } - + // One contribution is a permutation of (1,1,-1) if ((c1 & 0x01) == 0) { dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_3D; @@ -672,14 +709,16 @@ public class OpenSimplexNoise { xsv_ext0 = xsb - 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb + 1; - } else if ((c1 & 0x02) == 0) { + } + else if ((c1 & 0x02) == 0) { dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext0 = dy0 + 1 - SQUISH_CONSTANT_3D; dz_ext0 = dz0 - 1 - SQUISH_CONSTANT_3D; xsv_ext0 = xsb + 1; ysv_ext0 = ysb - 1; zsv_ext0 = zsb + 1; - } else { + } + else { dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; dz_ext0 = dz0 + 1 - SQUISH_CONSTANT_3D; @@ -687,7 +726,7 @@ public class OpenSimplexNoise { ysv_ext0 = ysb + 1; zsv_ext0 = zsb - 1; } - + // One contribution is a permutation of (0,0,2) dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; @@ -698,15 +737,17 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { dx_ext1 -= 2; xsv_ext1 += 2; - } else if ((c2 & 0x02) != 0) { + } + else if ((c2 & 0x02) != 0) { dy_ext1 -= 2; ysv_ext1 += 2; - } else { + } + else { dz_ext1 -= 2; zsv_ext1 += 2; } } - + // Contribution (1,0,0) double dx1 = dx0 - 1 - SQUISH_CONSTANT_3D; double dy1 = dy0 - 0 - SQUISH_CONSTANT_3D; @@ -716,7 +757,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, dx1, dy1, dz1); } - + // Contribution (0,1,0) double dx2 = dx0 - 0 - SQUISH_CONSTANT_3D; double dy2 = dy0 - 1 - SQUISH_CONSTANT_3D; @@ -726,7 +767,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, dx2, dy2, dz2); } - + // Contribution (0,0,1) double dx3 = dx2; double dy3 = dy1; @@ -736,7 +777,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, dx3, dy3, dz3); } - + // Contribution (1,1,0) double dx4 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; double dy4 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; @@ -746,7 +787,7 @@ public class OpenSimplexNoise { attn4 *= attn4; value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 0, dx4, dy4, dz4); } - + // Contribution (1,0,1) double dx5 = dx4; double dy5 = dy0 - 0 - 2 * SQUISH_CONSTANT_3D; @@ -756,7 +797,7 @@ public class OpenSimplexNoise { attn5 *= attn5; value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 0, zsb + 1, dx5, dy5, dz5); } - + // Contribution (0,1,1) double dx6 = dx0 - 0 - 2 * SQUISH_CONSTANT_3D; double dy6 = dy4; @@ -767,41 +808,41 @@ public class OpenSimplexNoise { value += attn6 * attn6 * extrapolate(xsb + 0, ysb + 1, zsb + 1, dx6, dy6, dz6); } } - + // First extra vertex double attn_ext0 = 2 - dx_ext0 * dx_ext0 - dy_ext0 * dy_ext0 - dz_ext0 * dz_ext0; if (attn_ext0 > 0) { attn_ext0 *= attn_ext0; value += attn_ext0 * attn_ext0 * extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, dx_ext0, dy_ext0, dz_ext0); } - + // Second extra vertex double attn_ext1 = 2 - dx_ext1 * dx_ext1 - dy_ext1 * dy_ext1 - dz_ext1 * dz_ext1; if (attn_ext1 > 0) { attn_ext1 *= attn_ext1; value += attn_ext1 * attn_ext1 * extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, dx_ext1, dy_ext1, dz_ext1); } - + return value / NORM_CONSTANT_3D; } - + // 4D OpenSimplex Noise. public double eval(double x, double y, double z, double w) { - + // Place input coordinates on simplectic honeycomb. double stretchOffset = (x + y + z + w) * STRETCH_CONSTANT_4D; double xs = x + stretchOffset; double ys = y + stretchOffset; double zs = z + stretchOffset; double ws = w + stretchOffset; - + // Floor to get simplectic honeycomb coordinates of rhombo-hypercube // super-cell origin. int xsb = fastFloor(xs); int ysb = fastFloor(ys); int zsb = fastFloor(zs); int wsb = fastFloor(ws); - + // Skew out to get actual coordinates of stretched rhombo-hypercube // origin. We'll need these later. double squishOffset = (xsb + ysb + zsb + wsb) * SQUISH_CONSTANT_4D; @@ -809,24 +850,24 @@ public class OpenSimplexNoise { double yb = ysb + squishOffset; double zb = zsb + squishOffset; double wb = wsb + squishOffset; - + // Compute simplectic honeycomb coordinates relative to rhombo-hypercube // origin. double xins = xs - xsb; double yins = ys - ysb; double zins = zs - zsb; double wins = ws - wsb; - + // Sum those together to get a value that determines which region we're // in. double inSum = xins + yins + zins + wins; - + // Positions relative to origin point. double dx0 = x - xb; double dy0 = y - yb; double dz0 = z - zb; double dw0 = w - wb; - + // We'll be defining these inside the next block and using them // afterwards. double dx_ext0, dy_ext0, dz_ext0, dw_ext0; @@ -835,11 +876,11 @@ public class OpenSimplexNoise { int xsv_ext0, ysv_ext0, zsv_ext0, wsv_ext0; int xsv_ext1, ysv_ext1, zsv_ext1, wsv_ext1; int xsv_ext2, ysv_ext2, zsv_ext2, wsv_ext2; - + double value = 0; if (inSum <= 1) { // We're inside the pentachoron (4-Simplex) at - // (0,0,0,0) - + // (0,0,0,0) + // Determine which two of (0,0,0,1), (0,0,1,0), (0,1,0,0), (1,0,0,0) // are closest. byte aPoint = 0x01; @@ -849,56 +890,61 @@ public class OpenSimplexNoise { if (aScore >= bScore && zins > bScore) { bScore = zins; bPoint = 0x04; - } else if (aScore < bScore && zins > aScore) { + } + else if (aScore < bScore && zins > aScore) { aScore = zins; aPoint = 0x04; } if (aScore >= bScore && wins > bScore) { bScore = wins; bPoint = 0x08; - } else if (aScore < bScore && wins > aScore) { + } + else if (aScore < bScore && wins > aScore) { aScore = wins; aPoint = 0x08; } - + // Now we determine the three lattice points not part of the // pentachoron that may contribute. // This depends on the closest two pentachoron vertices, including // (0,0,0,0) double uins = 1 - inSum; if (uins > aScore || uins > bScore) { // (0,0,0,0) is one of the - // closest two pentachoron - // vertices. + // closest two pentachoron + // vertices. byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. + // closest + // vertex is the + // closest out + // of a and b. if ((c & 0x01) == 0) { xsv_ext0 = xsb - 1; xsv_ext1 = xsv_ext2 = xsb; dx_ext0 = dx0 + 1; dx_ext1 = dx_ext2 = dx0; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb + 1; dx_ext0 = dx_ext1 = dx_ext2 = dx0 - 1; } - + if ((c & 0x02) == 0) { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; dy_ext0 = dy_ext1 = dy_ext2 = dy0; if ((c & 0x01) == 0x01) { ysv_ext0 -= 1; dy_ext0 += 1; - } else { + } + else { ysv_ext1 -= 1; dy_ext1 += 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 1; } - + if ((c & 0x04) == 0) { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; dz_ext0 = dz_ext1 = dz_ext2 = dz0; @@ -906,46 +952,52 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0x03) { zsv_ext0 -= 1; dz_ext0 += 1; - } else { + } + else { zsv_ext1 -= 1; dz_ext1 += 1; } - } else { + } + else { zsv_ext2 -= 1; dz_ext2 += 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 1; } - + if ((c & 0x08) == 0) { wsv_ext0 = wsv_ext1 = wsb; wsv_ext2 = wsb - 1; dw_ext0 = dw_ext1 = dw0; dw_ext2 = dw0 + 1; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb + 1; dw_ext0 = dw_ext1 = dw_ext2 = dw0 - 1; } - } else { // (0,0,0,0) is not one of the closest two pentachoron - // vertices. + } + else { // (0,0,0,0) is not one of the closest two pentachoron + // vertices. byte c = (byte) (aPoint | bPoint); // Our three extra vertices - // are determined by the - // closest two. - + // are determined by the + // closest two. + if ((c & 0x01) == 0) { xsv_ext0 = xsv_ext2 = xsb; xsv_ext1 = xsb - 1; dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 + 1 - SQUISH_CONSTANT_4D; dx_ext2 = dx0 - SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb + 1; dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; dx_ext1 = dx_ext2 = dx0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x02) == 0) { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_4D; @@ -953,16 +1005,18 @@ public class OpenSimplexNoise { if ((c & 0x01) == 0x01) { ysv_ext1 -= 1; dy_ext1 += 1; - } else { + } + else { ysv_ext2 -= 1; dy_ext2 += 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; dy_ext1 = dy_ext2 = dy0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x04) == 0) { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_4D; @@ -970,36 +1024,39 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0x03) { zsv_ext1 -= 1; dz_ext1 += 1; - } else { + } + else { zsv_ext2 -= 1; dz_ext2 += 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; dz_ext1 = dz_ext2 = dz0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x08) == 0) { wsv_ext0 = wsv_ext1 = wsb; wsv_ext2 = wsb - 1; dw_ext0 = dw0 - 2 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 - SQUISH_CONSTANT_4D; dw_ext2 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb + 1; dw_ext0 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; dw_ext1 = dw_ext2 = dw0 - 1 - SQUISH_CONSTANT_4D; } } - + // Contribution (0,0,0,0) double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0 - dw0 * dw0; if (attn0 > 0) { attn0 *= attn0; value += attn0 * attn0 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 0, dx0, dy0, dz0, dw0); } - + // Contribution (1,0,0,0) double dx1 = dx0 - 1 - SQUISH_CONSTANT_4D; double dy1 = dy0 - 0 - SQUISH_CONSTANT_4D; @@ -1010,7 +1067,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 0, dx1, dy1, dz1, dw1); } - + // Contribution (0,1,0,0) double dx2 = dx0 - 0 - SQUISH_CONSTANT_4D; double dy2 = dy0 - 1 - SQUISH_CONSTANT_4D; @@ -1021,7 +1078,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 0, dx2, dy2, dz2, dw2); } - + // Contribution (0,0,1,0) double dx3 = dx2; double dy3 = dy1; @@ -1032,7 +1089,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 0, dx3, dy3, dz3, dw3); } - + // Contribution (0,0,0,1) double dx4 = dx2; double dy4 = dy1; @@ -1043,11 +1100,12 @@ public class OpenSimplexNoise { attn4 *= attn4; value += attn4 * attn4 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 1, dx4, dy4, dz4, dw4); } - } else if (inSum >= 3) { // We're inside the pentachoron (4-Simplex) at - // (1,1,1,1) - // Determine which two of (1,1,1,0), - // (1,1,0,1), (1,0,1,1), (0,1,1,1) - // are closest. + } + else if (inSum >= 3) { // We're inside the pentachoron (4-Simplex) at + // (1,1,1,1) + // Determine which two of (1,1,1,0), + // (1,1,0,1), (1,0,1,1), (0,1,1,1) + // are closest. byte aPoint = 0x0E; double aScore = xins; byte bPoint = 0x0D; @@ -1055,57 +1113,62 @@ public class OpenSimplexNoise { if (aScore <= bScore && zins < bScore) { bScore = zins; bPoint = 0x0B; - } else if (aScore > bScore && zins < aScore) { + } + else if (aScore > bScore && zins < aScore) { aScore = zins; aPoint = 0x0B; } if (aScore <= bScore && wins < bScore) { bScore = wins; bPoint = 0x07; - } else if (aScore > bScore && wins < aScore) { + } + else if (aScore > bScore && wins < aScore) { aScore = wins; aPoint = 0x07; } - + // Now we determine the three lattice points not part of the // pentachoron that may contribute. // This depends on the closest two pentachoron vertices, including // (0,0,0,0) double uins = 4 - inSum; if (uins < aScore || uins < bScore) { // (1,1,1,1) is one of the - // closest two pentachoron - // vertices. + // closest two pentachoron + // vertices. byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // closest + // vertex is the + // closest out + // of a and b. + if ((c & 0x01) != 0) { xsv_ext0 = xsb + 2; xsv_ext1 = xsv_ext2 = xsb + 1; dx_ext0 = dx0 - 2 - 4 * SQUISH_CONSTANT_4D; dx_ext1 = dx_ext2 = dx0 - 1 - 4 * SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb; dx_ext0 = dx_ext1 = dx_ext2 = dx0 - 4 * SQUISH_CONSTANT_4D; } - + if ((c & 0x02) != 0) { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; if ((c & 0x01) != 0) { ysv_ext1 += 1; dy_ext1 -= 1; - } else { + } + else { ysv_ext0 += 1; dy_ext0 -= 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 4 * SQUISH_CONSTANT_4D; } - + if ((c & 0x04) != 0) { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 1 - 4 * SQUISH_CONSTANT_4D; @@ -1113,46 +1176,52 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0) { zsv_ext0 += 1; dz_ext0 -= 1; - } else { + } + else { zsv_ext1 += 1; dz_ext1 -= 1; } - } else { + } + else { zsv_ext2 += 1; dz_ext2 -= 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 4 * SQUISH_CONSTANT_4D; } - + if ((c & 0x08) != 0) { wsv_ext0 = wsv_ext1 = wsb + 1; wsv_ext2 = wsb + 2; dw_ext0 = dw_ext1 = dw0 - 1 - 4 * SQUISH_CONSTANT_4D; dw_ext2 = dw0 - 2 - 4 * SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb; dw_ext0 = dw_ext1 = dw_ext2 = dw0 - 4 * SQUISH_CONSTANT_4D; } - } else { // (1,1,1,1) is not one of the closest two pentachoron - // vertices. + } + else { // (1,1,1,1) is not one of the closest two pentachoron + // vertices. byte c = (byte) (aPoint & bPoint); // Our three extra vertices - // are determined by the - // closest two. - + // are determined by the + // closest two. + if ((c & 0x01) != 0) { xsv_ext0 = xsv_ext2 = xsb + 1; xsv_ext1 = xsb + 2; dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; dx_ext2 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb; dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_4D; dx_ext1 = dx_ext2 = dx0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x02) != 0) { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -1160,16 +1229,18 @@ public class OpenSimplexNoise { if ((c & 0x01) != 0) { ysv_ext2 += 1; dy_ext2 -= 1; - } else { + } + else { ysv_ext1 += 1; dy_ext1 -= 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_4D; dy_ext1 = dy_ext2 = dy0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x04) != 0) { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -1177,29 +1248,32 @@ public class OpenSimplexNoise { if ((c & 0x03) != 0) { zsv_ext2 += 1; dz_ext2 -= 1; - } else { + } + else { zsv_ext1 += 1; dz_ext1 -= 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_4D; dz_ext1 = dz_ext2 = dz0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x08) != 0) { wsv_ext0 = wsv_ext1 = wsb + 1; wsv_ext2 = wsb + 2; dw_ext0 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; dw_ext2 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb; dw_ext0 = dw0 - 2 * SQUISH_CONSTANT_4D; dw_ext1 = dw_ext2 = dw0 - 3 * SQUISH_CONSTANT_4D; } } - + // Contribution (1,1,1,0) double dx4 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; double dy4 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; @@ -1210,7 +1284,7 @@ public class OpenSimplexNoise { attn4 *= attn4; value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 0, dx4, dy4, dz4, dw4); } - + // Contribution (1,1,0,1) double dx3 = dx4; double dy3 = dy4; @@ -1221,7 +1295,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 1, dx3, dy3, dz3, dw3); } - + // Contribution (1,0,1,1) double dx2 = dx4; double dy2 = dy0 - 3 * SQUISH_CONSTANT_4D; @@ -1232,7 +1306,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 1, dx2, dy2, dz2, dw2); } - + // Contribution (0,1,1,1) double dx1 = dx0 - 3 * SQUISH_CONSTANT_4D; double dz1 = dz4; @@ -1243,7 +1317,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 1, dx1, dy1, dz1, dw1); } - + // Contribution (1,1,1,1) dx0 = dx0 - 1 - 4 * SQUISH_CONSTANT_4D; dy0 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; @@ -1254,33 +1328,36 @@ public class OpenSimplexNoise { attn0 *= attn0; value += attn0 * attn0 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 1, dx0, dy0, dz0, dw0); } - } else if (inSum <= 2) { // We're inside the first dispentachoron - // (Rectified 4-Simplex) + } + else if (inSum <= 2) { // We're inside the first dispentachoron + // (Rectified 4-Simplex) double aScore; byte aPoint; boolean aIsBiggerSide = true; double bScore; byte bPoint; boolean bIsBiggerSide = true; - + // Decide between (1,1,0,0) and (0,0,1,1) if (xins + yins > zins + wins) { aScore = xins + yins; aPoint = 0x03; - } else { + } + else { aScore = zins + wins; aPoint = 0x0C; } - + // Decide between (1,0,1,0) and (0,1,0,1) if (xins + zins > yins + wins) { bScore = xins + zins; bPoint = 0x05; - } else { + } + else { bScore = yins + wins; bPoint = 0x0A; } - + // Closer between (1,0,0,1) and (0,1,1,0) will replace the further // of a and b, if closer. if (xins + wins > yins + zins) { @@ -1288,69 +1365,76 @@ public class OpenSimplexNoise { if (aScore >= bScore && score > bScore) { bScore = score; bPoint = 0x09; - } else if (aScore < bScore && score > aScore) { + } + else if (aScore < bScore && score > aScore) { aScore = score; aPoint = 0x09; } - } else { + } + else { double score = yins + zins; if (aScore >= bScore && score > bScore) { bScore = score; bPoint = 0x06; - } else if (aScore < bScore && score > aScore) { + } + else if (aScore < bScore && score > aScore) { aScore = score; aPoint = 0x06; } } - + // Decide if (1,0,0,0) is closer. double p1 = 2 - inSum + xins; if (aScore >= bScore && p1 > bScore) { bScore = p1; bPoint = 0x01; bIsBiggerSide = false; - } else if (aScore < bScore && p1 > aScore) { + } + else if (aScore < bScore && p1 > aScore) { aScore = p1; aPoint = 0x01; aIsBiggerSide = false; } - + // Decide if (0,1,0,0) is closer. double p2 = 2 - inSum + yins; if (aScore >= bScore && p2 > bScore) { bScore = p2; bPoint = 0x02; bIsBiggerSide = false; - } else if (aScore < bScore && p2 > aScore) { + } + else if (aScore < bScore && p2 > aScore) { aScore = p2; aPoint = 0x02; aIsBiggerSide = false; } - + // Decide if (0,0,1,0) is closer. double p3 = 2 - inSum + zins; if (aScore >= bScore && p3 > bScore) { bScore = p3; bPoint = 0x04; bIsBiggerSide = false; - } else if (aScore < bScore && p3 > aScore) { + } + else if (aScore < bScore && p3 > aScore) { aScore = p3; aPoint = 0x04; aIsBiggerSide = false; } - + // Decide if (0,0,0,1) is closer. double p4 = 2 - inSum + wins; if (aScore >= bScore && p4 > bScore) { bScore = p4; bPoint = 0x08; bIsBiggerSide = false; - } else if (aScore < bScore && p4 > aScore) { + } + else if (aScore < bScore && p4 > aScore) { aScore = p4; aPoint = 0x08; aIsBiggerSide = false; } - + // Where each of the two closest points are determines how the extra // three vertices are calculated. if (aIsBiggerSide == bIsBiggerSide) { @@ -1362,45 +1446,49 @@ public class OpenSimplexNoise { xsv_ext1 = xsb - 1; dx_ext0 = dx0 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x02) == 0) { ysv_ext0 = ysb; ysv_ext1 = ysb - 1; dy_ext0 = dy0 - 3 * SQUISH_CONSTANT_4D; dy_ext1 = dy0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; dy_ext1 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x04) == 0) { zsv_ext0 = zsb; zsv_ext1 = zsb - 1; dz_ext0 = dz0 - 3 * SQUISH_CONSTANT_4D; dz_ext1 = dz0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; dz_ext1 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x08) == 0) { wsv_ext0 = wsb; wsv_ext1 = wsb - 1; dw_ext0 = dw0 - 3 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsb + 1; dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; } - + // One combination is a permutation of (0,0,0,2) based on c2 xsv_ext2 = xsb; ysv_ext2 = ysb; @@ -1413,19 +1501,23 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { xsv_ext2 += 2; dx_ext2 -= 2; - } else if ((c2 & 0x02) != 0) { + } + else if ((c2 & 0x02) != 0) { ysv_ext2 += 2; dy_ext2 -= 2; - } else if ((c2 & 0x04) != 0) { + } + else if ((c2 & 0x04) != 0) { zsv_ext2 += 2; dz_ext2 -= 2; - } else { + } + else { wsv_ext2 += 2; dw_ext2 -= 2; } - - } else { // Both closest points on the smaller side - // One of the two extra points is (0,0,0,0) + + } + else { // Both closest points on the smaller side + // One of the two extra points is (0,0,0,0) xsv_ext2 = xsb; ysv_ext2 = ysb; zsv_ext2 = zsb; @@ -1434,71 +1526,79 @@ public class OpenSimplexNoise { dy_ext2 = dy0; dz_ext2 = dz0; dw_ext2 = dw0; - + // Other two points are based on the omitted axes. byte c = (byte) (aPoint | bPoint); - + if ((c & 0x01) == 0) { xsv_ext0 = xsb - 1; xsv_ext1 = xsb; dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_4D; dx_ext1 = dx0 - SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x02) == 0) { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - SQUISH_CONSTANT_4D; if ((c & 0x01) == 0x01) { ysv_ext0 -= 1; dy_ext0 += 1; - } else { + } + else { ysv_ext1 -= 1; dy_ext1 += 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x04) == 0) { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - SQUISH_CONSTANT_4D; if ((c & 0x03) == 0x03) { zsv_ext0 -= 1; dz_ext0 += 1; - } else { + } + else { zsv_ext1 -= 1; dz_ext1 += 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c & 0x08) == 0) { wsv_ext0 = wsb; wsv_ext1 = wsb - 1; dw_ext0 = dw0 - SQUISH_CONSTANT_4D; dw_ext1 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsb + 1; dw_ext0 = dw_ext1 = dw0 - 1 - SQUISH_CONSTANT_4D; } - + } - } else { // One point on each "side" + } + else { // One point on each "side" byte c1, c2; if (aIsBiggerSide) { c1 = aPoint; c2 = bPoint; - } else { + } + else { c1 = bPoint; c2 = aPoint; } - + // Two contributions are the bigger-sided point with each 0 // replaced with -1. if ((c1 & 0x01) == 0) { @@ -1506,51 +1606,57 @@ public class OpenSimplexNoise { xsv_ext1 = xsb; dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_4D; dx_ext1 = dx0 - SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c1 & 0x02) == 0) { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - SQUISH_CONSTANT_4D; if ((c1 & 0x01) == 0x01) { ysv_ext0 -= 1; dy_ext0 += 1; - } else { + } + else { ysv_ext1 -= 1; dy_ext1 += 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c1 & 0x04) == 0) { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - SQUISH_CONSTANT_4D; if ((c1 & 0x03) == 0x03) { zsv_ext0 -= 1; dz_ext0 += 1; - } else { + } + else { zsv_ext1 -= 1; dz_ext1 += 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_4D; } - + if ((c1 & 0x08) == 0) { wsv_ext0 = wsb; wsv_ext1 = wsb - 1; dw_ext0 = dw0 - SQUISH_CONSTANT_4D; dw_ext1 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsb + 1; dw_ext0 = dw_ext1 = dw0 - 1 - SQUISH_CONSTANT_4D; } - + // One contribution is a permutation of (0,0,0,2) based on the // smaller-sided point xsv_ext2 = xsb; @@ -1564,18 +1670,21 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { xsv_ext2 += 2; dx_ext2 -= 2; - } else if ((c2 & 0x02) != 0) { + } + else if ((c2 & 0x02) != 0) { ysv_ext2 += 2; dy_ext2 -= 2; - } else if ((c2 & 0x04) != 0) { + } + else if ((c2 & 0x04) != 0) { zsv_ext2 += 2; dz_ext2 -= 2; - } else { + } + else { wsv_ext2 += 2; dw_ext2 -= 2; } } - + // Contribution (1,0,0,0) double dx1 = dx0 - 1 - SQUISH_CONSTANT_4D; double dy1 = dy0 - 0 - SQUISH_CONSTANT_4D; @@ -1586,7 +1695,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 0, dx1, dy1, dz1, dw1); } - + // Contribution (0,1,0,0) double dx2 = dx0 - 0 - SQUISH_CONSTANT_4D; double dy2 = dy0 - 1 - SQUISH_CONSTANT_4D; @@ -1597,7 +1706,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 0, dx2, dy2, dz2, dw2); } - + // Contribution (0,0,1,0) double dx3 = dx2; double dy3 = dy1; @@ -1608,7 +1717,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 0, dx3, dy3, dz3, dw3); } - + // Contribution (0,0,0,1) double dx4 = dx2; double dy4 = dy1; @@ -1619,7 +1728,7 @@ public class OpenSimplexNoise { attn4 *= attn4; value += attn4 * attn4 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 1, dx4, dy4, dz4, dw4); } - + // Contribution (1,1,0,0) double dx5 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy5 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -1630,7 +1739,7 @@ public class OpenSimplexNoise { attn5 *= attn5; value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 0, dx5, dy5, dz5, dw5); } - + // Contribution (1,0,1,0) double dx6 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy6 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -1641,7 +1750,7 @@ public class OpenSimplexNoise { attn6 *= attn6; value += attn6 * attn6 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 0, dx6, dy6, dz6, dw6); } - + // Contribution (1,0,0,1) double dx7 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy7 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -1652,7 +1761,7 @@ public class OpenSimplexNoise { attn7 *= attn7; value += attn7 * attn7 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 1, dx7, dy7, dz7, dw7); } - + // Contribution (0,1,1,0) double dx8 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy8 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -1663,7 +1772,7 @@ public class OpenSimplexNoise { attn8 *= attn8; value += attn8 * attn8 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 0, dx8, dy8, dz8, dw8); } - + // Contribution (0,1,0,1) double dx9 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy9 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -1674,7 +1783,7 @@ public class OpenSimplexNoise { attn9 *= attn9; value += attn9 * attn9 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 1, dx9, dy9, dz9, dw9); } - + // Contribution (0,0,1,1) double dx10 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy10 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -1685,32 +1794,35 @@ public class OpenSimplexNoise { attn10 *= attn10; value += attn10 * attn10 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 1, dx10, dy10, dz10, dw10); } - } else { // We're inside the second dispentachoron (Rectified 4-Simplex) + } + else { // We're inside the second dispentachoron (Rectified 4-Simplex) double aScore; byte aPoint; boolean aIsBiggerSide = true; double bScore; byte bPoint; boolean bIsBiggerSide = true; - + // Decide between (0,0,1,1) and (1,1,0,0) if (xins + yins < zins + wins) { aScore = xins + yins; aPoint = 0x0C; - } else { + } + else { aScore = zins + wins; aPoint = 0x03; } - + // Decide between (0,1,0,1) and (1,0,1,0) if (xins + zins < yins + wins) { bScore = xins + zins; bPoint = 0x0A; - } else { + } + else { bScore = yins + wins; bPoint = 0x05; } - + // Closer between (0,1,1,0) and (1,0,0,1) will replace the further // of a and b, if closer. if (xins + wins < yins + zins) { @@ -1718,76 +1830,83 @@ public class OpenSimplexNoise { if (aScore <= bScore && score < bScore) { bScore = score; bPoint = 0x06; - } else if (aScore > bScore && score < aScore) { + } + else if (aScore > bScore && score < aScore) { aScore = score; aPoint = 0x06; } - } else { + } + else { double score = yins + zins; if (aScore <= bScore && score < bScore) { bScore = score; bPoint = 0x09; - } else if (aScore > bScore && score < aScore) { + } + else if (aScore > bScore && score < aScore) { aScore = score; aPoint = 0x09; } } - + // Decide if (0,1,1,1) is closer. double p1 = 3 - inSum + xins; if (aScore <= bScore && p1 < bScore) { bScore = p1; bPoint = 0x0E; bIsBiggerSide = false; - } else if (aScore > bScore && p1 < aScore) { + } + else if (aScore > bScore && p1 < aScore) { aScore = p1; aPoint = 0x0E; aIsBiggerSide = false; } - + // Decide if (1,0,1,1) is closer. double p2 = 3 - inSum + yins; if (aScore <= bScore && p2 < bScore) { bScore = p2; bPoint = 0x0D; bIsBiggerSide = false; - } else if (aScore > bScore && p2 < aScore) { + } + else if (aScore > bScore && p2 < aScore) { aScore = p2; aPoint = 0x0D; aIsBiggerSide = false; } - + // Decide if (1,1,0,1) is closer. double p3 = 3 - inSum + zins; if (aScore <= bScore && p3 < bScore) { bScore = p3; bPoint = 0x0B; bIsBiggerSide = false; - } else if (aScore > bScore && p3 < aScore) { + } + else if (aScore > bScore && p3 < aScore) { aScore = p3; aPoint = 0x0B; aIsBiggerSide = false; } - + // Decide if (1,1,1,0) is closer. double p4 = 3 - inSum + wins; if (aScore <= bScore && p4 < bScore) { bScore = p4; bPoint = 0x07; bIsBiggerSide = false; - } else if (aScore > bScore && p4 < aScore) { + } + else if (aScore > bScore && p4 < aScore) { aScore = p4; aPoint = 0x07; aIsBiggerSide = false; } - + // Where each of the two closest points are determines how the extra // three vertices are calculated. if (aIsBiggerSide == bIsBiggerSide) { if (aIsBiggerSide) { // Both closest points on the bigger side byte c1 = (byte) (aPoint & bPoint); byte c2 = (byte) (aPoint | bPoint); - + // Two contributions are permutations of (0,0,0,1) and // (0,0,0,2) based on c1 xsv_ext0 = xsv_ext1 = xsb; @@ -1807,23 +1926,26 @@ public class OpenSimplexNoise { dx_ext0 -= 1; xsv_ext1 += 2; dx_ext1 -= 2; - } else if ((c1 & 0x02) != 0) { + } + else if ((c1 & 0x02) != 0) { ysv_ext0 += 1; dy_ext0 -= 1; ysv_ext1 += 2; dy_ext1 -= 2; - } else if ((c1 & 0x04) != 0) { + } + else if ((c1 & 0x04) != 0) { zsv_ext0 += 1; dz_ext0 -= 1; zsv_ext1 += 2; dz_ext1 -= 2; - } else { + } + else { wsv_ext0 += 1; dw_ext0 -= 1; wsv_ext1 += 2; dw_ext1 -= 2; } - + // One contribution is a permutation of (1,1,1,-1) based on // c2 xsv_ext2 = xsb + 1; @@ -1837,18 +1959,22 @@ public class OpenSimplexNoise { if ((c2 & 0x01) == 0) { xsv_ext2 -= 2; dx_ext2 += 2; - } else if ((c2 & 0x02) == 0) { + } + else if ((c2 & 0x02) == 0) { ysv_ext2 -= 2; dy_ext2 += 2; - } else if ((c2 & 0x04) == 0) { + } + else if ((c2 & 0x04) == 0) { zsv_ext2 -= 2; dz_ext2 += 2; - } else { + } + else { wsv_ext2 -= 2; dw_ext2 += 2; } - } else { // Both closest points on the smaller side - // One of the two extra points is (1,1,1,1) + } + else { // Both closest points on the smaller side + // One of the two extra points is (1,1,1,1) xsv_ext2 = xsb + 1; ysv_ext2 = ysb + 1; zsv_ext2 = zsb + 1; @@ -1857,70 +1983,78 @@ public class OpenSimplexNoise { dy_ext2 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; dz_ext2 = dz0 - 1 - 4 * SQUISH_CONSTANT_4D; dw_ext2 = dw0 - 1 - 4 * SQUISH_CONSTANT_4D; - + // Other two points are based on the shared axes. byte c = (byte) (aPoint & bPoint); - + if ((c & 0x01) != 0) { xsv_ext0 = xsb + 2; xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x02) != 0) { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; if ((c & 0x01) == 0) { ysv_ext0 += 1; dy_ext0 -= 1; - } else { + } + else { ysv_ext1 += 1; dy_ext1 -= 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x04) != 0) { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; if ((c & 0x03) == 0) { zsv_ext0 += 1; dz_ext0 -= 1; - } else { + } + else { zsv_ext1 += 1; dz_ext1 -= 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c & 0x08) != 0) { wsv_ext0 = wsb + 1; wsv_ext1 = wsb + 2; dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsb; dw_ext0 = dw_ext1 = dw0 - 3 * SQUISH_CONSTANT_4D; } } - } else { // One point on each "side" + } + else { // One point on each "side" byte c1, c2; if (aIsBiggerSide) { c1 = aPoint; c2 = bPoint; - } else { + } + else { c1 = bPoint; c2 = aPoint; } - + // Two contributions are the bigger-sided point with each 1 // replaced with 2. if ((c1 & 0x01) != 0) { @@ -1928,51 +2062,57 @@ public class OpenSimplexNoise { xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x02) != 0) { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; if ((c1 & 0x01) == 0) { ysv_ext0 += 1; dy_ext0 -= 1; - } else { + } + else { ysv_ext1 += 1; dy_ext1 -= 1; } - } else { + } + else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x04) != 0) { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; if ((c1 & 0x03) == 0) { zsv_ext0 += 1; dz_ext0 -= 1; - } else { + } + else { zsv_ext1 += 1; dz_ext1 -= 1; } - } else { + } + else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_4D; } - + if ((c1 & 0x08) != 0) { wsv_ext0 = wsb + 1; wsv_ext1 = wsb + 2; dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; dw_ext1 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { + } + else { wsv_ext0 = wsv_ext1 = wsb; dw_ext0 = dw_ext1 = dw0 - 3 * SQUISH_CONSTANT_4D; } - + // One contribution is a permutation of (1,1,1,-1) based on the // smaller-sided point xsv_ext2 = xsb + 1; @@ -1986,18 +2126,21 @@ public class OpenSimplexNoise { if ((c2 & 0x01) == 0) { xsv_ext2 -= 2; dx_ext2 += 2; - } else if ((c2 & 0x02) == 0) { + } + else if ((c2 & 0x02) == 0) { ysv_ext2 -= 2; dy_ext2 += 2; - } else if ((c2 & 0x04) == 0) { + } + else if ((c2 & 0x04) == 0) { zsv_ext2 -= 2; dz_ext2 += 2; - } else { + } + else { wsv_ext2 -= 2; dw_ext2 += 2; } } - + // Contribution (1,1,1,0) double dx4 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; double dy4 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; @@ -2008,7 +2151,7 @@ public class OpenSimplexNoise { attn4 *= attn4; value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 0, dx4, dy4, dz4, dw4); } - + // Contribution (1,1,0,1) double dx3 = dx4; double dy3 = dy4; @@ -2019,7 +2162,7 @@ public class OpenSimplexNoise { attn3 *= attn3; value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 1, dx3, dy3, dz3, dw3); } - + // Contribution (1,0,1,1) double dx2 = dx4; double dy2 = dy0 - 3 * SQUISH_CONSTANT_4D; @@ -2030,7 +2173,7 @@ public class OpenSimplexNoise { attn2 *= attn2; value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 1, dx2, dy2, dz2, dw2); } - + // Contribution (0,1,1,1) double dx1 = dx0 - 3 * SQUISH_CONSTANT_4D; double dz1 = dz4; @@ -2041,7 +2184,7 @@ public class OpenSimplexNoise { attn1 *= attn1; value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 1, dx1, dy1, dz1, dw1); } - + // Contribution (1,1,0,0) double dx5 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy5 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -2052,7 +2195,7 @@ public class OpenSimplexNoise { attn5 *= attn5; value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 0, dx5, dy5, dz5, dw5); } - + // Contribution (1,0,1,0) double dx6 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy6 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -2063,7 +2206,7 @@ public class OpenSimplexNoise { attn6 *= attn6; value += attn6 * attn6 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 0, dx6, dy6, dz6, dw6); } - + // Contribution (1,0,0,1) double dx7 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; double dy7 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -2074,7 +2217,7 @@ public class OpenSimplexNoise { attn7 *= attn7; value += attn7 * attn7 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 1, dx7, dy7, dz7, dw7); } - + // Contribution (0,1,1,0) double dx8 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy8 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -2085,7 +2228,7 @@ public class OpenSimplexNoise { attn8 *= attn8; value += attn8 * attn8 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 0, dx8, dy8, dz8, dw8); } - + // Contribution (0,1,0,1) double dx9 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy9 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; @@ -2096,7 +2239,7 @@ public class OpenSimplexNoise { attn9 *= attn9; value += attn9 * attn9 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 1, dx9, dy9, dz9, dw9); } - + // Contribution (0,0,1,1) double dx10 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; double dy10 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; @@ -2108,78 +2251,64 @@ public class OpenSimplexNoise { value += attn10 * attn10 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 1, dx10, dy10, dz10, dw10); } } - + // First extra vertex double attn_ext0 = 2 - dx_ext0 * dx_ext0 - dy_ext0 * dy_ext0 - dz_ext0 * dz_ext0 - dw_ext0 * dw_ext0; if (attn_ext0 > 0) { attn_ext0 *= attn_ext0; - value += attn_ext0 * attn_ext0 - * extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, wsv_ext0, dx_ext0, dy_ext0, dz_ext0, dw_ext0); + value += attn_ext0 * attn_ext0 * extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, wsv_ext0, dx_ext0, dy_ext0, dz_ext0, dw_ext0); } - + // Second extra vertex double attn_ext1 = 2 - dx_ext1 * dx_ext1 - dy_ext1 * dy_ext1 - dz_ext1 * dz_ext1 - dw_ext1 * dw_ext1; if (attn_ext1 > 0) { attn_ext1 *= attn_ext1; - value += attn_ext1 * attn_ext1 - * extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, wsv_ext1, dx_ext1, dy_ext1, dz_ext1, dw_ext1); + value += attn_ext1 * attn_ext1 * extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, wsv_ext1, dx_ext1, dy_ext1, dz_ext1, dw_ext1); } - + // Third extra vertex double attn_ext2 = 2 - dx_ext2 * dx_ext2 - dy_ext2 * dy_ext2 - dz_ext2 * dz_ext2 - dw_ext2 * dw_ext2; if (attn_ext2 > 0) { attn_ext2 *= attn_ext2; - value += attn_ext2 * attn_ext2 - * extrapolate(xsv_ext2, ysv_ext2, zsv_ext2, wsv_ext2, dx_ext2, dy_ext2, dz_ext2, dw_ext2); + value += attn_ext2 * attn_ext2 * extrapolate(xsv_ext2, ysv_ext2, zsv_ext2, wsv_ext2, dx_ext2, dy_ext2, dz_ext2, dw_ext2); } - + return value / NORM_CONSTANT_4D; } - + private double extrapolate(int xsb, int ysb, double dx, double dy) { int index = perm[(perm[xsb & 0xFF] + ysb) & 0xFF] & 0x0E; return gradients2D[index] * dx + gradients2D[index + 1] * dy; } - + private double extrapolate(int xsb, int ysb, int zsb, double dx, double dy, double dz) { int index = permGradIndex3D[(perm[(perm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF]; return gradients3D[index] * dx + gradients3D[index + 1] * dy + gradients3D[index + 2] * dz; } - + private double extrapolate(int xsb, int ysb, int zsb, int wsb, double dx, double dy, double dz, double dw) { int index = perm[(perm[(perm[(perm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF] + wsb) & 0xFF] & 0xFC; - return gradients4D[index] * dx + gradients4D[index + 1] * dy + gradients4D[index + 2] * dz - + gradients4D[index + 3] * dw; + return gradients4D[index] * dx + gradients4D[index + 1] * dy + gradients4D[index + 2] * dz + gradients4D[index + 3] * dw; } - + private static int fastFloor(double x) { int xi = (int) x; return x < xi ? xi - 1 : xi; } - + // Gradients for 2D. They approximate the directions to the // vertices of an octagon from the center. - private static byte[] gradients2D = new byte[] { 5, 2, 2, 5, -5, 2, -2, 5, 5, -2, 2, -5, -5, -2, -2, -5, }; - + private static byte[] gradients2D = new byte[] {5, 2, 2, 5, -5, 2, -2, 5, 5, -2, 2, -5, -5, -2, -2, -5,}; + // Gradients for 3D. They approximate the directions to the // vertices of a rhombicuboctahedron from the center, skewed so // that the triangular and square facets can be inscribed inside // circles of the same radius. - private static byte[] gradients3D = new byte[] { -11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11, -11, - -4, 4, -4, -11, 4, -4, -4, 11, 11, -4, 4, 4, -11, 4, 4, -4, 11, -11, 4, -4, -4, 11, -4, -4, 4, -11, 11, 4, - -4, 4, 11, -4, 4, 4, -11, -11, -4, -4, -4, -11, -4, -4, -4, -11, 11, -4, -4, 4, -11, -4, 4, -4, -11, }; - + private static byte[] gradients3D = new byte[] {-11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11, -11, -4, 4, -4, -11, 4, -4, -4, 11, 11, -4, 4, 4, -11, 4, 4, -4, 11, -11, 4, -4, -4, 11, -4, -4, 4, -11, 11, 4, -4, 4, 11, -4, 4, 4, -11, -11, -4, -4, -4, -11, -4, -4, -4, -11, 11, -4, -4, 4, -11, -4, 4, -4, -11,}; + // Gradients for 4D. They approximate the directions to the // vertices of a disprismatotesseractihexadecachoron from the center, // skewed so that the tetrahedral and cubic facets can be inscribed inside // spheres of the same radius. - private static byte[] gradients4D = new byte[] { 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, -3, 1, 1, 1, -1, 3, - 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1, 3, -3, -1, 1, 1, -1, -3, 1, - 1, -1, -1, 3, 1, -1, -1, 1, 3, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, -3, 1, -1, 1, -1, 3, -1, - 1, -1, 1, -3, 1, -1, 1, -1, 3, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, -3, -1, -1, 1, -1, - -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, 3, 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, -3, 1, 1, -1, - -1, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, -3, -1, 1, - -1, -1, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, -3, - 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, -1, 1, -1, - -1, -3, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3, }; + private static byte[] gradients4D = new byte[] {3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1, 3, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, -3, -1, -1, 1, -1, -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, 3, 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, -1, 1, -1, -1, -3, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3,}; } \ No newline at end of file diff --git a/src/main/java/ru/bclib/noise/VoronoiNoise.java b/src/main/java/ru/bclib/noise/VoronoiNoise.java index 07bea100..3e1424ec 100644 --- a/src/main/java/ru/bclib/noise/VoronoiNoise.java +++ b/src/main/java/ru/bclib/noise/VoronoiNoise.java @@ -1,10 +1,10 @@ package ru.bclib.noise; -import java.util.Random; - import net.minecraft.core.BlockPos; import ru.bclib.util.MHelper; +import java.util.Random; + public class VoronoiNoise { private static final Random RANDOM = new Random(); final int seed; @@ -12,7 +12,7 @@ public class VoronoiNoise { public VoronoiNoise() { this(0); } - + public VoronoiNoise(int seed) { this.seed = seed; } @@ -22,7 +22,7 @@ public class VoronoiNoise { h = (h ^ (h >> 13)) * 1274126177; return h ^ (h >> 16); } - + public double sample(double x, double y, double z) { int ix = MHelper.floor(x); int iy = MHelper.floor(y); diff --git a/src/main/java/ru/bclib/recipes/BCLRecipeManager.java b/src/main/java/ru/bclib/recipes/BCLRecipeManager.java index 8e2f6e71..0ecacc23 100644 --- a/src/main/java/ru/bclib/recipes/BCLRecipeManager.java +++ b/src/main/java/ru/bclib/recipes/BCLRecipeManager.java @@ -1,10 +1,6 @@ package ru.bclib.recipes; -import java.util.Map; -import java.util.Map.Entry; - import com.google.common.collect.Maps; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; @@ -13,9 +9,12 @@ import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; +import java.util.Map; +import java.util.Map.Entry; + public class BCLRecipeManager { private static final Map, Map>> RECIPES = Maps.newHashMap(); - + public static void addRecipe(RecipeType type, Recipe recipe) { Map> list = RECIPES.get(type); if (list == null) { @@ -32,16 +31,16 @@ public class BCLRecipeManager { } return null; } - + public static Map, Map>> getMap(Map, Map>> recipes) { Map, Map>> result = Maps.newHashMap(); - + for (RecipeType type : recipes.keySet()) { Map> typeList = Maps.newHashMap(); typeList.putAll(recipes.get(type)); result.put(type, typeList); } - + for (RecipeType type : RECIPES.keySet()) { Map> list = RECIPES.get(type); if (list != null) { @@ -52,32 +51,32 @@ public class BCLRecipeManager { } for (Entry> entry : list.entrySet()) { ResourceLocation id = entry.getKey(); - if (!typeList.containsKey(id)) - typeList.put(id, entry.getValue()); + if (!typeList.containsKey(id)) typeList.put(id, entry.getValue()); } } } - + return result; } - + public static , T extends Recipe> S registerSerializer(String modID, String id, S serializer) { return Registry.register(Registry.RECIPE_SERIALIZER, modID + ":" + id, serializer); } - + public static > RecipeType registerType(String modID, String type) { ResourceLocation recipeTypeId = new ResourceLocation(modID, type); return Registry.register(Registry.RECIPE_TYPE, recipeTypeId, new RecipeType() { public String toString() { return type; } - }); + }); } public static boolean exists(ItemLike item) { if (item instanceof Block) { return Registry.BLOCK.getKey((Block) item) != Registry.BLOCK.getDefaultKey(); - } else { + } + else { return Registry.ITEM.getKey(item.asItem()) != Registry.ITEM.getDefaultKey(); } } diff --git a/src/main/java/ru/bclib/recipes/CraftingRecipes.java b/src/main/java/ru/bclib/recipes/CraftingRecipes.java index d28b5b97..ec9788e5 100644 --- a/src/main/java/ru/bclib/recipes/CraftingRecipes.java +++ b/src/main/java/ru/bclib/recipes/CraftingRecipes.java @@ -20,18 +20,8 @@ public class CraftingRecipes { GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART).setShape("I I", "III").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD).setShape("WIW", "WWW", " W ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('W', ItemTags.PLANKS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) - .setShape("I I", "ICI", " I ") - .addMaterial('I', TagAPI.IRON_INGOTS) - .addMaterial('C', TagAPI.ITEM_CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - - GridRecipe.make(BCLib.MOD_ID, "tag_shulker_box", Blocks.SHULKER_BOX) - .setShape("S", "C", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('C', TagAPI.ITEM_CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER).setShape("I I", "ICI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); + + GridRecipe.make(BCLib.MOD_ID, "tag_shulker_box", Blocks.SHULKER_BOX).setShape("S", "C", "S").addMaterial('S', Items.SHULKER_SHELL).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); } } diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index bfb9abe7..c74f3117 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -1,10 +1,6 @@ package ru.bclib.recipes; -import java.util.Arrays; -import java.util.Map; - import com.google.common.collect.Maps; - import net.minecraft.core.NonNullList; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; @@ -19,6 +15,9 @@ import net.minecraft.world.level.ItemLike; import ru.bclib.BCLib; import ru.bclib.config.PathConfig; +import java.util.Arrays; +import java.util.Map; + public class GridRecipe { private static final GridRecipe INSTANCE = new GridRecipe(); @@ -55,7 +54,7 @@ public class GridRecipe { exist |= config.getBoolean("grid", id.getPath(), true); return this; } - + public GridRecipe setGroup(String group) { this.group = group; return this; @@ -67,7 +66,7 @@ public class GridRecipe { } public GridRecipe setList(String shape) { - this.shape = new String[] { shape }; + this.shape = new String[] {shape}; this.shaped = false; return this; } @@ -81,7 +80,7 @@ public class GridRecipe { } public GridRecipe addMaterial(char key, ItemLike... values) { - for (ItemLike item: values) { + for (ItemLike item : values) { exist &= BCLRecipeManager.exists(item); } return addMaterial(key, Ingredient.of(values)); @@ -100,11 +99,11 @@ public class GridRecipe { private NonNullList getMaterials(int width, int height) { NonNullList materials = NonNullList.withSize(width * height, Ingredient.EMPTY); int pos = 0; - for (String line: shape) { + for (String line : shape) { for (int i = 0; i < width; i++) { char c = line.charAt(i); Ingredient material = materialKeys.get(c); - materials.set(pos ++, material == null ? Ingredient.EMPTY : material); + materials.set(pos++, material == null ? Ingredient.EMPTY : material); } } return materials; @@ -119,7 +118,8 @@ public class GridRecipe { CraftingRecipe recipe = shaped ? new ShapedRecipe(id, group, width, height, materials, result) : new ShapelessRecipe(id, group, result, materials); BCLRecipeManager.addRecipe(type, recipe); - } else { + } + else { BCLib.LOGGER.debug("Recipe {} couldn't be added", id); } } diff --git a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java index bc6aa702..a74c6184 100644 --- a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java +++ b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java @@ -89,7 +89,7 @@ public class SmithingTableRecipe { BCLib.LOGGER.warning("Addition input for Smithing recipe can't be 'null', recipe {} will be ignored!", id); return; } - if(result == null) { + if (result == null) { BCLib.LOGGER.warning("Result for Smithing recipe can't be 'null', recipe {} will be ignored!", id); return; } diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index 7da1352b..f1170bb8 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -1,7 +1,5 @@ package ru.bclib.registry; -import java.util.function.Supplier; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; @@ -24,34 +22,26 @@ public class BaseBlockEntities { public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID("barrel"), BaseBarrelBlockEntity::new); public static final DynamicBlockEntityType SIGN = registerBlockEntityType(BCLib.makeID("sign"), BaseSignBlockEntity::new); public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID("furnace"), BaseFurnaceBlockEntity::new); - + public static DynamicBlockEntityType registerBlockEntityType(ResourceLocation typeId, BlockEntitySupplier supplier) { return Registry.register(Registry.BLOCK_ENTITY_TYPE, typeId, new DynamicBlockEntityType<>(supplier)); } public static void register() {} - + public static Block[] getChests() { - return BaseRegistry.getRegisteredBlocks().values().stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock) - .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getBarrels() { - return BaseRegistry.getRegisteredBlocks().values().stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock) - .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getSigns() { - return BaseRegistry.getRegisteredBlocks().values().stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock) - .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getFurnaces() { - return BaseRegistry.getRegisteredBlocks().values().stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock) - .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } } diff --git a/src/main/java/ru/bclib/registry/BaseRegistry.java b/src/main/java/ru/bclib/registry/BaseRegistry.java index cf9796b5..9369bc72 100644 --- a/src/main/java/ru/bclib/registry/BaseRegistry.java +++ b/src/main/java/ru/bclib/registry/BaseRegistry.java @@ -1,11 +1,7 @@ package ru.bclib.registry; -import java.util.List; -import java.util.Map; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; @@ -14,20 +10,23 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import ru.bclib.BCLib; -public abstract class BaseRegistry { +import java.util.List; +import java.util.Map; +public abstract class BaseRegistry { + private static final List> REGISTRIES = Lists.newArrayList(); private static final Map> MOD_BLOCKS = Maps.newHashMap(); private static final Map> MOD_ITEMS = Maps.newHashMap(); - + public static Map> getRegisteredBlocks() { return MOD_BLOCKS; } - + public static Map> getRegisteredItems() { return MOD_ITEMS; } - + public static List getModBlocks(String modId) { if (MOD_BLOCKS.containsKey(modId)) { return MOD_BLOCKS.get(modId); @@ -36,7 +35,7 @@ public abstract class BaseRegistry { MOD_BLOCKS.put(modId, modBlocks); return modBlocks; } - + public static List getModItems(String modId) { if (MOD_ITEMS.containsKey(modId)) { return MOD_ITEMS.get(modId); @@ -45,39 +44,39 @@ public abstract class BaseRegistry { MOD_ITEMS.put(modId, modBlocks); return modBlocks; } - + public static void register() { REGISTRIES.forEach(BaseRegistry::registerInternal); } - + protected final CreativeModeTab creativeTab; - + protected BaseRegistry(CreativeModeTab creativeTab) { this.creativeTab = creativeTab; REGISTRIES.add(this); } - + public T register(String name, T obj) { return register(createModId(name), obj); } - + public abstract T register(ResourceLocation objId, T obj); - + public ResourceLocation createModId(String name) { return BCLib.makeID(name); } - + public void registerItem(ResourceLocation id, Item item, List registry) { if (item != Items.AIR) { Registry.register(Registry.ITEM, id, item); registry.add(item); } } - + public FabricItemSettings makeItemSettings() { FabricItemSettings properties = new FabricItemSettings(); return (FabricItemSettings) properties.tab(creativeTab); } - + private void registerInternal() {} } diff --git a/src/main/java/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlocksRegistry.java index bd663f50..3da2f9c4 100644 --- a/src/main/java/ru/bclib/registry/BlocksRegistry.java +++ b/src/main/java/ru/bclib/registry/BlocksRegistry.java @@ -12,7 +12,7 @@ import net.minecraft.world.level.block.Block; import ru.bclib.interfaces.ISpetialItem; public abstract class BlocksRegistry extends BaseRegistry { - + protected BlocksRegistry(CreativeModeTab creativeTab) { super(creativeTab); } @@ -29,7 +29,8 @@ public abstract class BlocksRegistry extends BaseRegistry { Properties item = makeItemSettings().stacksTo(maxCount); if (placeOnWater) { registerBlockItem(id, new WaterLilyBlockItem(block, item)); - } else { + } + else { registerBlockItem(id, new BlockItem(block, item)); } if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance().get(block).getBurnChance() == 0) { @@ -41,7 +42,7 @@ public abstract class BlocksRegistry extends BaseRegistry { public Block registerBlockOnly(String name, Block block) { return Registry.register(Registry.BLOCK, createModId(name), block); } - + public Item registerBlockItem(ResourceLocation id, Item item) { registerItem(id, item, BaseRegistry.getModBlocks(id.getNamespace())); return item; diff --git a/src/main/java/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemsRegistry.java index 7dcc9744..fd9b728a 100644 --- a/src/main/java/ru/bclib/registry/ItemsRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemsRegistry.java @@ -30,44 +30,48 @@ import ru.bclib.items.tool.BasePickaxeItem; import ru.bclib.util.TagHelper; public abstract class ItemsRegistry extends BaseRegistry { - + protected ItemsRegistry(CreativeModeTab creativeTab) { super(creativeTab); } - + public Item registerDisc(String name, int power, SoundEvent sound) { return register(name, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); } - + public Item registerItem(String name) { return register(name, new ModelProviderItem(makeItemSettings())); } - + @Override public Item register(ResourceLocation itemId, Item item) { registerItem(itemId, item, BaseRegistry.getModItems(itemId.getNamespace())); return item; } - + public TieredItem registerTool(String name, TieredItem item) { ResourceLocation id = createModId(name); registerItem(id, item, BaseRegistry.getModItems(id.getNamespace())); - + if (item instanceof ShovelItem) { TagHelper.addTag((Tag.Named) FabricToolTags.SHOVELS, item); - } else if (item instanceof SwordItem) { + } + else if (item instanceof SwordItem) { TagHelper.addTag((Tag.Named) FabricToolTags.SWORDS, item); - } else if (item instanceof BasePickaxeItem) { + } + else if (item instanceof BasePickaxeItem) { TagHelper.addTag((Tag.Named) FabricToolTags.PICKAXES, item); - } else if (item instanceof BaseAxeItem) { + } + else if (item instanceof BaseAxeItem) { TagHelper.addTag((Tag.Named) FabricToolTags.AXES, item); - } else if (item instanceof BaseHoeItem) { + } + else if (item instanceof BaseHoeItem) { TagHelper.addTag((Tag.Named) FabricToolTags.HOES, item); } - + return item; } - + public Item registerEgg(String name, EntityType type, int background, int dots) { SpawnEggItem item = new BaseSpawnEggItem(type, background, dots, makeItemSettings()); DefaultDispenseItemBehavior behavior = new DefaultDispenseItemBehavior() { @@ -82,27 +86,27 @@ public abstract class ItemsRegistry extends BaseRegistry { DispenserBlock.registerBehavior(item, behavior); return register(name, item); } - + public Item registerFood(String name, int hunger, float saturation, MobEffectInstance... effects) { FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); - for (MobEffectInstance effect: effects) { + for (MobEffectInstance effect : effects) { builder.effect(effect, 1F); } return registerFood(name, builder.build()); } - + public Item registerFood(String name, FoodProperties foodComponent) { return register(name, new ModelProviderItem(makeItemSettings().food(foodComponent))); } - + public Item registerDrink(String name) { return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1))); } - + public Item registerDrink(String name, FoodProperties foodComponent) { return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1).food(foodComponent))); } - + public Item registerDrink(String name, int hunger, float saturation) { FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); return registerDrink(name, builder.build()); diff --git a/src/main/java/ru/bclib/sdf/PosInfo.java b/src/main/java/ru/bclib/sdf/PosInfo.java index b8a64c4d..d7e7e0ed 100644 --- a/src/main/java/ru/bclib/sdf/PosInfo.java +++ b/src/main/java/ru/bclib/sdf/PosInfo.java @@ -1,12 +1,12 @@ package ru.bclib.sdf; -import java.util.Map; - import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; +import java.util.Map; + public class PosInfo implements Comparable { private static final BlockState AIR = Blocks.AIR.defaultBlockState(); private final Map blocks; @@ -86,12 +86,12 @@ public class PosInfo implements Comparable { } return pos.equals(((PosInfo) obj).pos); } - + @Override public int compareTo(PosInfo info) { return this.pos.getY() - info.pos.getY(); } - + public BlockPos getPos() { return pos; } diff --git a/src/main/java/ru/bclib/sdf/SDF.java b/src/main/java/ru/bclib/sdf/SDF.java index 396850de..57d7ab31 100644 --- a/src/main/java/ru/bclib/sdf/SDF.java +++ b/src/main/java/ru/bclib/sdf/SDF.java @@ -1,16 +1,8 @@ package ru.bclib.sdf; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -20,12 +12,19 @@ import net.minecraft.world.phys.AABB; import ru.bclib.util.BlocksHelper; import ru.bclib.world.structures.StructureWorld; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + public abstract class SDF { private List> postProcesses = Lists.newArrayList(); private Function canReplace = (state) -> { return state.getMaterial().isReplaceable(); }; - + public abstract float getDistance(float x, float y, float z); public abstract BlockState getBlockState(BlockPos pos); @@ -52,8 +51,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center: ends) { - for (Direction dir: Direction.values()) { + for (BlockPos center : ends) { + for (Direction dir : Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); @@ -86,7 +85,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -135,7 +134,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -164,8 +163,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center: ends) { - for (Direction dir: Direction.values()) { + for (BlockPos center : ends) { + for (Direction dir : Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); BlockState state = world.getBlockState(wpos); @@ -198,7 +197,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -227,8 +226,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center: ends) { - for (Direction dir: Direction.values()) { + for (BlockPos center : ends) { + for (Direction dir : Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); @@ -284,8 +283,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center: ends) { - for (Direction dir: Direction.values()) { + for (BlockPos center : ends) { + for (Direction dir : Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); BlockState state = world.getBlockState(wpos); diff --git a/src/main/java/ru/bclib/sdf/operator/SDFBinary.java b/src/main/java/ru/bclib/sdf/operator/SDFBinary.java index 0e223e54..056aba3f 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFBinary.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFBinary.java @@ -27,7 +27,8 @@ public abstract class SDFBinary extends SDF { public BlockState getBlockState(BlockPos pos) { if (firstValue) { return sourceA.getBlockState(pos); - } else { + } + else { return sourceB.getBlockState(pos); } } diff --git a/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java b/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java index 1b096f5e..d0c01c3e 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java @@ -1,9 +1,9 @@ package ru.bclib.sdf.operator; -import java.util.function.Consumer; - import com.mojang.math.Vector3f; +import java.util.function.Consumer; + public class SDFCoordModify extends SDFUnary { private static final Vector3f POS = new Vector3f(); private Consumer function; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java b/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java index 5ca88dee..c25bbae2 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java @@ -1,9 +1,9 @@ package ru.bclib.sdf.operator; -import java.util.function.Function; - import com.mojang.math.Vector3f; +import java.util.function.Function; + public class SDFDisplacement extends SDFUnary { private static final Vector3f POS = new Vector3f(); private Function displace; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java b/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java index 5629607a..b5233d51 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java @@ -1,7 +1,6 @@ package ru.bclib.sdf.operator; import com.mojang.blaze3d.platform.NativeImage; - import net.minecraft.util.Mth; public class SDFHeightmap extends SDFDisplacement { diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java index 393d66d2..5770d25b 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java @@ -4,7 +4,7 @@ import net.minecraft.util.Mth; public class SDFSmoothIntersection extends SDFBinary { private float radius; - + public SDFSmoothIntersection setRadius(float radius) { this.radius = radius; return this; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java index 020b8590..c7ac6e73 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java @@ -4,7 +4,7 @@ import net.minecraft.util.Mth; public class SDFSmoothSubtraction extends SDFBinary { private float radius; - + public SDFSmoothSubtraction setRadius(float radius) { this.radius = radius; return this; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java index 493c1c9b..e7034e75 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java @@ -4,12 +4,12 @@ import net.minecraft.util.Mth; public class SDFSmoothUnion extends SDFBinary { private float radius; - + public SDFSmoothUnion setRadius(float radius) { this.radius = radius; return this; } - + @Override public float getDistance(float x, float y, float z) { float a = this.sourceA.getDistance(x, y, z); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java index 891253da..d66e0f46 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java @@ -22,7 +22,7 @@ public class SDFCappedCone extends SDFPrimitive { this.height = height; return this; } - + @Override public float getDistance(float x, float y, float z) { float qx = MHelper.length(x, z); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java b/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java index 1f06cbf5..586aaf73 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java @@ -3,6 +3,6 @@ package ru.bclib.sdf.primitive; public class SDFFlatland extends SDFPrimitive { @Override public float getDistance(float x, float y, float z) { - return y; + return y; } } diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java b/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java index 23a5b55c..a2e28a83 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java @@ -15,7 +15,7 @@ public class SDFHexPrism extends SDFPrimitive { this.height = height; return this; } - + @Override public float getDistance(float x, float y, float z) { float px = Math.abs(x); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFLine.java b/src/main/java/ru/bclib/sdf/primitive/SDFLine.java index 9fd316d7..0c166a91 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFLine.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFLine.java @@ -30,17 +30,17 @@ public class SDFLine extends SDFPrimitive { this.z2 = z; return this; } - + @Override public float getDistance(float x, float y, float z) { float pax = x - x1; float pay = y - y1; float paz = z - z1; - + float bax = x2 - x1; float bay = y2 - y1; float baz = z2 - z1; - + float dpb = MHelper.dot(pax, pay, paz, bax, bay, baz); float dbb = MHelper.dot(bax, bay, baz, bax, bay, baz); float h = Mth.clamp(dpb / dbb, 0F, 1F); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFPie.java b/src/main/java/ru/bclib/sdf/primitive/SDFPie.java index 0ad180f4..6bff34ea 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFPie.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFPie.java @@ -22,10 +22,10 @@ public class SDFPie extends SDFPrimitive { @Override public float getDistance(float x, float y, float z) { float px = Math.abs(x); - float l = MHelper.length(px, y, z) - radius; - float m = MHelper.dot(px, z, sin, cos); - m = Mth.clamp(m, 0, radius); + float l = MHelper.length(px, y, z) - radius; + float m = MHelper.dot(px, z, sin, cos); + m = Mth.clamp(m, 0, radius); m = MHelper.length(px - sin * m, z - cos * m); - return MHelper.max(l, m * (float) Math.signum(cos * px - sin * z)); + return MHelper.max(l, m * (float) Math.signum(cos * px - sin * z)); } } diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java b/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java index e40b61ab..4e3b527f 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java @@ -1,12 +1,12 @@ package ru.bclib.sdf.primitive; -import java.util.function.Function; - import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import ru.bclib.sdf.SDF; +import java.util.function.Function; + public abstract class SDFPrimitive extends SDF { protected Function placerFunction; diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java b/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java index c8ff092b..edeb8ea2 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java @@ -6,7 +6,7 @@ public class SDFSphere extends SDFPrimitive { private float radius; public SDFSphere setRadius(float radius) { - this.radius = radius; + this.radius = radius; return this; } diff --git a/src/main/java/ru/bclib/util/BlocksHelper.java b/src/main/java/ru/bclib/util/BlocksHelper.java index 21b974f9..1ba8952a 100644 --- a/src/main/java/ru/bclib/util/BlocksHelper.java +++ b/src/main/java/ru/bclib/util/BlocksHelper.java @@ -1,10 +1,6 @@ package ru.bclib.util; -import java.util.Map; -import java.util.Random; - import com.google.common.collect.Maps; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -18,48 +14,51 @@ import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; +import java.util.Map; +import java.util.Random; + public class BlocksHelper { private static final Map COLOR_BY_BLOCK = Maps.newHashMap(); - + public static final int FLAG_UPDATE_BLOCK = 1; public static final int FLAG_SEND_CLIENT_CHANGES = 2; public static final int FLAG_NO_RERENDER = 4; public static final int FORSE_RERENDER = 8; public static final int FLAG_IGNORE_OBSERVERS = 16; - + public static final int SET_SILENT = FLAG_UPDATE_BLOCK | FLAG_IGNORE_OBSERVERS | FLAG_SEND_CLIENT_CHANGES; public static final int SET_OBSERV = FLAG_UPDATE_BLOCK | FLAG_SEND_CLIENT_CHANGES; public static final Direction[] HORIZONTAL = makeHorizontal(); public static final Direction[] DIRECTIONS = Direction.values(); - + private static final MutableBlockPos POS = new MutableBlockPos(); protected static final BlockState AIR = Blocks.AIR.defaultBlockState(); protected static final BlockState WATER = Blocks.WATER.defaultBlockState(); - + public static void addBlockColor(Block block, int color) { COLOR_BY_BLOCK.put(block, color); } - + public static int getBlockColor(Block block) { return COLOR_BY_BLOCK.getOrDefault(block, 0xFF000000); } - + public static void setWithoutUpdate(LevelAccessor world, BlockPos pos, BlockState state) { world.setBlock(pos, state, SET_SILENT); } - + public static void setWithoutUpdate(LevelAccessor world, BlockPos pos, Block block) { world.setBlock(pos, block.defaultBlockState(), SET_SILENT); } - + public static void setWithUpdate(LevelAccessor world, BlockPos pos, BlockState state) { world.setBlock(pos, state, SET_OBSERV); } - + public static void setWithUpdate(LevelAccessor world, BlockPos pos, Block block) { world.setBlock(pos, block.defaultBlockState(), SET_OBSERV); } - + public static int upRay(LevelAccessor world, BlockPos pos, int maxDist) { int length = 0; for (int j = 1; j < maxDist && (world.isEmptyBlock(pos.above(j))); j++) { @@ -67,7 +66,7 @@ public class BlocksHelper { } return length; } - + public static int downRay(LevelAccessor world, BlockPos pos, int maxDist) { int length = 0; for (int j = 1; j < maxDist && (world.isEmptyBlock(pos.below(j))); j++) { @@ -75,7 +74,7 @@ public class BlocksHelper { } return length; } - + public static int downRayRep(LevelAccessor world, BlockPos pos, int maxDist) { POS.set(pos); for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { @@ -83,7 +82,7 @@ public class BlocksHelper { } return pos.getY() - POS.getY(); } - + public static int raycastSqr(LevelAccessor world, BlockPos pos, int dx, int dy, int dz, int maxDist) { POS.set(pos); for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { @@ -91,21 +90,23 @@ public class BlocksHelper { } return (int) pos.distSqr(POS); } - + /** * Rotates {@link BlockState} horizontally. Used in block classes with {@link Direction} {@link Property} in rotate function. - * @param state - {@link BlockState} to mirror; + * + * @param state - {@link BlockState} to mirror; * @param rotation - {@link Rotation}; - * @param facing - Block {@link Direction} {@link Property}. + * @param facing - Block {@link Direction} {@link Property}. * @return Rotated {@link BlockState}. */ public static BlockState rotateHorizontal(BlockState state, Rotation rotation, Property facing) { return state.setValue(facing, rotation.rotate(state.getValue(facing))); } - + /** * Mirrors {@link BlockState} horizontally. Used in block classes with {@link Direction} {@link Property} in mirror function. - * @param state - {@link BlockState} to mirror; + * + * @param state - {@link BlockState} to mirror; * @param mirror - {@link Mirror}; * @param facing - Block {@link Direction} {@link Property}. * @return Mirrored {@link BlockState}. @@ -113,11 +114,12 @@ public class BlocksHelper { public static BlockState mirrorHorizontal(BlockState state, Mirror mirror, Property facing) { return state.rotate(mirror.getRotation(state.getValue(facing))); } - + /** * Counts the amount of same block down. + * * @param world - {@link LevelAccessor} world; - * @param pos - {@link BlockPos} start position; + * @param pos - {@link BlockPos} start position; * @param block - {@link Block} to count. * @return Integer amount of blocks. */ @@ -128,36 +130,40 @@ public class BlocksHelper { } return count; } - + /** * Creates a new {@link Direction} array with clockwise order: * NORTH, EAST, SOUTH, WEST + * * @return Array of {@link Direction}. */ public static Direction[] makeHorizontal() { - return new Direction[] { Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST }; + return new Direction[] {Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}; } - + /** * Get any random horizontal {@link Direction}. + * * @param random - {@link Random}. * @return {@link Direction}. */ public static Direction randomHorizontal(Random random) { return HORIZONTAL[random.nextInt(4)]; } - + /** * Get any random {@link Direction} including vertical and horizontal. + * * @param random - {@link Random}. * @return {@link Direction}. */ public static Direction randomDirection(Random random) { return DIRECTIONS[random.nextInt(6)]; } - + /** * Check if block is {@link Fluid} or not. + * * @param state - {@link BlockState} to check. * @return {@code true} if block is fluid and {@code false} if not. */ @@ -167,9 +173,10 @@ public class BlocksHelper { /** * Check if block is "invulnerable" like Bedrock. + * * @param state - {@link BlockState} to check; * @param world - {@link BlockGetter} world where BlockState exist; - * @param pos - {@link BlockPos} where BlockState is. + * @param pos - {@link BlockPos} where BlockState is. * @return {@code true} if block is "invulnerable" and {@code false} if not. */ public static boolean isInvulnerable(BlockState state, BlockGetter world, BlockPos pos) { @@ -178,6 +185,7 @@ public class BlocksHelper { /** * Check if block is "invulnerable" like Bedrock. Unlike safe function will pass world and position parameters as {@code null}. + * * @param state - {@link BlockState} to check. * @return {@code true} if block is "invulnerable" and {@code false} if not. */ diff --git a/src/main/java/ru/bclib/util/ColorExtractor.java b/src/main/java/ru/bclib/util/ColorExtractor.java index 9614345d..e383a5d3 100644 --- a/src/main/java/ru/bclib/util/ColorExtractor.java +++ b/src/main/java/ru/bclib/util/ColorExtractor.java @@ -9,7 +9,7 @@ public class ColorExtractor { private List
centers = new ArrayList<>(); private List colors; private Integer result; - + public ColorExtractor(List colors) { this.colors = colors; Random rnd = new Random(); @@ -19,7 +19,7 @@ public class ColorExtractor { this.centers.add(new Center(color)); } } - + public int analize() { boolean moved = true; while (moved) { @@ -41,10 +41,10 @@ public class ColorExtractor { toClear.forEach(clear -> centers.remove(clear)); } this.centers.sort(Center.COMPARATOR); - + return this.getResult(); } - + public int getResult() { if (result == null) { double weights = 0; @@ -59,19 +59,20 @@ public class ColorExtractor { red += center.r * weight; green += center.g * weight; blue += center.b * weight; - } ; - + } + ; + int a = (int) Math.round(alpha / weights); int r = (int) Math.round(red / weights); int g = (int) Math.round(green / weights); int b = (int) Math.round(blue / weights); - + this.result = a << 24 | r << 16 | g << 8 | b; } - + return this.result; } - + private void remap() { this.centers.forEach(entry -> entry.colors.clear()); this.colors.forEach(color -> { @@ -89,7 +90,7 @@ public class ColorExtractor { this.centers.get(id).colors.add(color); }); } - + private static class Center { static final Comparator
COMPARATOR = new Comparator
() { @Override @@ -97,24 +98,24 @@ public class ColorExtractor { return Integer.compare(c1.getColor(), c2.getColor()); } }; - + List colors = new ArrayList<>(); double a, r, g, b; - + Center(int color) { this.a = (color >> 24) & 255; this.r = (color >> 16) & 255; this.g = (color >> 8) & 255; this.b = color & 255; } - + private void update(double a, double r, double g, double b) { this.a = a; this.r = r; this.g = g; this.b = b; } - + public int getColor() { int a = (int) Math.round(this.a); int r = (int) Math.round(this.r); @@ -122,7 +123,7 @@ public class ColorExtractor { int b = (int) Math.round(this.b); return a << 24 | r << 16 | g << 8 | b; } - + public boolean move() { double or = r; double og = g; @@ -139,9 +140,9 @@ public class ColorExtractor { r /= size; g /= size; b /= size; - + this.update(a, r, g, b); - + return Math.abs(r - or) > 0.1 || Math.abs(g - og) > 0.1 || Math.abs(b - ob) > 0.1; } } diff --git a/src/main/java/ru/bclib/util/ColorUtil.java b/src/main/java/ru/bclib/util/ColorUtil.java index 179dff9e..d091e83d 100644 --- a/src/main/java/ru/bclib/util/ColorUtil.java +++ b/src/main/java/ru/bclib/util/ColorUtil.java @@ -1,13 +1,7 @@ package ru.bclib.util; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import com.google.common.collect.Maps; import com.mojang.blaze3d.platform.NativeImage; - import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.client.indigo.renderer.helper.ColorHelper; @@ -21,39 +15,39 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import ru.bclib.BCLib; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + public class ColorUtil { private static final float[] FLOAT_BUFFER = new float[4]; private static final int ALPHA = 255 << 24; - + public static int color(int r, int g, int b) { return ALPHA | (r << 16) | (g << 8) | b; } - + public static int color(String hex) { int r = Integer.parseInt(hex.substring(0, 2), 16); int g = Integer.parseInt(hex.substring(2, 4), 16); int b = Integer.parseInt(hex.substring(4, 6), 16); return color(r, g, b); } - + public static int[] toIntArray(int color) { - return new int[] { - (color >> 24) & 255, - (color >> 16) & 255, - (color >> 8) & 255, - color & 255 - }; + return new int[] {(color >> 24) & 255, (color >> 16) & 255, (color >> 8) & 255, color & 255}; } - + public static float[] toFloatArray(int color) { FLOAT_BUFFER[0] = ((color >> 16 & 255) / 255.0F); FLOAT_BUFFER[1] = ((color >> 8 & 255) / 255.0F); FLOAT_BUFFER[2] = ((color & 255) / 255.0F); FLOAT_BUFFER[3] = ((color >> 24 & 255) / 255.0F); - + return FLOAT_BUFFER; } - + public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) { float hue, saturation, brightness; if (hsbvals == null) { @@ -63,34 +57,27 @@ public class ColorUtil { if (b > cmax) cmax = b; int cmin = (r < g) ? r : g; if (b < cmin) cmin = b; - + brightness = ((float) cmax) / 255.0F; - if (cmax != 0) - saturation = ((float) (cmax - cmin)) / ((float) cmax); - else - saturation = 0; - if (saturation == 0) - hue = 0; + if (cmax != 0) saturation = ((float) (cmax - cmin)) / ((float) cmax); + else saturation = 0; + if (saturation == 0) hue = 0; else { float redc = ((float) (cmax - r)) / ((float) (cmax - cmin)); float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin)); float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin)); - if (r == cmax) - hue = bluec - greenc; - else if (g == cmax) - hue = 2.0F + redc - bluec; - else - hue = 4.0F + greenc - redc; + if (r == cmax) hue = bluec - greenc; + else if (g == cmax) hue = 2.0F + redc - bluec; + else hue = 4.0F + greenc - redc; hue = hue / 6.0F; - if (hue < 0) - hue = hue + 1.0F; + if (hue < 0) hue = hue + 1.0F; } hsbvals[0] = hue; hsbvals[1] = saturation; hsbvals[2] = brightness; return hsbvals; } - + public static int HSBtoRGB(float hue, float saturation, float brightness) { int r = 0, g = 0, b = 0; if (saturation == 0) { @@ -137,13 +124,13 @@ public class ColorUtil { } return 0xFF000000 | (r << 16) | (g << 8) | (b << 0); } - + public static int parseHex(String hexColor) { int len = hexColor.length(); if (len < 6 || len > 8 || len % 2 > 0) { return -1; } - + int color, shift; if (len == 6) { color = 0xFF000000; @@ -153,7 +140,7 @@ public class ColorUtil { color = 0; shift = 24; } - + try { String[] splited = hexColor.split("(?<=\\G.{2})"); for (String digit : splited) { @@ -165,17 +152,17 @@ public class ColorUtil { BCLib.LOGGER.catching(ex); return -1; } - + return color; } - + public static int toABGR(int color) { int r = (color >> 16) & 255; int g = (color >> 8) & 255; int b = color & 255; return 0xFF000000 | b << 16 | g << 8 | r; } - + public static int ABGRtoARGB(int color) { int a = (color >> 24) & 255; int b = (color >> 16) & 255; @@ -183,18 +170,18 @@ public class ColorUtil { int r = color & 255; return a << 24 | r << 16 | g << 8 | b; } - + public static int colorBrigtness(int color, float val) { RGBtoHSB((color >> 16) & 255, (color >> 8) & 255, color & 255, FLOAT_BUFFER); FLOAT_BUFFER[2] += val / 10.0F; FLOAT_BUFFER[2] = Mth.clamp(FLOAT_BUFFER[2], 0.0F, 1.0F); return HSBtoRGB(FLOAT_BUFFER[0], FLOAT_BUFFER[1], FLOAT_BUFFER[2]); } - + public static int applyTint(int color, int tint) { return colorBrigtness(ColorHelper.multiplyColor(color, tint), 1.5F); } - + public static int colorDistance(int color1, int color2) { int r1 = (color1 >> 16) & 255; int g1 = (color1 >> 8) & 255; @@ -204,9 +191,9 @@ public class ColorUtil { int b2 = color2 & 255; return MHelper.sqr(r1 - r2) + MHelper.sqr(g1 - g2) + MHelper.sqr(b1 - b2); } - + private static Map colorPalette = Maps.newHashMap(); - + @Environment(EnvType.CLIENT) public static int extractColor(Item item) { ResourceLocation id = Registry.ITEM.getKey(item); @@ -232,16 +219,16 @@ public class ColorUtil { } } image.close(); - + if (colors.size() == 0) return -1; - + ColorExtractor extractor = new ColorExtractor(colors); int color = extractor.analize(); colorPalette.put(id, color); - + return color; } - + @Environment(EnvType.CLIENT) public static NativeImage loadImage(ResourceLocation image, int w, int h) { Minecraft minecraft = Minecraft.getInstance(); diff --git a/src/main/java/ru/bclib/util/JsonFactory.java b/src/main/java/ru/bclib/util/JsonFactory.java index 9397f32c..72df3a38 100644 --- a/src/main/java/ru/bclib/util/JsonFactory.java +++ b/src/main/java/ru/bclib/util/JsonFactory.java @@ -1,5 +1,11 @@ package ru.bclib.util; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import ru.bclib.BCLib; + import java.io.File; import java.io.FileReader; import java.io.FileWriter; @@ -8,16 +14,9 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import ru.bclib.BCLib; - public class JsonFactory { public final static Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - + public static JsonObject getJsonObject(InputStream stream) { try { Reader reader = new InputStreamReader(stream); @@ -32,7 +31,7 @@ public class JsonFactory { } return new JsonObject(); } - + public static JsonObject getJsonObject(File jsonFile) { if (jsonFile.exists()) { JsonElement json = loadJson(jsonFile); @@ -43,7 +42,7 @@ public class JsonFactory { } return new JsonObject(); } - + public static JsonElement loadJson(File jsonFile) { if (jsonFile.exists()) { try (Reader reader = new FileReader(jsonFile)) { @@ -55,11 +54,11 @@ public class JsonFactory { } return null; } - + public static JsonElement loadJson(Reader reader) { return GSON.fromJson(reader, JsonElement.class); } - + public static void storeJson(File jsonFile, JsonElement jsonObject) { try (FileWriter writer = new FileWriter(jsonFile)) { String json = GSON.toJson(jsonObject); @@ -70,22 +69,22 @@ public class JsonFactory { BCLib.LOGGER.catching(ex); } } - + public static int getInt(JsonObject object, String member, int def) { JsonElement elem = object.get(member); return elem == null ? def : elem.getAsInt(); } - + public static float getFloat(JsonObject object, String member, float def) { JsonElement elem = object.get(member); return elem == null ? def : elem.getAsFloat(); } - + public static boolean getBoolean(JsonObject object, String member, boolean def) { JsonElement elem = object.get(member); return elem == null ? def : elem.getAsBoolean(); } - + public static String getString(JsonObject object, String member, String def) { JsonElement elem = object.get(member); return elem == null ? def : elem.getAsString(); diff --git a/src/main/java/ru/bclib/util/Logger.java b/src/main/java/ru/bclib/util/Logger.java index 52721bac..68cce157 100644 --- a/src/main/java/ru/bclib/util/Logger.java +++ b/src/main/java/ru/bclib/util/Logger.java @@ -6,56 +6,56 @@ import org.apache.logging.log4j.LogManager; public final class Logger { private static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger(); private final String modPref; - + public Logger(String modID) { this.modPref = "[" + modID + "] "; } - + public void log(Level level, String message) { LOGGER.log(level, modPref + message); } - + public void log(Level level, String message, Object... params) { LOGGER.log(level, modPref + message, params); } - + public void debug(Object message) { this.log(Level.DEBUG, message.toString()); } - + public void debug(Object message, Object... params) { this.log(Level.DEBUG, message.toString(), params); } - + public void catching(Throwable ex) { this.error(ex.getLocalizedMessage()); LOGGER.catching(ex); } - + public void info(String message) { this.log(Level.INFO, message); } - + public void info(String message, Object... params) { this.log(Level.INFO, message, params); } - + public void warning(String message, Object... params) { this.log(Level.WARN, message, params); } - + public void warning(String message, Object obj, Exception ex) { LOGGER.warn(modPref + message, obj, ex); } - + public void error(String message) { this.log(Level.ERROR, message); } - + public void error(String message, Object obj, Exception ex) { LOGGER.error(modPref + message, obj, ex); } - + public void error(String message, Exception ex) { LOGGER.error(modPref + message, ex); } diff --git a/src/main/java/ru/bclib/util/MHelper.java b/src/main/java/ru/bclib/util/MHelper.java index b7d53913..95bb8853 100644 --- a/src/main/java/ru/bclib/util/MHelper.java +++ b/src/main/java/ru/bclib/util/MHelper.java @@ -1,18 +1,17 @@ package ru.bclib.util; -import java.util.Random; - import com.mojang.math.Vector3f; - import net.minecraft.core.Vec3i; +import java.util.Random; + public class MHelper { private static final Vec3i[] RANDOM_OFFSETS = new Vec3i[3 * 3 * 3 - 1]; private static final float RAD_TO_DEG = 57.295779513082320876798154814105F; public static final float PHI = (float) (Math.PI * (3 - Math.sqrt(5))); public static final float PI2 = (float) (Math.PI * 2); public static final Random RANDOM = new Random(); - + public static int randRange(int min, int max, Random random) { return min + random.nextInt(max - min + 1); } @@ -20,37 +19,37 @@ public class MHelper { public static double randRange(double min, double max, Random random) { return min + random.nextDouble() * (max - min); } - + public static float randRange(float min, float max, Random random) { return min + random.nextFloat() * (max - min); } - + public static byte setBit(byte source, int pos, boolean value) { return value ? setBitTrue(source, pos) : setBitFalse(source, pos); } - + public static byte setBitTrue(byte source, int pos) { source |= 1 << pos; return source; } - + public static byte setBitFalse(byte source, int pos) { source &= ~(1 << pos); return source; } - + public static boolean getBit(byte source, int pos) { return ((source >> pos) & 1) == 1; } - + public static float wrap(float x, float side) { return x - floor(x / side) * side; } - + public static int floor(double x) { return x < 0 ? (int) (x - 1) : (int) x; } - + public static int min(int a, int b) { return a < b ? a : b; } @@ -134,7 +133,7 @@ public class MHelper { h = (h ^ (h >> 13)) * 1274126177; return h ^ (h >> 16); } - + public static int getSeed(int seed, int x, int y, int z) { int h = seed + x * 374761393 + y * 668265263 + z; h = (h ^ (h >> 13)) * 1274126177; @@ -149,7 +148,7 @@ public class MHelper { array[i2] = element; } } - + public static int sqr(int i) { return i * i; } @@ -170,8 +169,7 @@ public class MHelper { return value / RAD_TO_DEG; } - public static Vector3f cross(Vector3f vec1, Vector3f vec2) - { + public static Vector3f cross(Vector3f vec1, Vector3f vec2) { float cx = vec1.y() * vec2.z() - vec1.z() * vec2.y(); float cy = vec1.z() * vec2.x() - vec1.x() * vec2.z(); float cz = vec1.x() * vec2.y() - vec1.y() * vec2.x(); diff --git a/src/main/java/ru/bclib/util/SplineHelper.java b/src/main/java/ru/bclib/util/SplineHelper.java index 0b1e8a75..844e357a 100644 --- a/src/main/java/ru/bclib/util/SplineHelper.java +++ b/src/main/java/ru/bclib/util/SplineHelper.java @@ -1,13 +1,7 @@ package ru.bclib.util; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.function.Function; - import com.google.common.collect.Lists; import com.mojang.math.Vector3f; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.util.Mth; @@ -17,6 +11,11 @@ import ru.bclib.sdf.SDF; import ru.bclib.sdf.operator.SDFUnion; import ru.bclib.sdf.primitive.SDFLine; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.Function; + public class SplineHelper { public static List makeSpline(float x1, float y1, float z1, float x2, float y2, float z2, int points) { List spline = Lists.newArrayList(); @@ -86,11 +85,7 @@ public class SplineHelper { for (int i = 1; i < count; i++) { Vector3f pos = spline.get(i); float delta = (float) (i - 1) / max; - SDF line = new SDFLine() - .setRadius(Mth.lerp(delta, radius1, radius2)) - .setStart(start.x(), start.y(), start.z()) - .setEnd(pos.x(), pos.y(), pos.z()) - .setBlock(placerFunction); + SDF line = new SDFLine().setRadius(Mth.lerp(delta, radius1, radius2)).setStart(start.x(), start.y(), start.z()).setEnd(pos.x(), pos.y(), pos.z()).setBlock(placerFunction); result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); start = pos; } @@ -105,11 +100,7 @@ public class SplineHelper { for (int i = 1; i < count; i++) { Vector3f pos = spline.get(i); float delta = (float) (i - 1) / max; - SDF line = new SDFLine() - .setRadius(radiusFunction.apply(delta)) - .setStart(start.x(), start.y(), start.z()) - .setEnd(pos.x(), pos.y(), pos.z()) - .setBlock(placerFunction); + SDF line = new SDFLine().setRadius(radiusFunction.apply(delta)).setStart(start.x(), start.y(), start.z()).setEnd(pos.x(), pos.y(), pos.z()).setBlock(placerFunction); result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); start = pos; } @@ -309,7 +300,7 @@ public class SplineHelper { } public static void rotateSpline(List spline, float angle) { - for (Vector3f v: spline) { + for (Vector3f v : spline) { float sin = (float) Math.sin(angle); float cos = (float) Math.cos(angle); float x = v.x() * cos + v.z() * sin; @@ -320,7 +311,7 @@ public class SplineHelper { public static List copySpline(List spline) { List result = new ArrayList(spline.size()); - for (Vector3f v: spline) { + for (Vector3f v : spline) { result.add(new Vector3f(v.x(), v.y(), v.z())); } return result; @@ -331,13 +322,13 @@ public class SplineHelper { } public static void scale(List spline, float x, float y, float z) { - for (Vector3f v: spline) { + for (Vector3f v : spline) { v.set(v.x() * x, v.y() * y, v.z() * z); } } public static void offset(List spline, Vector3f offset) { - for (Vector3f v: spline) { + for (Vector3f v : spline) { v.set(offset.x() + v.x(), offset.y() + v.y(), offset.z() + v.z()); } } diff --git a/src/main/java/ru/bclib/util/StructureHelper.java b/src/main/java/ru/bclib/util/StructureHelper.java index 9d724ac8..aed50005 100644 --- a/src/main/java/ru/bclib/util/StructureHelper.java +++ b/src/main/java/ru/bclib/util/StructureHelper.java @@ -1,16 +1,6 @@ package ru.bclib.util; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Random; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - import com.google.common.collect.Sets; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -31,6 +21,15 @@ import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.Vec3; import ru.bclib.api.TagAPI; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + public class StructureHelper { private static final Direction[] DIR = BlocksHelper.makeHorizontal(); @@ -54,7 +53,7 @@ public class StructureHelper { long compressedSize = entry.getCompressedSize(); long normalSize = entry.getSize(); String type = entry.isDirectory() ? "DIR" : "FILE"; - + System.out.println(name); System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize); } @@ -80,10 +79,10 @@ public class StructureHelper { private static StructureTemplate readStructureFromStream(InputStream stream) throws IOException { CompoundTag nbttagcompound = NbtIo.readCompressed(stream); - + StructureTemplate template = new StructureTemplate(); template.load(nbttagcompound); - + return template; } @@ -181,7 +180,7 @@ public class StructureHelper { } if (!state.isAir() && random.nextBoolean()) { MHelper.shuffle(DIR, random); - for (Direction dir: DIR) { + for (Direction dir : DIR) { if (world.isEmptyBlock(mut.relative(dir)) && world.isEmptyBlock(mut.below().relative(dir))) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); mut.move(dir).move(Direction.DOWN); @@ -226,7 +225,7 @@ public class StructureHelper { } } } - + public static void erodeIntense(WorldGenLevel world, BoundingBox bounds, Random random) { MutableBlockPos mut = new MutableBlockPos(); MutableBlockPos mut2 = new MutableBlockPos(); @@ -261,12 +260,12 @@ public class StructureHelper { } } } - + drop(world, bounds); } private static boolean isTerrainNear(WorldGenLevel world, BlockPos pos) { - for (Direction dir: BlocksHelper.DIRECTIONS) { + for (Direction dir : BlocksHelper.DIRECTIONS) { if (world.getBlockState(pos.relative(dir)).is(TagAPI.GEN_TERRAIN)) { return true; } @@ -300,8 +299,8 @@ public class StructureHelper { } while (!edge.isEmpty()) { - for (BlockPos center: edge) { - for (Direction dir: BlocksHelper.DIRECTIONS) { + for (BlockPos center : edge) { + for (Direction dir : BlocksHelper.DIRECTIONS) { BlockState state = world.getBlockState(center); if (state.isCollisionShapeFullBlock(world, center)) { mut.set(center).move(dir); @@ -343,16 +342,9 @@ public class StructureHelper { } } } - + private static boolean ignore(BlockState state, WorldGenLevel world, BlockPos pos) { - return state.getMaterial().isReplaceable() || - !state.getFluidState().isEmpty() || - state.is(TagAPI.END_GROUND) || - state.is(BlockTags.LOGS) || - state.is(BlockTags.LEAVES) || - state.getMaterial().equals(Material.PLANT) || - state.getMaterial().equals(Material.LEAVES) || - BlocksHelper.isInvulnerable(state, world, pos); + return state.getMaterial().isReplaceable() || !state.getFluidState().isEmpty() || state.is(TagAPI.END_GROUND) || state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES) || state.getMaterial().equals(Material.PLANT) || state.getMaterial().equals(Material.LEAVES) || BlocksHelper.isInvulnerable(state, world, pos); } public static void cover(WorldGenLevel world, BoundingBox bounds, Random random) { diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java index dae193d0..29126662 100644 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -1,11 +1,7 @@ package ru.bclib.util; -import java.util.Map; -import java.util.Set; - import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; @@ -13,6 +9,9 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; +import java.util.Map; +import java.util.Set; + public class TagHelper { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); @@ -20,7 +19,7 @@ public class TagHelper { public static void addTag(Tag.Named tag, Block... blocks) { ResourceLocation tagID = tag.getName(); Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (Block block: blocks) { + for (Block block : blocks) { ResourceLocation id = Registry.BLOCK.getKey(block); if (id != Registry.BLOCK.getDefaultKey()) { set.add(id); @@ -31,7 +30,7 @@ public class TagHelper { public static void addTag(Tag.Named tag, ItemLike... items) { ResourceLocation tagID = tag.getName(); Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (ItemLike item: items) { + for (ItemLike item : items) { ResourceLocation id = Registry.ITEM.getKey(item.asItem()); if (id != Registry.ITEM.getDefaultKey()) { set.add(id); @@ -41,14 +40,14 @@ public class TagHelper { @SafeVarargs public static void addTags(ItemLike item, Tag.Named... tags) { - for (Tag.Named tag: tags) { + for (Tag.Named tag : tags) { addTag(tag, item); } } @SafeVarargs public static void addTags(Block block, Tag.Named... tags) { - for (Tag.Named tag: tags) { + for (Tag.Named tag : tags) { addTag(tag, block); } } @@ -62,7 +61,8 @@ public class TagHelper { Map> endTags = null; if ("tags/blocks".equals(directory)) { endTags = TAGS_BLOCK; - } else if ("tags/items".equals(directory)) { + } + else if ("tags/items".equals(directory)) { endTags = TAGS_ITEM; } if (endTags != null) { diff --git a/src/main/java/ru/bclib/util/TranslationHelper.java b/src/main/java/ru/bclib/util/TranslationHelper.java index 68ad5412..3540a39a 100644 --- a/src/main/java/ru/bclib/util/TranslationHelper.java +++ b/src/main/java/ru/bclib/util/TranslationHelper.java @@ -1,18 +1,17 @@ package ru.bclib.util; +import com.google.common.collect.Lists; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import net.minecraft.core.Registry; +import net.minecraft.data.BuiltinRegistries; +import net.minecraft.resources.ResourceLocation; + import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collections; import java.util.List; -import com.google.common.collect.Lists; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import net.minecraft.core.Registry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceLocation; - public class TranslationHelper { public static void printMissingNames(String modID) { List missingNamesEn = Lists.newArrayList(); diff --git a/src/main/java/ru/bclib/util/WeighTree.java b/src/main/java/ru/bclib/util/WeighTree.java index 096747c4..8aca4f5f 100644 --- a/src/main/java/ru/bclib/util/WeighTree.java +++ b/src/main/java/ru/bclib/util/WeighTree.java @@ -14,6 +14,7 @@ public class WeighTree { /** * Get eandom value from tree. + * * @param random - {@link Random}. * @return {@link T} value. */ @@ -53,7 +54,7 @@ public class WeighTree { this.min = min; this.max = max; } - + @Override T get(float value) { return value < separator ? min.get(value) : max.get(value); @@ -71,7 +72,7 @@ public class WeighTree { Leaf(T value) { this.biome = value; } - + @Override T get(float value) { return biome; diff --git a/src/main/java/ru/bclib/util/WeightedList.java b/src/main/java/ru/bclib/util/WeightedList.java index 5455dd39..3a7f3680 100644 --- a/src/main/java/ru/bclib/util/WeightedList.java +++ b/src/main/java/ru/bclib/util/WeightedList.java @@ -12,6 +12,7 @@ public class WeightedList { /** * Adds value with specified weight to the list + * * @param value * @param weight */ @@ -23,6 +24,7 @@ public class WeightedList { /** * Get random value. + * * @param random - {@link Random}. * @return {@link T} value. */ @@ -41,6 +43,7 @@ public class WeightedList { /** * Get value by index. + * * @param index - {@code int} index. * @return {@link T} value. */ @@ -50,33 +53,37 @@ public class WeightedList { /** * Get value weight. Weight is summed with all previous values weights. + * * @param index - {@code int} index. * @return {@code float} weight. */ public float getWeight(int index) { return weights.get(index); } - + /** * Chech if the list is empty. + * * @return {@code true} if list is empty and {@code false} if not. */ public boolean isEmpty() { return maxWeight == 0; } - + /** * Get the list size. + * * @return {@code int} list size. */ public int size() { return values.size(); } - + /** * Makes a sublist of this list with same weights. Used only in {@link WeighTree} + * * @param start - {@code int} start index (inclusive). - * @param end - {@code int} end index (exclusive). + * @param end - {@code int} end index (exclusive). * @return {@link WeightedList}. */ protected WeightedList subList(int start, int end) { @@ -87,26 +94,29 @@ public class WeightedList { } return list; } - + /** * Check if list contains certain value. + * * @param value - {@link T} value. * @return {@code true} if value is in list and {@code false} if not. */ public boolean contains(T value) { return values.contains(value); } - + /** * Applies {@link Consumer} to all values in list. + * * @param function - {@link Consumer}. */ public void forEach(Consumer function) { values.forEach(function); } - + /** * Get the maximum weight of the tree. + * * @return {@code float} maximum weight. */ public float getMaxWeight() { diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiome.java b/src/main/java/ru/bclib/world/biomes/BCLBiome.java index d6326ebe..dcae78c1 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiome.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiome.java @@ -1,15 +1,9 @@ package ru.bclib.world.biomes; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Random; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.JsonArray; import com.google.gson.JsonObject; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.Biome; @@ -21,23 +15,28 @@ import ru.bclib.world.features.ListFeature; import ru.bclib.world.features.ListFeature.StructureInfo; import ru.bclib.world.features.NBTStructureFeature.TerrainMerge; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Random; + public class BCLBiome { protected WeightedList subbiomes = new WeightedList(); - + protected final Biome biome; protected final ResourceLocation mcID; protected BCLBiome edge; protected int edgeSize; - + protected BCLBiome biomeParent; protected float maxSubBiomeChance = 1; protected final float genChance; - + private final Map customData; private final float fogDensity; private BCLFeature structuresFeature; private Biome actualBiome; - + public BCLBiome(BCLBiomeDef definition) { this.mcID = definition.getID(); this.readStructureList(); @@ -49,7 +48,7 @@ public class BCLBiome { this.fogDensity = definition.getFodDensity(); this.customData = definition.getCustomData(); } - + public BCLBiome(ResourceLocation id, Biome biome, float fogDensity, float genChance) { this.mcID = id; this.biome = biome; @@ -58,24 +57,24 @@ public class BCLBiome { this.readStructureList(); this.customData = Maps.newHashMap(); } - + public BCLBiome getEdge() { return edge == null ? this : edge; } - + public void setEdge(BCLBiome edge) { this.edge = edge; edge.biomeParent = this; } - + public int getEdgeSize() { return edgeSize; } - + public void setEdgeSize(int size) { edgeSize = size; } - + public void addSubBiome(BCLBiome biome) { biome.biomeParent = this; subbiomes.add(biome, biome.getGenChance()); @@ -84,41 +83,41 @@ public class BCLBiome { public boolean containsSubBiome(BCLBiome biome) { return subbiomes.contains(biome); } - + public BCLBiome getSubBiome(Random random) { BCLBiome biome = subbiomes.get(random); return biome == null ? this : biome; } - + public BCLBiome getParentBiome() { return this.biomeParent; } - + public boolean hasEdge() { return edge != null; } - + public boolean hasParentBiome() { return biomeParent != null; } - + public boolean isSame(BCLBiome biome) { return biome == this || (biome.hasParentBiome() && biome.getParentBiome() == this); } - + public Biome getBiome() { return biome; } - + @Override public String toString() { return mcID.toString(); } - + public ResourceLocation getID() { return mcID; } - + public float getFogDensity() { return fogDensity; } @@ -126,7 +125,7 @@ public class BCLBiome { protected void readStructureList() { String ns = mcID.getNamespace(); String nm = mcID.getPath(); - + String path = "/data/" + ns + "/structures/biome/" + nm + "/"; InputStream inputstream = StructureHelper.class.getResourceAsStream(path + "structures.json"); if (inputstream != null) { @@ -155,7 +154,7 @@ public class BCLBiome { public Biome getActualBiome() { return this.actualBiome; } - + public float getGenChance() { return this.genChance; } diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index 1d77c26d..3c5e6013 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -1,11 +1,7 @@ package ru.bclib.world.biomes; -import java.util.List; -import java.util.Map; - import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import net.minecraft.core.Registry; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.resources.ResourceLocation; @@ -32,7 +28,6 @@ import net.minecraft.world.level.levelgen.carver.CarverConfiguration; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; -import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration; import net.minecraft.world.level.levelgen.surfacebuilders.ConfiguredSurfaceBuilder; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilder; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderBaseConfiguration; @@ -42,6 +37,9 @@ import ru.bclib.world.features.BCLFeature; import ru.bclib.world.structures.BCLStructureFeature; import ru.bclib.world.surface.DoubleBlockSurfaceBuilder; +import java.util.List; +import java.util.Map; + public class BCLBiomeDef { public static final int DEF_FOLIAGE_OVERWORLD = ColorUtil.color(110, 143, 64); public static final int DEF_FOLIAGE_NETHER = ColorUtil.color(117, 10, 10); @@ -55,13 +53,13 @@ public class BCLBiomeDef { private final Map customData = Maps.newHashMap(); private final ResourceLocation id; - + private AmbientParticleSettings particleConfig; private AmbientAdditionsSettings additions; private AmbientMoodSettings mood; private SoundEvent music; private SoundEvent loop; - + private int foliageColor = DEF_FOLIAGE_OVERWORLD; private int grassColor = DEF_FOLIAGE_OVERWORLD; private int waterFogColor = 329011; @@ -78,17 +76,19 @@ public class BCLBiomeDef { private int edgeSize = 32; private ConfiguredSurfaceBuilder surface; - + /** * Custom biome definition. Can be extended with new parameters. + * * @param id - Biome {@link ResourceLocation} (identifier). */ public BCLBiomeDef(ResourceLocation id) { this.id = id; } - /** + /** * Create default definition for The Nether biome. + * * @return {@link BCLBiomeDef}. */ public BCLBiomeDef netherBiome() { @@ -98,8 +98,9 @@ public class BCLBiomeDef { return this; } - /** + /** * Create default definition for The End biome. + * * @return {@link BCLBiomeDef}. */ public BCLBiomeDef endBiome() { @@ -111,6 +112,7 @@ public class BCLBiomeDef { /** * Used to load biome settings from config. + * * @param config - {@link IdConfig}. * @return this {@link BCLBiomeDef}. */ @@ -123,6 +125,7 @@ public class BCLBiomeDef { /** * Set category of the biome. + * * @param category - {@link BiomeCategory}. * @return this {@link BCLBiomeDef}. */ @@ -137,11 +140,7 @@ public class BCLBiomeDef { } public BCLBiomeDef setSurface(Block block) { - setSurface(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderBaseConfiguration( - block.defaultBlockState(), - Blocks.END_STONE.defaultBlockState(), - Blocks.END_STONE.defaultBlockState() - ))); + setSurface(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderBaseConfiguration(block.defaultBlockState(), Blocks.END_STONE.defaultBlockState(), Blocks.END_STONE.defaultBlockState()))); return this; } @@ -154,7 +153,7 @@ public class BCLBiomeDef { this.surface = builder; return this; } - + public BCLBiomeDef setParticles(ParticleOptions particle, float probability) { this.particleConfig = new AmbientParticleSettings(particle, probability); return this; @@ -184,7 +183,7 @@ public class BCLBiomeDef { this.edgeSize = edgeSize; return this; } - + public BCLBiomeDef addMobSpawn(EntityType type, int weight, int minGroupSize, int maxGroupSize) { ResourceLocation eID = Registry.ENTITY_TYPE.getKey(type); if (eID != Registry.ENTITY_TYPE.getDefaultKey()) { @@ -202,7 +201,7 @@ public class BCLBiomeDef { spawns.add(entry); return this; } - + public BCLBiomeDef addStructureFeature(ConfiguredStructureFeature feature) { structures.add(feature); return this; @@ -220,7 +219,7 @@ public class BCLBiomeDef { features.add(info); return this; } - + public BCLBiomeDef addFeature(Decoration featureStep, ConfiguredFeature feature) { FeatureInfo info = new FeatureInfo(); info.featureStep = featureStep; @@ -235,22 +234,22 @@ public class BCLBiomeDef { b = Mth.clamp(b, 0, 255); return ColorUtil.color(r, g, b); } - + public BCLBiomeDef setFogColor(int r, int g, int b) { this.fogColor = getColor(r, g, b); return this; } - + public BCLBiomeDef setFogDensity(float density) { this.fogDensity = density; return this; } - + public BCLBiomeDef setWaterColor(int r, int g, int b) { this.waterColor = getColor(r, g, b); return this; } - + public BCLBiomeDef setWaterFogColor(int r, int g, int b) { this.waterFogColor = getColor(r, g, b); return this; @@ -273,32 +272,32 @@ public class BCLBiomeDef { public BCLBiomeDef setPlantsColor(int r, int g, int b) { return this.setFoliageColor(r, g, b).setGrassColor(r, g, b); } - + public BCLBiomeDef setLoop(SoundEvent loop) { this.loop = loop; return this; } - + public BCLBiomeDef setMood(SoundEvent mood) { this.mood = new AmbientMoodSettings(mood, 6000, 8, 2.0D); return this; } - + public BCLBiomeDef setAdditions(SoundEvent additions) { this.additions = new AmbientAdditionsSettings(additions, 0.0111); return this; } - + public BCLBiomeDef setMusic(SoundEvent music) { this.music = music; return this; } - + public Biome build() { MobSpawnSettings.Builder spawnSettings = new MobSpawnSettings.Builder(); BiomeGenerationSettings.Builder generationSettings = new BiomeGenerationSettings.Builder(); Builder effects = new Builder(); - + mobs.forEach((spawn) -> { spawnSettings.addSpawn(spawn.type.getCategory(), new MobSpawnSettings.SpawnerData(spawn.type, spawn.weight, spawn.minGroupSize, spawn.maxGroupSize)); }); @@ -311,34 +310,24 @@ public class BCLBiomeDef { structures.forEach((structure) -> generationSettings.addStructureStart(structure)); features.forEach((info) -> generationSettings.addFeature(info.featureStep, info.feature)); carvers.forEach((info) -> generationSettings.addCarver(info.carverStep, info.carver)); - + effects.skyColor(0).waterColor(waterColor).waterFogColor(waterFogColor).fogColor(fogColor).foliageColorOverride(foliageColor).grassColorOverride(grassColor); if (loop != null) effects.ambientLoopSound(loop); if (mood != null) effects.ambientMoodSound(mood); if (additions != null) effects.ambientAdditionsSound(additions); if (particleConfig != null) effects.ambientParticle(particleConfig); effects.backgroundMusic(music != null ? new Music(music, 600, 2400, true) : Musics.END); - - return new Biome.BiomeBuilder() - .precipitation(precipitation) - .biomeCategory(category) - .depth(depth) - .scale(0.2F) - .temperature(temperature) - .downfall(downfall) - .specialEffects(effects.build()) - .mobSpawnSettings(spawnSettings.build()) - .generationSettings(generationSettings.build()) - .build(); + + return new Biome.BiomeBuilder().precipitation(precipitation).biomeCategory(category).depth(depth).scale(0.2F).temperature(temperature).downfall(downfall).specialEffects(effects.build()).mobSpawnSettings(spawnSettings.build()).generationSettings(generationSettings.build()).build(); } - + private static final class SpawnInfo { EntityType type; int weight; int minGroupSize; int maxGroupSize; } - + private static final class FeatureInfo { Decoration featureStep; ConfiguredFeature feature; @@ -348,7 +337,7 @@ public class BCLBiomeDef { Carving carverStep; ConfiguredWorldCarver carver; } - + public ResourceLocation getID() { return id; } @@ -356,7 +345,7 @@ public class BCLBiomeDef { public float getFodDensity() { return fogDensity; } - + public float getGenChance() { return genChance; } @@ -364,7 +353,7 @@ public class BCLBiomeDef { public int getEdgeSize() { return edgeSize; } - + public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { CarverInfo info = new CarverInfo(); info.carverStep = carverStep; diff --git a/src/main/java/ru/bclib/world/features/BCLDecorators.java b/src/main/java/ru/bclib/world/features/BCLDecorators.java index d037c5f6..ee5b60b2 100644 --- a/src/main/java/ru/bclib/world/features/BCLDecorators.java +++ b/src/main/java/ru/bclib/world/features/BCLDecorators.java @@ -8,7 +8,7 @@ import java.lang.reflect.Field; public class BCLDecorators { public static final ConfiguredDecorator HEIGHTMAP_SQUARE; - + private static final ConfiguredDecorator getDecorator(Field[] fields, int index) { try { return (ConfiguredDecorator) fields[index].get(null); @@ -18,7 +18,7 @@ public class BCLDecorators { return null; } } - + static { Class[] classes = Features.class.getDeclaredClasses(); Field[] fields = classes[1].getDeclaredFields(); // Decorators class diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index 2227cddd..df27a021 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -2,9 +2,7 @@ package ru.bclib.world.features; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; -import net.minecraft.data.worldgen.Features; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.GenerationStep; @@ -15,7 +13,6 @@ import net.minecraft.world.level.levelgen.feature.configurations.CountConfigurat import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.OreConfiguration; -import net.minecraft.world.level.levelgen.feature.configurations.RangeDecoratorConfiguration; import net.minecraft.world.level.levelgen.placement.ChanceDecoratorConfiguration; import net.minecraft.world.level.levelgen.placement.FeatureDecorator; import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest; @@ -28,7 +25,7 @@ public class BCLFeature { private ConfiguredFeature featureConfigured; private GenerationStep.Decoration featureStep; private Feature feature; - + public BCLFeature(Feature feature, ConfiguredFeature configuredFeature, GenerationStep.Decoration featureStep) { this.featureConfigured = configuredFeature; this.featureStep = featureStep; @@ -59,10 +56,7 @@ public class BCLFeature { public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, int veins, int veinSize, int offset, int minY, int maxY) { OreConfiguration featureConfig = new OreConfiguration(new BlockMatchTest(Blocks.END_STONE), blockOre.defaultBlockState(), veinSize); OreConfiguration config = new OreConfiguration(ANY_TERRAIN, blockOre.defaultBlockState(), 33); - ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig) - .rangeUniform(VerticalAnchor.absolute(minY), VerticalAnchor.absolute(maxY)) - .squared() - .count(veins); + ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig).rangeUniform(VerticalAnchor.absolute(minY), VerticalAnchor.absolute(maxY)).squared().count(veins); return new BCLFeature(Feature.ORE, Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), GenerationStep.Decoration.UNDERGROUND_ORES); } @@ -89,11 +83,11 @@ public class BCLFeature { public Feature getFeature() { return feature; } - + public ConfiguredFeature getFeatureConfigured() { return featureConfigured; } - + public GenerationStep.Decoration getFeatureStep() { return featureStep; } diff --git a/src/main/java/ru/bclib/world/features/ListFeature.java b/src/main/java/ru/bclib/world/features/ListFeature.java index 8f00c087..a6990896 100644 --- a/src/main/java/ru/bclib/world/features/ListFeature.java +++ b/src/main/java/ru/bclib/world/features/ListFeature.java @@ -1,8 +1,5 @@ package ru.bclib.world.features; -import java.util.List; -import java.util.Random; - import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Mirror; @@ -11,6 +8,9 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlac import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import ru.bclib.util.StructureHelper; +import java.util.List; +import java.util.Random; + public class ListFeature extends NBTStructureFeature { private final List list; private StructureInfo selected; @@ -24,29 +24,29 @@ public class ListFeature extends NBTStructureFeature { selected = list.get(random.nextInt(list.size())); return selected.getStructure(); } - + @Override protected boolean canSpawn(WorldGenLevel world, BlockPos pos, Random random) { int cx = pos.getX() >> 4; int cz = pos.getZ() >> 4; return ((cx + cz) & 1) == 0 && pos.getY() > 58;// && world.getBlockState(pos.below()).is(EndTags.GEN_TERRAIN); } - + @Override protected Rotation getRotation(WorldGenLevel world, BlockPos pos, Random random) { return Rotation.getRandom(random); } - + @Override protected Mirror getMirror(WorldGenLevel world, BlockPos pos, Random random) { return Mirror.values()[random.nextInt(3)]; } - + @Override protected int getYOffset(StructureTemplate structure, WorldGenLevel world, BlockPos pos, Random random) { return selected.offsetY; } - + @Override protected TerrainMerge getTerrainMerge(WorldGenLevel world, BlockPos pos, Random random) { return selected.terrainMerge; diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index e48bfb5a..afbad417 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -1,9 +1,5 @@ package ru.bclib.world.features; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; - import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -17,36 +13,38 @@ import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderConfiguration; -import net.minecraft.world.phys.Vec3; import ru.bclib.api.BiomeAPI; import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; import ru.bclib.world.processors.DestructionStructureProcessor; +import java.io.IOException; +import java.io.InputStream; +import java.util.Random; + public abstract class NBTStructureFeature extends DefaultFeature { protected static final DestructionStructureProcessor DESTRUCTION = new DestructionStructureProcessor(); - + protected abstract StructureTemplate getStructure(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract boolean canSpawn(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract Rotation getRotation(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract Mirror getMirror(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract int getYOffset(StructureTemplate structure, WorldGenLevel world, BlockPos pos, Random random); - + protected abstract TerrainMerge getTerrainMerge(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract void addStructureData(StructurePlaceSettings data); - + protected BlockPos getGround(WorldGenLevel world, BlockPos center) { Biome biome = world.getBiome(center); ResourceLocation id = BiomeAPI.getBiomeID(biome); @@ -59,7 +57,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { return new BlockPos(center.getX(), y, center.getZ()); } } - + protected int getAverageY(WorldGenLevel world, BlockPos center) { int y = getYOnSurface(world, center.getX(), center.getZ()); y += getYOnSurface(world, center.getX() - 2, center.getZ() - 2); @@ -68,7 +66,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { y += getYOnSurface(world, center.getX() + 2, center.getZ() + 2); return y / 5; } - + protected int getAverageYWG(WorldGenLevel world, BlockPos center) { int y = getYOnSurfaceWG(world, center.getX(), center.getZ()); y += getYOnSurfaceWG(world, center.getX() - 2, center.getZ() - 2); @@ -77,33 +75,33 @@ public abstract class NBTStructureFeature extends DefaultFeature { y += getYOnSurfaceWG(world, center.getX() + 2, center.getZ() + 2); return y / 5; } - + @Override public boolean place(FeaturePlaceContext context) { WorldGenLevel world = context.level(); Random random = context.random(); BlockPos center = context.origin(); - + center = new BlockPos(((center.getX() >> 4) << 4) | 8, 128, ((center.getZ() >> 4) << 4) | 8); center = getGround(world, center); - + if (!canSpawn(world, center, random)) { return false; } - + int posY = center.getY() + 1; StructureTemplate structure = getStructure(world, center, random); Rotation rotation = getRotation(world, center, random); Mirror mirror = getMirror(world, center, random); BlockPos offset = StructureTemplate.transform(new BlockPos(structure.getSize()), mirror, rotation, BlockPos.ZERO); center = center.offset(0, getYOffset(structure, world, center, random) + 0.5, 0); - + BoundingBox bounds = makeBox(center); StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); addStructureData(placementData); center = center.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); structure.placeInWorld(world, center, center, placementData, random, 4); - + TerrainMerge merge = getTerrainMerge(world, center, random); int x1 = center.getX(); int z1 = center.getZ(); @@ -111,19 +109,19 @@ public abstract class NBTStructureFeature extends DefaultFeature { int z2 = z1 + offset.getZ(); if (merge != TerrainMerge.NONE) { MutableBlockPos mut = new MutableBlockPos(); - + if (x2 < x1) { int a = x1; x1 = x2; x2 = a; } - + if (z2 < z1) { int a = z1; z1 = z2; z2 = a; } - + int surfMax = posY - 1; for (int x = x1; x <= x2; x++) { mut.setX(x); @@ -149,8 +147,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { else { if (stateSt.is(TagAPI.END_GROUND) && state.getMaterial().isSolidBlocking()) { if (merge == TerrainMerge.SURFACE) { - SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings() - .getSurfaceBuilderConfig(); + SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings().getSurfaceBuilderConfig(); BlocksHelper.setWithoutUpdate(world, mut, config.getUnderMaterial()); } else { @@ -165,10 +162,10 @@ public abstract class NBTStructureFeature extends DefaultFeature { } } //BlocksHelper.fixBlocks(world, new BlockPos(x1, center.getY(), z1), new BlockPos(x2, center.getY() + offset.getY(), z2)); - + return true; } - + protected BoundingBox makeBox(BlockPos pos) { int sx = ((pos.getX() >> 4) << 4) - 16; int sz = ((pos.getZ() >> 4) << 4) - 16; @@ -176,35 +173,34 @@ public abstract class NBTStructureFeature extends DefaultFeature { int ez = sz + 47; return BoundingBox.fromCorners(new Vec3i(sx, 0, sz), new Vec3i(ex, 255, ez)); } - + protected static StructureTemplate readStructure(ResourceLocation resource) { String ns = resource.getNamespace(); String nm = resource.getPath(); - + try { - InputStream inputstream = MinecraftServer.class - .getResourceAsStream("/data/" + ns + "/structures/" + nm + ".nbt"); + InputStream inputstream = MinecraftServer.class.getResourceAsStream("/data/" + ns + "/structures/" + nm + ".nbt"); return readStructureFromStream(inputstream); } catch (IOException e) { e.printStackTrace(); } - + return null; } - + private static StructureTemplate readStructureFromStream(InputStream stream) throws IOException { CompoundTag nbttagcompound = NbtIo.readCompressed(stream); - + StructureTemplate template = new StructureTemplate(); template.load(nbttagcompound); - + return template; } - + public static enum TerrainMerge { NONE, SURFACE, OBJECT; - + public static TerrainMerge getFromString(String type) { if (type.equals("surface")) { return SURFACE; diff --git a/src/main/java/ru/bclib/world/generator/BiomeChunk.java b/src/main/java/ru/bclib/world/generator/BiomeChunk.java index 3fdb6358..93a5e9df 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeChunk.java +++ b/src/main/java/ru/bclib/world/generator/BiomeChunk.java @@ -1,34 +1,38 @@ package ru.bclib.world.generator; -import java.util.Random; - import ru.bclib.world.biomes.BCLBiome; +import java.util.Random; + public class BiomeChunk { protected static final int WIDTH = 16; private static final int SM_WIDTH = WIDTH >> 1; private static final int MASK_OFFSET = SM_WIDTH - 1; protected static final int MASK_WIDTH = WIDTH - 1; - + private final BCLBiome[][] biomes; - + public BiomeChunk(BiomeMap map, Random random, BiomePicker picker) { BCLBiome[][] PreBio = new BCLBiome[SM_WIDTH][SM_WIDTH]; biomes = new BCLBiome[WIDTH][WIDTH]; - - for (int x = 0; x < SM_WIDTH; x++) - for (int z = 0; z < SM_WIDTH; z++) + + for (int x = 0; x < SM_WIDTH; x++) { + for (int z = 0; z < SM_WIDTH; z++) { PreBio[x][z] = picker.getBiome(random); - - for (int x = 0; x < WIDTH; x++) - for (int z = 0; z < WIDTH; z++) + } + } + + for (int x = 0; x < WIDTH; x++) { + for (int z = 0; z < WIDTH; z++) { biomes[x][z] = PreBio[offsetXZ(x, random)][offsetXZ(z, random)].getSubBiome(random); + } + } } - + public BCLBiome getBiome(int x, int z) { return biomes[x & MASK_WIDTH][z & MASK_WIDTH]; } - + private int offsetXZ(int x, Random random) { return ((x + random.nextInt(2)) >> 1) & MASK_OFFSET; } diff --git a/src/main/java/ru/bclib/world/generator/BiomeMap.java b/src/main/java/ru/bclib/world/generator/BiomeMap.java index 088fda63..9de76325 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeMap.java +++ b/src/main/java/ru/bclib/world/generator/BiomeMap.java @@ -1,15 +1,14 @@ package ru.bclib.world.generator; -import java.util.Map; - import com.google.common.collect.Maps; - import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.levelgen.WorldgenRandom; import ru.bclib.noise.OpenSimplexNoise; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; +import java.util.Map; + public class BiomeMap { private static final WorldgenRandom RANDOM = new WorldgenRandom(); diff --git a/src/main/java/ru/bclib/world/generator/BiomePicker.java b/src/main/java/ru/bclib/world/generator/BiomePicker.java index 57eb36dd..bfdb5faf 100644 --- a/src/main/java/ru/bclib/world/generator/BiomePicker.java +++ b/src/main/java/ru/bclib/world/generator/BiomePicker.java @@ -1,17 +1,16 @@ package ru.bclib.world.generator; -import java.util.List; -import java.util.Random; -import java.util.Set; - import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import net.minecraft.resources.ResourceLocation; import ru.bclib.util.WeighTree; import ru.bclib.util.WeightedList; import ru.bclib.world.biomes.BCLBiome; +import java.util.List; +import java.util.Random; +import java.util.Set; + public class BiomePicker { private final Set immutableIDs = Sets.newHashSet(); private final List biomes = Lists.newArrayList(); @@ -21,7 +20,7 @@ public class BiomePicker { public void addBiome(BCLBiome biome) { immutableIDs.add(biome.getID()); biomes.add(biome); - biomeCount ++; + biomeCount++; } public void addBiomeMutable(BCLBiome biome) { diff --git a/src/main/java/ru/bclib/world/generator/BiomeType.java b/src/main/java/ru/bclib/world/generator/BiomeType.java index 6e40eb2c..7556894d 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeType.java +++ b/src/main/java/ru/bclib/world/generator/BiomeType.java @@ -1,6 +1,5 @@ package ru.bclib.world.generator; public enum BiomeType { - LAND, - VOID; + LAND, VOID; } diff --git a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java index 3d12057a..4c63a7e7 100644 --- a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java @@ -23,7 +23,7 @@ public class DestructionStructureProcessor extends StructureProcessor { } return structureBlockInfo2; } - + @Override protected StructureProcessorType getType() { return StructureProcessorType.RULE; diff --git a/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java index dceb0ee1..8231cde8 100644 --- a/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java @@ -19,7 +19,7 @@ public class TerrainStructureProcessor extends StructureProcessor { } return structureBlockInfo2; } - + @Override protected StructureProcessorType getType() { return StructureProcessorType.RULE; diff --git a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java index 581f0b60..3db8e57b 100644 --- a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java +++ b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java @@ -1,8 +1,7 @@ package ru.bclib.world.structures; -import java.util.Random; - import net.fabricmc.fabric.api.structure.v1.FabricStructureBuilder; +import net.fabricmc.fabric.mixin.structure.FlatChunkGeneratorConfigAccessor; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.levelgen.GenerationStep; @@ -10,6 +9,8 @@ import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; +import java.util.Random; + public class BCLStructureFeature { private static final Random RANDOM = new Random(354); private final StructureFeature structure; @@ -18,24 +19,22 @@ public class BCLStructureFeature { public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation) { this.featureStep = step; - this.structure = FabricStructureBuilder.create(id, structure) - .step(step) - .defaultConfig(spacing, separation, RANDOM.nextInt(8192)) - .register(); - - this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); + this.structure = FabricStructureBuilder.create(id, structure).step(step).defaultConfig(spacing, separation, RANDOM.nextInt(8192)).register(); + + this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); BuiltinRegistries.register(BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE, id, this.featureConfigured); + FlatChunkGeneratorConfigAccessor.getStructureToFeatures().put(this.structure, this.featureConfigured); } - + public StructureFeature getStructure() { return structure; } - + public ConfiguredStructureFeature getFeatureConfigured() { return featureConfigured; } - + public GenerationStep.Decoration getFeatureStep() { return featureStep; } diff --git a/src/main/java/ru/bclib/world/structures/StructureWorld.java b/src/main/java/ru/bclib/world/structures/StructureWorld.java index 8f3c80d5..48c2ea30 100644 --- a/src/main/java/ru/bclib/world/structures/StructureWorld.java +++ b/src/main/java/ru/bclib/world/structures/StructureWorld.java @@ -1,9 +1,6 @@ package ru.bclib.world.structures; -import java.util.Map; - import com.google.common.collect.Maps; - import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -15,6 +12,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.structure.BoundingBox; +import java.util.Map; + public class StructureWorld { private Map parts = Maps.newHashMap(); private ChunkPos lastPos; @@ -153,7 +152,7 @@ public class StructureWorld { blocks.forEach((pos, state) -> { int stateID = states.getOrDefault(states, -1); if (stateID < 0) { - stateID = id[0] ++; + stateID = id[0]++; states.put(state, stateID); stateMap.add(NbtUtils.writeBlockState(state)); } diff --git a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java index 14e6bba4..9e78a08c 100644 --- a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java +++ b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java @@ -1,7 +1,5 @@ package ru.bclib.world.surface; -import java.util.Random; - import net.minecraft.core.Registry; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; @@ -14,6 +12,8 @@ import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderBaseConf import ru.bclib.noise.OpenSimplexNoise; import ru.bclib.util.MHelper; +import java.util.Random; + public class DoubleBlockSurfaceBuilder extends SurfaceBuilder { private static final OpenSimplexNoise NOISE = new OpenSimplexNoise(4141); private SurfaceBuilderBaseConfiguration config1; @@ -43,7 +43,7 @@ public class DoubleBlockSurfaceBuilder extends SurfaceBuilder Date: Sat, 10 Jul 2021 16:18:05 +0300 Subject: [PATCH 0025/1033] Color provider mixin --- .../ru/bclib/mixin/client/MinecraftMixin.java | 46 +++++++++++++++++++ .../world/structures/BCLStructureFeature.java | 2 - src/main/resources/bclib.mixins.client.json | 5 +- src/main/resources/bclib.mixins.common.json | 2 +- 4 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 src/main/java/ru/bclib/mixin/client/MinecraftMixin.java diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java new file mode 100644 index 00000000..a497e0b6 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -0,0 +1,46 @@ +package ru.bclib.mixin.client; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.color.block.BlockColors; +import net.minecraft.client.color.item.ItemColors; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.WinScreen; +import net.minecraft.client.main.GameConfig; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.Registry; +import net.minecraft.sounds.Music; +import net.minecraft.sounds.Musics; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import ru.bclib.interfaces.IColorProvider; +import ru.bclib.util.MHelper; + +@Mixin(Minecraft.class) +public class MinecraftMixin { + @Final + @Shadow + private BlockColors blockColors; + + @Final + @Shadow + private ItemColors itemColors; + + @Inject(method = "*", at = @At("TAIL")) + private void bclib_onMCInit(GameConfig args, CallbackInfo info) { + Registry.BLOCK.forEach(block -> { + if (block instanceof IColorProvider) { + IColorProvider provider = (IColorProvider) block; + blockColors.register(provider.getProvider(), block); + itemColors.register(provider.getItemProvider(), block.asItem()); + } + }); + } +} diff --git a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java index 3db8e57b..d8655332 100644 --- a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java +++ b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java @@ -19,9 +19,7 @@ public class BCLStructureFeature { public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation) { this.featureStep = step; - this.structure = FabricStructureBuilder.create(id, structure).step(step).defaultConfig(spacing, separation, RANDOM.nextInt(8192)).register(); - this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); BuiltinRegistries.register(BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE, id, this.featureConfigured); FlatChunkGeneratorConfigAccessor.getStructureToFeatures().put(this.structure, this.featureConfigured); diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index f36a59e9..3e95d655 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -2,11 +2,12 @@ "required": true, "minVersion": "0.8", "package": "ru.bclib.mixin.client", - "compatibilityLevel": "JAVA_8", + "compatibilityLevel": "JAVA_16", "client": [ "EnchantingTableBlockMixin", "BackgroundRendererMixin", - "ModelBakeryMixin" + "ModelBakeryMixin", + "MinecraftMixin" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 20e03d8d..a357113d 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -2,7 +2,7 @@ "required": true, "minVersion": "0.8", "package": "ru.bclib.mixin.common", - "compatibilityLevel": "JAVA_8", + "compatibilityLevel": "JAVA_16", "mixins": [ "ComposterBlockAccessor", "PotionBrewingAccessor", From e41b59d506f6ca3188abf6ee25d6e4633de0c297 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 10 Jul 2021 19:47:33 +0300 Subject: [PATCH 0026/1033] Added resource loading for JSON --- src/main/java/ru/bclib/util/JsonFactory.java | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/ru/bclib/util/JsonFactory.java b/src/main/java/ru/bclib/util/JsonFactory.java index 72df3a38..09be9ac7 100644 --- a/src/main/java/ru/bclib/util/JsonFactory.java +++ b/src/main/java/ru/bclib/util/JsonFactory.java @@ -4,6 +4,10 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; import ru.bclib.BCLib; import java.io.File; @@ -43,6 +47,30 @@ public class JsonFactory { return new JsonObject(); } + /** + * Loads {@link JsonObject} from resource location using Minecraft resource manager. Can be used to load JSON from resourcepacks and resources. + * @param location {@link ResourceLocation} to JSON file + * @return {@link JsonObject} + */ + public static JsonObject getJsonObject(ResourceLocation location) { + ResourceManager manager = Minecraft.getInstance().getResourceManager(); + JsonObject obj = null; + try { + Resource resource = manager.getResource(location); + if (resource != null) { + InputStream stream = resource.getInputStream(); + InputStreamReader reader = new InputStreamReader(stream); + obj = JsonFactory.GSON.fromJson(reader, JsonObject.class); + reader.close(); + stream.close(); + } + } + catch (IOException ex) { + BCLib.LOGGER.catching(ex); + } + return obj == null ? new JsonObject() : obj; + } + public static JsonElement loadJson(File jsonFile) { if (jsonFile.exists()) { try (Reader reader = new FileReader(jsonFile)) { From 7d923ba04e4b4e65a55111919929224284eb529b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 10 Jul 2021 19:54:19 +0300 Subject: [PATCH 0027/1033] Small fixes --- src/main/java/ru/bclib/util/JsonFactory.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/ru/bclib/util/JsonFactory.java b/src/main/java/ru/bclib/util/JsonFactory.java index 09be9ac7..07ddc606 100644 --- a/src/main/java/ru/bclib/util/JsonFactory.java +++ b/src/main/java/ru/bclib/util/JsonFactory.java @@ -4,10 +4,13 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; +import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; import java.io.File; @@ -52,6 +55,8 @@ public class JsonFactory { * @param location {@link ResourceLocation} to JSON file * @return {@link JsonObject} */ + @Nullable + @Environment(EnvType.CLIENT) public static JsonObject getJsonObject(ResourceLocation location) { ResourceManager manager = Minecraft.getInstance().getResourceManager(); JsonObject obj = null; @@ -65,10 +70,8 @@ public class JsonFactory { stream.close(); } } - catch (IOException ex) { - BCLib.LOGGER.catching(ex); - } - return obj == null ? new JsonObject() : obj; + catch (IOException ex) {} + return obj; } public static JsonElement loadJson(File jsonFile) { From f1ccd563b5a17be51e8d8400cfd0347f0bb9a2ce Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 11 Jul 2021 00:04:37 +0300 Subject: [PATCH 0028/1033] Transformations --- .../bclib/mixin/client/FaceBakeryMixin.java | 28 +++++++++++++++++++ src/main/resources/bclib.mixins.client.json | 1 + 2 files changed, 29 insertions(+) create mode 100644 src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java diff --git a/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java new file mode 100644 index 00000000..25546a67 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java @@ -0,0 +1,28 @@ +package ru.bclib.mixin.client; + +import com.mojang.math.Matrix4f; +import com.mojang.math.Transformation; +import com.mojang.math.Vector3f; +import net.minecraft.client.renderer.block.model.FaceBakery; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(FaceBakery.class) +public class FaceBakeryMixin { + @Inject(method = "applyModelRotation", at = @At("HEAD"), cancellable = true) + public void bclib_applyModelTransforms(Vector3f vector3f, Transformation transformation, CallbackInfo info) { + if (transformation != Transformation.identity()) { + Vector3f scale = transformation.getScale(); + this.rotateVertexBy(vector3f, new Vector3f(0.5F, 0.5F, 0.5F), transformation.getMatrix(), new Vector3f(1.0F, 1.0F, 1.0F)); + vector3f.mul(scale.x(), scale.y(), scale.z()); + vector3f.add(transformation.getTranslation()); + info.cancel(); + } + } + + @Shadow + private void rotateVertexBy(Vector3f vector3f, Vector3f vector3f2, Matrix4f matrix4f, Vector3f vector3f3) {} +} diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 3e95d655..3174ac72 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -7,6 +7,7 @@ "EnchantingTableBlockMixin", "BackgroundRendererMixin", "ModelBakeryMixin", + "FaceBakeryMixin", "MinecraftMixin" ], "injectors": { From cb51137c87b521bb8fa8e53059235cd79103ac28 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 11 Jul 2021 00:41:29 +0300 Subject: [PATCH 0029/1033] Removed face bakery mixin --- .../bclib/mixin/client/FaceBakeryMixin.java | 28 ------------------- src/main/resources/bclib.mixins.client.json | 1 - 2 files changed, 29 deletions(-) delete mode 100644 src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java diff --git a/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java deleted file mode 100644 index 25546a67..00000000 --- a/src/main/java/ru/bclib/mixin/client/FaceBakeryMixin.java +++ /dev/null @@ -1,28 +0,0 @@ -package ru.bclib.mixin.client; - -import com.mojang.math.Matrix4f; -import com.mojang.math.Transformation; -import com.mojang.math.Vector3f; -import net.minecraft.client.renderer.block.model.FaceBakery; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(FaceBakery.class) -public class FaceBakeryMixin { - @Inject(method = "applyModelRotation", at = @At("HEAD"), cancellable = true) - public void bclib_applyModelTransforms(Vector3f vector3f, Transformation transformation, CallbackInfo info) { - if (transformation != Transformation.identity()) { - Vector3f scale = transformation.getScale(); - this.rotateVertexBy(vector3f, new Vector3f(0.5F, 0.5F, 0.5F), transformation.getMatrix(), new Vector3f(1.0F, 1.0F, 1.0F)); - vector3f.mul(scale.x(), scale.y(), scale.z()); - vector3f.add(transformation.getTranslation()); - info.cancel(); - } - } - - @Shadow - private void rotateVertexBy(Vector3f vector3f, Vector3f vector3f2, Matrix4f matrix4f, Vector3f vector3f3) {} -} diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 3174ac72..3e95d655 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -7,7 +7,6 @@ "EnchantingTableBlockMixin", "BackgroundRendererMixin", "ModelBakeryMixin", - "FaceBakeryMixin", "MinecraftMixin" ], "injectors": { From 992d7558010501f555b4ae86ea2e148b687e32c9 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 11 Jul 2021 01:25:11 +0300 Subject: [PATCH 0030/1033] Post init interface --- src/main/java/ru/bclib/client/BCLibClient.java | 6 ++++++ src/main/java/ru/bclib/interfaces/IPostInit.java | 5 +++++ src/main/java/ru/bclib/server/BCLibServer.java | 7 +++++++ 3 files changed, 18 insertions(+) create mode 100644 src/main/java/ru/bclib/interfaces/IPostInit.java diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index c281553e..5cb2d390 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -6,6 +6,7 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.interfaces.IPostInit; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.registry.BaseBlockEntityRenders; @@ -15,6 +16,11 @@ public class BCLibClient implements ClientModInitializer { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); registerRenderLayers(); + Registry.BLOCK.forEach(block -> { + if (block instanceof IPostInit) { + ((IPostInit) block).postInit(); + } + }); } private void registerRenderLayers() { diff --git a/src/main/java/ru/bclib/interfaces/IPostInit.java b/src/main/java/ru/bclib/interfaces/IPostInit.java new file mode 100644 index 00000000..341a6229 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/IPostInit.java @@ -0,0 +1,5 @@ +package ru.bclib.interfaces; + +public interface IPostInit { + void postInit(); +} diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index 2fbc8c0b..de5bf700 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -1,11 +1,18 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; +import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; +import ru.bclib.interfaces.IPostInit; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); + Registry.BLOCK.forEach(block -> { + if (block instanceof IPostInit) { + ((IPostInit) block).postInit(); + } + }); } } From cbff8625941a85a02ea34c1df5dd1889b29734d2 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 11 Jul 2021 01:32:07 +0300 Subject: [PATCH 0031/1033] Fog rendering skip --- .../ru/bclib/mixin/client/BackgroundRendererMixin.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index ec084197..c35fcd4b 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -63,6 +63,9 @@ public class BackgroundRendererMixin { Entity entity = camera.getEntity(); FogType fogType = camera.getFluidInCamera(); if (fogType != FogType.WATER) { + if (bcl_shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + return; + } float fog = bcl_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); BackgroundInfo.fogDensity = fog; float start = viewDistance * 0.75F / fog; @@ -96,6 +99,11 @@ public class BackgroundRendererMixin { } } + private static boolean bcl_shouldIgnore(Level level, int x, int y, int z) { + Biome biome = level.getBiome(BCL_MUT_POS.set(x, y, z)); + return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; + } + private static float bcl_getFogDensityI(Level level, int x, int y, int z) { Biome biome = level.getBiome(BCL_MUT_POS.set(x, y, z)); BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); From 8fca5aab41236e1ae29e6a7848a6178512b3426d Mon Sep 17 00:00:00 2001 From: Aleksey Date: Sun, 11 Jul 2021 14:32:13 +0300 Subject: [PATCH 0032/1033] Blockstates StringProperty --- build.gradle | 21 ++++---- .../blocks/properties/StringProperty.java | 52 +++++++++++++++++++ 2 files changed, 64 insertions(+), 9 deletions(-) create mode 100644 src/main/java/ru/bclib/blocks/properties/StringProperty.java diff --git a/build.gradle b/build.gradle index b0cead1a..9f747bfd 100644 --- a/build.gradle +++ b/build.gradle @@ -38,27 +38,30 @@ dependencies { def useOptional(String dep) { dependencies.modRuntime (dep) { - exclude group: "net.fabricmc.fabric-api" - exclude group: "net.fabricmc" + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' if (!dep.contains("me.shedaniel")) { - exclude group: "me.shedaniel" + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' } } dependencies.modCompileOnly (dep) { - exclude group: "net.fabricmc.fabric-api" - exclude group: "net.fabricmc" + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' if (!dep.contains("me.shedaniel")) { - exclude group: "me.shedaniel" + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' } } } def useApi(String dep) { dependencies.modApi (dep) { - exclude group: "net.fabricmc.fabric-api" - exclude group: "net.fabricmc" + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' if (!dep.contains("me.shedaniel")) { - exclude group: "me.shedaniel" + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' } } } diff --git a/src/main/java/ru/bclib/blocks/properties/StringProperty.java b/src/main/java/ru/bclib/blocks/properties/StringProperty.java new file mode 100644 index 00000000..1b86316e --- /dev/null +++ b/src/main/java/ru/bclib/blocks/properties/StringProperty.java @@ -0,0 +1,52 @@ +package ru.bclib.blocks.properties; + +import com.google.common.collect.Sets; +import net.minecraft.world.level.block.state.properties.Property; + +import java.util.*; + +public class StringProperty extends Property { + + private final Set values; + + public static StringProperty create(String name, String... values) { + return new StringProperty(name, values); + } + + protected StringProperty(String string, String... values) { + super(string, String.class); + this.values = Sets.newHashSet(values); + } + + @Override + public Collection getPossibleValues() { + return Collections.unmodifiableSet(values); + } + + @Override + public String getName(String comparable) { + return comparable; + } + + @Override + public Optional getValue(String string) { + if (values.contains(string)) { + return Optional.of(string); + } else { + return Optional.empty(); + } + } + + @Override + public int generateHashCode() { + return super.generateHashCode() + Objects.hashCode(values); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof StringProperty that)) return false; + if (!super.equals(o)) return false; + return values.equals(that.values); + } +} From f4a88c277b7a1bec6829e6836d57659c939c8ba4 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 11 Jul 2021 15:12:53 +0300 Subject: [PATCH 0033/1033] Add value operation --- src/main/java/ru/bclib/blocks/properties/StringProperty.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/blocks/properties/StringProperty.java b/src/main/java/ru/bclib/blocks/properties/StringProperty.java index 1b86316e..8345504e 100644 --- a/src/main/java/ru/bclib/blocks/properties/StringProperty.java +++ b/src/main/java/ru/bclib/blocks/properties/StringProperty.java @@ -6,7 +6,6 @@ import net.minecraft.world.level.block.state.properties.Property; import java.util.*; public class StringProperty extends Property { - private final Set values; public static StringProperty create(String name, String... values) { @@ -17,6 +16,10 @@ public class StringProperty extends Property { super(string, String.class); this.values = Sets.newHashSet(values); } + + public void addValue(String name) { + values.add(name); + } @Override public Collection getPossibleValues() { From 0a2b6d9977c562a502bf0a08259b1600b8b3f263 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 12 Jul 2021 10:03:13 +0300 Subject: [PATCH 0034/1033] Mining tags --- src/main/java/ru/bclib/api/TagAPI.java | 5 +++++ src/main/java/ru/bclib/blocks/properties/StringProperty.java | 1 + 2 files changed, 6 insertions(+) diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index e3491e2a..6ca55627 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -29,6 +29,11 @@ public class TagAPI { public static final Tag.Named DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); + public static final Tag.Named MINEABLE_AXE = getMCBlockTag("mineable/axe"); + public static final Tag.Named MINEABLE_PICKAXE = getMCBlockTag("mineable/pickaxe"); + public static final Tag.Named MINEABLE_SHOVEL = getMCBlockTag("mineable/shovel"); + public static final Tag.Named MINEABLE_HOE = getMCBlockTag("mineable/hoe"); + // Item Tags public static final Tag.Named ITEM_CHEST = makeCommonItemTag("chest"); public static final Tag.Named IRON_INGOTS = makeCommonItemTag("iron_ingots"); diff --git a/src/main/java/ru/bclib/blocks/properties/StringProperty.java b/src/main/java/ru/bclib/blocks/properties/StringProperty.java index 8345504e..8d7fc09b 100644 --- a/src/main/java/ru/bclib/blocks/properties/StringProperty.java +++ b/src/main/java/ru/bclib/blocks/properties/StringProperty.java @@ -5,6 +5,7 @@ import net.minecraft.world.level.block.state.properties.Property; import java.util.*; +@Deprecated public class StringProperty extends Property { private final Set values; From d8a620c589d51029d79698aae1e2a58f8f2190ee Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 12 Jul 2021 10:03:18 +0300 Subject: [PATCH 0035/1033] Mining tags --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 6a32f158..290c367c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.1 +mod_version = 0.2.2 maven_group = ru.bclib archives_base_name = bclib From bc4ff96f0b407c8d7ef4cc29c15cee0eed2baa22 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 14 Jul 2021 13:49:38 +0200 Subject: [PATCH 0036/1033] JavaDoc for `TagHelper` --- src/main/java/ru/bclib/util/TagHelper.java | 93 +++++++++++++++++++--- 1 file changed, 84 insertions(+), 9 deletions(-) diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java index 29126662..af0364aa 100644 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -1,21 +1,43 @@ package ru.bclib.util; +import java.util.Map; +import java.util.Set; + import com.google.common.collect.Maps; import com.google.common.collect.Sets; + import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import java.util.Map; -import java.util.Set; - +/** + * Utility functions to manage Minecraft Tags + */ public class TagHelper { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); - + + /** + * Adds one Tag to multiple Blocks. + * + * Example: + *
+	 * {@code
+	 * Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
+	 * TagHelper.addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);
+	 * }
+	 * 
+ * + * The call will reserve the Tag. The Tag is added to the blocks once + * {@link #apply(String, Map)} was executed. + * + * @param tag The new Tag + * @param blocks One or more blocks that should receive the Tag. + */ public static void addTag(Tag.Named tag, Block... blocks) { ResourceLocation tagID = tag.getName(); Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); @@ -26,7 +48,24 @@ public class TagHelper { } } } - + + /** + * Adds one Tag to multiple Items. + * + * Example: + *
+	 * {@code
+	 * Tag.Named METALS = makeBlockTag("mymod", "metals");
+	 * TagHelper.addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);
+	 * }
+	 * 
+ * + * The call will reserve the Tag. The Tag is added to the items once + * {@link #apply(String, Map)} was executed. + * + * @param tag The new Tag + * @param items One or more item that should receive the Tag. + */ public static void addTag(Tag.Named tag, ItemLike... items) { ResourceLocation tagID = tag.getName(); Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); @@ -37,26 +76,62 @@ public class TagHelper { } } } - + + /** + * Adds multiple Tags to one Item. + * + * The call will reserve the Tags. The Tags are added to the Item once + * * {@link #apply(String, Map)} was executed. + * + * @param item The Item that will receive all Tags + * @param tags One or more Tags + */ @SafeVarargs public static void addTags(ItemLike item, Tag.Named... tags) { for (Tag.Named tag : tags) { addTag(tag, item); } } - + + /** + * Adds multiple Tags to one Block. + * + * The call will reserve the Tags. The Tags are added to the Block once + * * {@link #apply(String, Map)} was executed. + * + * @param block The Block that will receive all Tags + * @param tags One or more Tags + */ @SafeVarargs public static void addTags(Block block, Tag.Named... tags) { for (Tag.Named tag : tags) { addTag(tag, block); } } - + + /** + * Adds all {@code ids} to the {@code builder}. + * @param builder + * @param ids + * + * @return The Builder passed as {@code builder}. + */ public static Tag.Builder apply(Tag.Builder builder, Set ids) { ids.forEach(value -> builder.addElement(value, "Better End Code")); return builder; } - + + /** + * Automatically called in {@link net.minecraft.tags.TagLoader#loadAndBuild(ResourceManager)}. + * + * In most cases there is no need to call this Method manually. + * + * @param directory The name of the Tag-directory. Should be either "tags/blocks" or + * "tags/items". + * @param tagsMap The map that will hold the registered Tags + * + * @return The {@code tagsMap} Parameter. + */ public static Map apply(String directory, Map tagsMap) { Map> endTags = null; if ("tags/blocks".equals(directory)) { From 1609b28595f5a46b02bfc3c41039b6793ac389f2 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 16 Jul 2021 15:04:42 +0300 Subject: [PATCH 0037/1033] Bonemeal API update and unification, sub-biome fix --- gradle.properties | 2 +- src/main/java/ru/bclib/api/BonemealAPI.java | 42 +++++++++----- .../mixin/client/BackgroundRendererMixin.java | 52 +++++++++--------- .../bclib/mixin/common/BoneMealItemMixin.java | 55 +++++++++++++------ .../common/FeatureDecoratorsAccessor.java | 2 +- .../mixin/common/MinecraftServerMixin.java | 12 ++-- .../mixin/common/RecipeManagerAccessor.java | 4 +- .../bclib/mixin/common/ServerLevelMixin.java | 8 +-- .../java/ru/bclib/world/biomes/BCLBiome.java | 5 +- 9 files changed, 109 insertions(+), 73 deletions(-) diff --git a/gradle.properties b/gradle.properties index 290c367c..e11b676a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.2 +mod_version = 0.2.3 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/api/BonemealAPI.java b/src/main/java/ru/bclib/api/BonemealAPI.java index 56276fd3..7de2e60a 100644 --- a/src/main/java/ru/bclib/api/BonemealAPI.java +++ b/src/main/java/ru/bclib/api/BonemealAPI.java @@ -15,38 +15,51 @@ public class BonemealAPI { private static final Map>> LAND_GRASS_BIOMES = Maps.newHashMap(); private static final Map> WATER_GRASS_TYPES = Maps.newHashMap(); private static final Map> LAND_GRASS_TYPES = Maps.newHashMap(); - private static final Set SPREADABLE_BLOCKS = Sets.newHashSet(); + private static final Map SPREADABLE_BLOCKS = Maps.newHashMap(); + private static final Set TERRAIN_TO_SPREAD = Sets.newHashSet(); + private static final Set TERRAIN = Sets.newHashSet(); - public static void addSpreadableBlock(Block block) { - SPREADABLE_BLOCKS.add(block); + public static void addSpreadableBlock(Block spreadableBlock, Block surfaceForSpread) { + SPREADABLE_BLOCKS.put(spreadableBlock, surfaceForSpread); + TERRAIN_TO_SPREAD.add(surfaceForSpread); + TERRAIN.add(surfaceForSpread); } - public static boolean isSpreadable(Block block) { - return SPREADABLE_BLOCKS.contains(block); + public static boolean isTerrain(Block block) { + return TERRAIN.contains(block); + } + + public static boolean isSpreadableTerrain(Block block) { + return TERRAIN_TO_SPREAD.contains(block); + } + + public static Block getSpreadable(Block block) { + return SPREADABLE_BLOCKS.get(block); } public static void addLandGrass(Block plant, Block... terrain) { for (Block block : terrain) { - addLandGrass(block, plant, 1F); + addLandGrass(plant, block, 1F); } } public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) { for (Block block : terrain) { - addLandGrass(biome, block, plant, 1F); + addLandGrass(biome, plant, block, 1F); } } - public static void addLandGrass(Block terrain, Block plant, float chance) { + public static void addLandGrass(Block plant, Block terrain, float chance) { WeightedList list = LAND_GRASS_TYPES.get(terrain); if (list == null) { list = new WeightedList(); LAND_GRASS_TYPES.put(terrain, list); } + TERRAIN.add(terrain); list.add(plant, chance); } - public static void addLandGrass(ResourceLocation biome, Block terrain, Block plant, float chance) { + public static void addLandGrass(ResourceLocation biome, Block plant, Block terrain, float chance) { Map> map = LAND_GRASS_BIOMES.get(biome); if (map == null) { map = Maps.newHashMap(); @@ -57,31 +70,33 @@ public class BonemealAPI { list = new WeightedList(); map.put(terrain, list); } + TERRAIN.add(terrain); list.add(plant, chance); } public static void addWaterGrass(Block plant, Block... terrain) { for (Block block : terrain) { - addWaterGrass(block, plant, 1F); + addWaterGrass(plant, block, 1F); } } public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) { for (Block block : terrain) { - addWaterGrass(biome, block, plant, 1F); + addWaterGrass(biome, plant, block, 1F); } } - public static void addWaterGrass(Block terrain, Block plant, float chance) { + public static void addWaterGrass(Block plant, Block terrain, float chance) { WeightedList list = WATER_GRASS_TYPES.get(terrain); if (list == null) { list = new WeightedList(); WATER_GRASS_TYPES.put(terrain, list); } + TERRAIN.add(terrain); list.add(plant, chance); } - public static void addWaterGrass(ResourceLocation biome, Block terrain, Block plant, float chance) { + public static void addWaterGrass(ResourceLocation biome, Block plant, Block terrain, float chance) { Map> map = WATER_GRASS_BIOMES.get(biome); if (map == null) { map = Maps.newHashMap(); @@ -92,6 +107,7 @@ public class BonemealAPI { list = new WeightedList(); map.put(terrain, list); } + TERRAIN.add(terrain); list.add(plant, chance); } diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index c35fcd4b..2fc492bd 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -25,9 +25,9 @@ import ru.bclib.world.biomes.BCLBiome; @Mixin(FogRenderer.class) public class BackgroundRendererMixin { - private static final MutableBlockPos BCL_LAST_POS = new MutableBlockPos(0, -100, 0); - private static final MutableBlockPos BCL_MUT_POS = new MutableBlockPos(); - private static final float[] BCL_FOG_DENSITY = new float[8]; + private static final MutableBlockPos BCLIB_LAST_POS = new MutableBlockPos(0, -100, 0); + private static final MutableBlockPos BCLIB_MUT_POS = new MutableBlockPos(); + private static final float[] BCLIB_FOG_DENSITY = new float[8]; @Shadow private static float fogRed; @@ -37,7 +37,7 @@ public class BackgroundRendererMixin { private static float fogBlue; @Inject(method = "setupColor", at = @At("RETURN")) - private static void bcl_onRender(Camera camera, float tickDelta, ClientLevel world, int i, float f, CallbackInfo info) { + private static void bclib_onRender(Camera camera, float tickDelta, ClientLevel world, int i, float f, CallbackInfo info) { FogType fogType = camera.getFluidInCamera(); if (fogType != FogType.WATER && world.dimension().equals(Level.END)) { Entity entity = camera.getEntity(); @@ -59,14 +59,14 @@ public class BackgroundRendererMixin { } @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) - private static void bcl_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { + private static void bclib_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { Entity entity = camera.getEntity(); FogType fogType = camera.getFluidInCamera(); if (fogType != FogType.WATER) { - if (bcl_shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + if (bclib_shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { return; } - float fog = bcl_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); + float fog = bclib_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); BackgroundInfo.fogDensity = fog; float start = viewDistance * 0.75F / fog; float end = viewDistance / fog; @@ -99,18 +99,18 @@ public class BackgroundRendererMixin { } } - private static boolean bcl_shouldIgnore(Level level, int x, int y, int z) { - Biome biome = level.getBiome(BCL_MUT_POS.set(x, y, z)); + private static boolean bclib_shouldIgnore(Level level, int x, int y, int z) { + Biome biome = level.getBiome(BCLIB_MUT_POS.set(x, y, z)); return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; } - private static float bcl_getFogDensityI(Level level, int x, int y, int z) { - Biome biome = level.getBiome(BCL_MUT_POS.set(x, y, z)); + private static float bclib_getFogDensityI(Level level, int x, int y, int z) { + Biome biome = level.getBiome(BCLIB_MUT_POS.set(x, y, z)); BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); return renderBiome.getFogDensity(); } - private static float bcl_getFogDensity(Level level, double x, double y, double z) { + private static float bclib_getFogDensity(Level level, double x, double y, double z) { int x1 = (MHelper.floor(x) >> 3) << 3; int y1 = (MHelper.floor(y) >> 3) << 3; int z1 = (MHelper.floor(z) >> 3) << 3; @@ -118,25 +118,25 @@ public class BackgroundRendererMixin { float dy = (float) (y - y1) / 8F; float dz = (float) (z - z1) / 8F; - if (BCL_LAST_POS.getX() != x1 || BCL_LAST_POS.getY() != y1 || BCL_LAST_POS.getZ() != z1) { + if (BCLIB_LAST_POS.getX() != x1 || BCLIB_LAST_POS.getY() != y1 || BCLIB_LAST_POS.getZ() != z1) { int x2 = x1 + 8; int y2 = y1 + 8; int z2 = z1 + 8; - BCL_LAST_POS.set(x1, y1, z1); - BCL_FOG_DENSITY[0] = bcl_getFogDensityI(level, x1, y1, z1); - BCL_FOG_DENSITY[1] = bcl_getFogDensityI(level, x2, y1, z1); - BCL_FOG_DENSITY[2] = bcl_getFogDensityI(level, x1, y2, z1); - BCL_FOG_DENSITY[3] = bcl_getFogDensityI(level, x2, y2, z1); - BCL_FOG_DENSITY[4] = bcl_getFogDensityI(level, x1, y1, z2); - BCL_FOG_DENSITY[5] = bcl_getFogDensityI(level, x2, y1, z2); - BCL_FOG_DENSITY[6] = bcl_getFogDensityI(level, x1, y2, z2); - BCL_FOG_DENSITY[7] = bcl_getFogDensityI(level, x2, y2, z2); + BCLIB_LAST_POS.set(x1, y1, z1); + BCLIB_FOG_DENSITY[0] = bclib_getFogDensityI(level, x1, y1, z1); + BCLIB_FOG_DENSITY[1] = bclib_getFogDensityI(level, x2, y1, z1); + BCLIB_FOG_DENSITY[2] = bclib_getFogDensityI(level, x1, y2, z1); + BCLIB_FOG_DENSITY[3] = bclib_getFogDensityI(level, x2, y2, z1); + BCLIB_FOG_DENSITY[4] = bclib_getFogDensityI(level, x1, y1, z2); + BCLIB_FOG_DENSITY[5] = bclib_getFogDensityI(level, x2, y1, z2); + BCLIB_FOG_DENSITY[6] = bclib_getFogDensityI(level, x1, y2, z2); + BCLIB_FOG_DENSITY[7] = bclib_getFogDensityI(level, x2, y2, z2); } - float a = Mth.lerp(dx, BCL_FOG_DENSITY[0], BCL_FOG_DENSITY[1]); - float b = Mth.lerp(dx, BCL_FOG_DENSITY[2], BCL_FOG_DENSITY[3]); - float c = Mth.lerp(dx, BCL_FOG_DENSITY[4], BCL_FOG_DENSITY[5]); - float d = Mth.lerp(dx, BCL_FOG_DENSITY[6], BCL_FOG_DENSITY[7]); + float a = Mth.lerp(dx, BCLIB_FOG_DENSITY[0], BCLIB_FOG_DENSITY[1]); + float b = Mth.lerp(dx, BCLIB_FOG_DENSITY[2], BCLIB_FOG_DENSITY[3]); + float c = Mth.lerp(dx, BCLIB_FOG_DENSITY[4], BCLIB_FOG_DENSITY[5]); + float d = Mth.lerp(dx, BCLIB_FOG_DENSITY[6], BCLIB_FOG_DENSITY[7]); a = Mth.lerp(dy, a, b); b = Mth.lerp(dy, c, d); diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index 2d3a06d0..fa3dd11e 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -11,6 +11,7 @@ import net.minecraft.world.level.biome.Biome.BiomeCategory; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.Property; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -21,6 +22,8 @@ import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; +import java.util.Collection; + @Mixin(BoneMealItem.class) public class BoneMealItemMixin { private static final MutableBlockPos bclib_BLOCK_POS = new MutableBlockPos(); @@ -31,24 +34,23 @@ public class BoneMealItemMixin { BlockPos blockPos = context.getClickedPos(); if (!world.isClientSide) { BlockPos offseted = blockPos.relative(context.getClickedFace()); - boolean endBiome = world.getBiome(offseted).getBiomeCategory() == BiomeCategory.THEEND; - - if (world.getBlockState(blockPos).is(TagAPI.END_GROUND)) { + if (BonemealAPI.isTerrain(world.getBlockState(blockPos).getBlock())) { boolean consume = false; - if (world.getBlockState(blockPos).is(Blocks.END_STONE)) { - BlockState nylium = bclib_getNylium(world, blockPos); - if (nylium != null) { - BlocksHelper.setWithoutUpdate(world, blockPos, nylium); + if (BonemealAPI.isSpreadableTerrain(world.getBlockState(blockPos).getBlock())) { + BlockState terrain = bclib_getSpreadable(world, blockPos); + if (terrain != null) { + BlocksHelper.setWithoutUpdate(world, blockPos, terrain); consume = true; } } else { - if (!world.getFluidState(offseted).isEmpty() && endBiome) { - if (world.getBlockState(offseted).getBlock().equals(Blocks.WATER)) { + BlockState state = world.getBlockState(offseted); + if (!state.getFluidState().isEmpty()) { + if (state.is(Blocks.WATER)) { consume = bclib_growWaterGrass(world, blockPos); } } - else { + else if (state.isAir()) { consume = bclib_growLandGrass(world, blockPos); } } @@ -61,12 +63,6 @@ public class BoneMealItemMixin { info.cancel(); } } - else if (!world.getFluidState(offseted).isEmpty() && endBiome) { - if (world.getBlockState(offseted).getBlock().equals(Blocks.WATER)) { - info.setReturnValue(InteractionResult.FAIL); - info.cancel(); - } - } } } @@ -134,15 +130,38 @@ public class BoneMealItemMixin { return block == null ? null : block.defaultBlockState(); } - private BlockState bclib_getNylium(Level world, BlockPos pos) { + private BlockState bclib_getSpreadable(Level world, BlockPos pos) { Vec3i[] offsets = MHelper.getOffsets(world.getRandom()); + BlockState center = world.getBlockState(pos); for (Vec3i dir : offsets) { BlockPos p = pos.offset(dir); BlockState state = world.getBlockState(p); - if (BonemealAPI.isSpreadable(state.getBlock())) { + Block terrain = BonemealAPI.getSpreadable(state.getBlock()); + if (center.is(terrain)) { + if (haveSameProperties(state, center)) { + for (Property property: center.getProperties()) { + state = state.setValue(property, center.getValue(property)); + } + } return state; } } return null; } + + private boolean haveSameProperties(BlockState state1, BlockState state2) { + Property[] properties1 = state1.getProperties().toArray(new Property[0]); + Property[] properties2 = state2.getProperties().toArray(new Property[0]); + if (properties1.length != properties2.length) { + return false; + } + for (int i = 0; i < properties1.length; i++) { + String name1 = properties1[i].getName(); + String name2 = properties2[i].getName(); + if (!name1.equals(name2)) { + return false; + } + } + return true; + } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java index ba18731a..5e6ed7ad 100644 --- a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java @@ -7,5 +7,5 @@ import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators") public interface FeatureDecoratorsAccessor { @Accessor("HEIGHTMAP_SQUARE") - ConfiguredDecorator bcl_getHeightmapSquare(); + ConfiguredDecorator bclib_getHeightmapSquare(); } diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index fe2b5897..d5876718 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -35,20 +35,20 @@ public class MinecraftServerMixin { protected WorldData worldData; @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) - private void bcl_reloadResources(Collection collection, CallbackInfoReturnable> info) { - bcl_injectRecipes(); + private void bclib_reloadResources(Collection collection, CallbackInfoReturnable> info) { + bclib_injectRecipes(); } @Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true) - private void bcl_loadLevel(CallbackInfo info) { - bcl_injectRecipes(); + private void bclib_loadLevel(CallbackInfo info) { + bclib_injectRecipes(); BiomeAPI.initRegistry(MinecraftServer.class.cast(this)); } - private void bcl_injectRecipes() { + private void bclib_injectRecipes() { if (FabricLoader.getInstance().isModLoaded("kubejs")) { RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); - accessor.bcl_setRecipes(BCLRecipeManager.getMap(accessor.bcl_getRecipes())); + accessor.bclib_setRecipes(BCLRecipeManager.getMap(accessor.bclib_getRecipes())); } } } diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java index c17bfdfd..3920b687 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java @@ -12,8 +12,8 @@ import java.util.Map; @Mixin(RecipeManager.class) public interface RecipeManagerAccessor { @Accessor("recipes") - Map, Map>> bcl_getRecipes(); + Map, Map>> bclib_getRecipes(); @Accessor("recipes") - void bcl_setRecipes(Map, Map>> recipes); + void bclib_setRecipes(Map, Map>> recipes); } \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 6a62af48..af47e301 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -27,21 +27,21 @@ import java.util.function.Supplier; @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level { - private static String bcl_lastWorld = null; + private static String bclib_lastWorld = null; protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(writableLevelData, resourceKey, dimensionType, supplier, bl, bl2, l); } @Inject(method = "*", at = @At("TAIL")) - private void bcl_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { + private void bclib_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { BiomeAPI.initRegistry(server); - if (bcl_lastWorld != null && bcl_lastWorld.equals(session.getLevelId())) { + if (bclib_lastWorld != null && bclib_lastWorld.equals(session.getLevelId())) { return; } - bcl_lastWorld = session.getLevelId(); + bclib_lastWorld = session.getLevelId(); ServerLevel world = ServerLevel.class.cast(this); File dir = session.getDimensionPath(world.dimension()); diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiome.java b/src/main/java/ru/bclib/world/biomes/BCLBiome.java index dcae78c1..7b021574 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiome.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiome.java @@ -47,6 +47,7 @@ public class BCLBiome { this.genChance = definition.getGenChance(); this.fogDensity = definition.getFodDensity(); this.customData = definition.getCustomData(); + subbiomes.add(this, 1); } public BCLBiome(ResourceLocation id, Biome biome, float fogDensity, float genChance) { @@ -56,6 +57,7 @@ public class BCLBiome { this.fogDensity = fogDensity; this.readStructureList(); this.customData = Maps.newHashMap(); + subbiomes.add(this, 1); } public BCLBiome getEdge() { @@ -85,8 +87,7 @@ public class BCLBiome { } public BCLBiome getSubBiome(Random random) { - BCLBiome biome = subbiomes.get(random); - return biome == null ? this : biome; + return subbiomes.get(random); } public BCLBiome getParentBiome() { From 036a94e171cbcf23b0c025ce8f6a2d15dec3e193 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 16 Jul 2021 15:35:01 +0300 Subject: [PATCH 0038/1033] Underwater plants fix --- src/main/java/ru/bclib/api/BonemealAPI.java | 6 +++--- .../java/ru/bclib/mixin/common/BoneMealItemMixin.java | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/ru/bclib/api/BonemealAPI.java b/src/main/java/ru/bclib/api/BonemealAPI.java index 7de2e60a..b6a5232e 100644 --- a/src/main/java/ru/bclib/api/BonemealAPI.java +++ b/src/main/java/ru/bclib/api/BonemealAPI.java @@ -127,16 +127,16 @@ public class BonemealAPI { } public static Block getWaterGrass(ResourceLocation biomeID, Block terrain, Random random) { - Map> map = LAND_GRASS_BIOMES.get(biomeID); + Map> map = WATER_GRASS_BIOMES.get(biomeID); WeightedList list = null; if (map != null) { list = map.get(terrain); if (list == null) { - list = LAND_GRASS_TYPES.get(terrain); + list = WATER_GRASS_TYPES.get(terrain); } } else { - list = LAND_GRASS_TYPES.get(terrain); + list = WATER_GRASS_TYPES.get(terrain); } return list == null ? null : list.get(random); } diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index fa3dd11e..cd84cb8a 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -44,13 +44,13 @@ public class BoneMealItemMixin { } } else { - BlockState state = world.getBlockState(offseted); - if (!state.getFluidState().isEmpty()) { - if (state.is(Blocks.WATER)) { + BlockState stateAbove = world.getBlockState(blockPos.above()); + if (!stateAbove.getFluidState().isEmpty()) { + if (stateAbove.is(Blocks.WATER)) { consume = bclib_growWaterGrass(world, blockPos); } } - else if (state.isAir()) { + else if (stateAbove.isAir()) { consume = bclib_growLandGrass(world, blockPos); } } @@ -126,7 +126,7 @@ public class BoneMealItemMixin { private BlockState bclib_getWaterGrassState(Level world, BlockPos pos) { BlockState state = world.getBlockState(pos); Block block = state.getBlock(); - block = BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); + block = BonemealAPI.getWaterGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); return block == null ? null : block.defaultBlockState(); } From 5b9eb304bc461f06aee241f3666619e6fdc3c1de Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Sat, 17 Jul 2021 10:27:21 +0200 Subject: [PATCH 0039/1033] Custom Stylesheet --- build.gradle | 1 + javadoc.css | 903 +++++++++++++++++++++ src/main/java/ru/bclib/api/TagAPI.java | 4 +- src/main/java/ru/bclib/util/TagHelper.java | 16 +- 4 files changed, 910 insertions(+), 14 deletions(-) create mode 100644 javadoc.css diff --git a/build.gradle b/build.gradle index 9f747bfd..ed0bc1c0 100644 --- a/build.gradle +++ b/build.gradle @@ -89,6 +89,7 @@ tasks.withType(JavaCompile) { javadoc { options.tags = [ "reason" ] + options.stylesheetFile = new File(projectDir, "javadoc.css"); } task javadocJar(type: Jar, dependsOn: javadoc) { diff --git a/javadoc.css b/javadoc.css new file mode 100644 index 00000000..922bc6bb --- /dev/null +++ b/javadoc.css @@ -0,0 +1,903 @@ +/* + * Javadoc style sheet + */ + +@import url("resources/fonts/dejavu.css"); + +/* + * Styles for individual HTML elements. + * + * These are styles that are specific to individual HTML elements. Changing them affects the style of a particular + * HTML element throughout the page. + */ + +body { + background-color: #ffffff; + color: #353833; + font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; + font-size: 14px; + margin: 0; + padding: 0; + height: 100%; + width: 100%; +} +iframe { + margin: 0; + padding: 0; + height: 100%; + width: 100%; + overflow-y: scroll; + border: none; +} +a:link, +a:visited { + text-decoration: none; + color: #4a6782; +} +a[href]:hover, +a[href]:focus { + text-decoration: none; + color: #bb7a2a; +} +a[name] { + color: #353833; +} +pre { + font-family: "DejaVu Sans Mono", monospace; + font-size: 16px; + background-color: #fffadb; + border-radius: 5px; +} +h1 { + font-size: 20px; +} +h2 { + font-size: 18px; +} +h3 { + font-size: 16px; +} +h4 { + font-size: 13px; +} +h5 { + font-size: 12px; +} +h6 { + font-size: 11px; +} +ul { + list-style-type: disc; +} +code, +tt { + font-family: "DejaVu Sans Mono", monospace; + font-size: 14px; + padding-top: 4px; + margin-top: 8px; + line-height: 1.4em; +} +dt code { + font-family: "DejaVu Sans Mono", monospace; + font-size: 14px; + padding-top: 4px; +} +.summary-table dt code { + font-family: "DejaVu Sans Mono", monospace; + font-size: 14px; + vertical-align: top; + padding-top: 4px; +} +sup { + font-size: 8px; +} +button { + font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; + font-size: 14px; +} +/* + * Styles for HTML generated by javadoc. + * + * These are style classes that are used by the standard doclet to generate HTML documentation. + */ + +/* + * Styles for document title and copyright. + */ +.clear { + clear: both; + height: 0; + overflow: hidden; +} +.about-language { + float: right; + padding: 0 21px 8px 8px; + font-size: 11px; + margin-top: -9px; + height: 2.9em; +} +.legal-copy { + margin-left: 0.5em; +} +.tab { + background-color: #0066ff; + color: #ffffff; + padding: 8px; + width: 5em; + font-weight: bold; +} +/* + * Styles for navigation bar. + */ +@media screen { + .flex-box { + position: fixed; + display: flex; + flex-direction: column; + height: 100%; + width: 100%; + } + .flex-header { + flex: 0 0 auto; + } + .flex-content { + flex: 1 1 auto; + overflow-y: auto; + } +} +.top-nav { + background-color: #4d7a97; + color: #ffffff; + float: left; + padding: 0; + width: 100%; + clear: right; + min-height: 2.8em; + padding-top: 10px; + overflow: hidden; + font-size: 12px; +} +.sub-nav { + background-color: #dee3e9; + float: left; + width: 100%; + overflow: hidden; + font-size: 12px; +} +.sub-nav div { + clear: left; + float: left; + padding: 0 0 5px 6px; + text-transform: uppercase; +} +.sub-nav .nav-list { + padding-top: 5px; +} +ul.nav-list { + display: block; + margin: 0 25px 0 0; + padding: 0; +} +ul.sub-nav-list { + float: left; + margin: 0 25px 0 0; + padding: 0; +} +ul.nav-list li { + list-style: none; + float: left; + padding: 5px 6px; + text-transform: uppercase; +} +.sub-nav .nav-list-search { + float: right; + margin: 0 0 0 0; + padding: 5px 6px; + clear: none; +} +.nav-list-search label { + position: relative; + right: -16px; +} +ul.sub-nav-list li { + list-style: none; + float: left; + padding-top: 10px; +} +.top-nav a:link, +.top-nav a:active, +.top-nav a:visited { + color: #ffffff; + text-decoration: none; + text-transform: uppercase; +} +.top-nav a:hover { + text-decoration: none; + color: #bb7a2a; + text-transform: uppercase; +} +.nav-bar-cell1-rev { + background-color: #f8981d; + color: #253441; + margin: auto 5px; +} +.skip-nav { + position: absolute; + top: auto; + left: -9999px; + overflow: hidden; +} +/* + * Hide navigation links and search box in print layout + */ +@media print { + ul.nav-list, + div.sub-nav { + display: none; + } +} +/* + * Styles for page header and footer. + */ +.title { + color: #2c4557; + margin: 10px 0; +} +.sub-title { + margin: 5px 0 0 0; +} +.header ul { + margin: 0 0 15px 0; + padding: 0; +} +.header ul li, +.footer ul li { + list-style: none; + font-size: 13px; +} +/* + * Styles for headings. + */ +body.class-declaration-page .summary h2, +body.class-declaration-page .details h2, +body.class-use-page h2, +body.module-declaration-page .block-list h2 { + font-style: italic; + padding: 0; + margin: 15px 0; +} +body.class-declaration-page .summary h3, +body.class-declaration-page .details h3, +body.class-declaration-page .summary .inherited-list h2 { + background-color: #dee3e9; + border: 1px solid #d0d9e0; + margin: 0 0 6px -8px; + padding: 7px 5px; +} +/* + * Styles for page layout containers. + */ +main { + clear: both; + padding: 10px 20px; + position: relative; +} +dl.notes > dt { + font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; + font-size: 12px; + font-weight: bold; + margin: 10px 0 0 0; + color: #4e4e4e; +} +dl.notes > dd { + margin: 5px 0 10px 0; + font-size: 15px; + font-family: "Roboto", "DejaVu Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; +} +dl.name-value > dt { + margin-left: 1px; + font-size: 1.1em; + display: inline; + font-weight: bold; +} +dl.name-value > dd { + margin: 0 0 0 1px; + font-size: 1.1em; + display: inline; +} +/* + * Styles for lists. + */ +li.circle { + list-style: circle; +} +ul.horizontal li { + display: inline; + font-size: 0.9em; +} +div.inheritance { + margin: 0; + padding: 0; +} +div.inheritance div.inheritance { + margin-left: 2em; +} +ul.block-list, +ul.details-list, +ul.member-list, +ul.summary-list { + margin: 10px 0 10px 0; + padding: 0; +} +ul.block-list > li, +ul.details-list > li, +ul.member-list > li, +ul.summary-list > li { + list-style: none; + margin-bottom: 15px; + line-height: 1.4; +} +.summary-table dl, +.summary-table dl dt, +.summary-table dl dd { + margin-top: 0; + margin-bottom: 1px; +} +/* + * Styles for tables. + */ +.summary-table { + width: 100%; + border-spacing: 0; + border-left: 1px solid #eee; + border-right: 1px solid #eee; + border-bottom: 1px solid #eee; +} +.summary-table { + padding: 0; +} +.caption { + position: relative; + text-align: left; + background-repeat: no-repeat; + color: #253441; + font-weight: bold; + clear: none; + overflow: hidden; + padding: 0px; + padding-top: 10px; + padding-left: 1px; + margin: 0px; + white-space: pre; +} +.caption a:link, +.caption a:visited { + color: #1f389c; +} +.caption a:hover, +.caption a:active { + color: #ffffff; +} +.caption span { + white-space: nowrap; + padding-top: 5px; + padding-left: 12px; + padding-right: 12px; + padding-bottom: 7px; + display: inline-block; + float: left; + background-color: #f8981d; + border: none; + height: 16px; +} + +div.table-tabs > button { + border: none; + cursor: pointer; + padding: 5px 12px 7px 12px; + font-weight: bold; + margin-right: 3px; +} +div.table-tabs > button.active-table-tab { + background: #f8981d; + color: #253441; +} +div.table-tabs > button.table-tab { + background: #4d7a97; + color: #ffffff; +} +.two-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(15%, auto); +} +.three-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(15%, max-content) minmax(15%, auto); +} +.four-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(10%, max-content) minmax(10%, max-content) minmax(10%, auto); +} +@media screen and (max-width: 600px) { + .two-column-summary { + display: grid; + grid-template-columns: 1fr; + } +} +@media screen and (max-width: 800px) { + .three-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(25%, auto); + } + .three-column-summary .col-last { + grid-column-end: span 2; + } +} +@media screen and (max-width: 1000px) { + .four-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(15%, auto); + } +} +.summary-table > div { + text-align: left; + padding: 8px 3px 3px 7px; +} +.col-first, +.col-second, +.col-last, +.col-constructor-name, +.col-deprecated-item-name { + vertical-align: top; + padding-right: 0; + padding-top: 8px; + padding-bottom: 3px; +} +.table-header { + background: #dee3e9; + font-weight: bold; +} +.col-first, +.col-first { + font-size: 13px; +} +.col-second, +.col-second, +.col-last, +.col-constructor-name, +.col-deprecated-item-name, +.col-last { + font-size: 13px; +} +.col-first, +.col-second, +.col-constructor-name { + vertical-align: top; + overflow: auto; +} +.col-last { + white-space: normal; +} +.col-first a:link, +.col-first a:visited, +.col-second a:link, +.col-second a:visited, +.col-first a:link, +.col-first a:visited, +.col-second a:link, +.col-second a:visited, +.col-constructor-name a:link, +.col-constructor-name a:visited, +.col-deprecated-item-name a:link, +.col-deprecated-item-name a:visited, +.constant-values-container a:link, +.constant-values-container a:visited, +.all-classes-container a:link, +.all-classes-container a:visited, +.all-packages-container a:link, +.all-packages-container a:visited { + font-weight: bold; +} +.table-sub-heading-color { + background-color: #eeeeff; +} +.even-row-color, +.even-row-color .table-header { + background-color: #ffffff; +} +.odd-row-color, +.odd-row-color .table-header { + background-color: #eeeeef; +} +/* + * Styles for contents. + */ +.deprecated-content { + margin: 0; + padding: 10px 0; +} +div.block { + font-size: 15px; + font-family: "Roboto", "DejaVu Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; +} +.col-last div { + padding-top: 0; +} +.col-last a { + padding-bottom: 3px; +} +.module-signature, +.package-signature, +.type-signature, +.member-signature { + font-family: "DejaVu Sans Mono", monospace; + font-size: 14px; + margin: 14px 0; + white-space: pre-wrap; +} +.module-signature, +.package-signature, +.type-signature { + margin-top: 0; +} +.member-signature .type-parameters-long, +.member-signature .parameters, +.member-signature .exceptions { + display: inline-block; + vertical-align: top; + white-space: pre; +} +.member-signature .type-parameters { + white-space: normal; +} +/* + * Styles for formatting effect. + */ +.source-line-no { + color: green; + padding: 0 30px 0 0; +} +h1.hidden { + visibility: hidden; + overflow: hidden; + font-size: 10px; +} +.block { + display: block; + margin: 0 10px 5px 0; + color: #474747; +} +.deprecated-label, +.descfrm-type-label, +.implementation-label, +.member-name-label, +.member-name-link, +.module-label-in-package, +.module-label-in-type, +.override-specify-label, +.package-label-in-type, +.package-hierarchy-label, +.type-name-label, +.type-name-link, +.search-tag-link { + font-weight: bold; +} +.deprecation-comment, +.help-footnote, +.interface-name { + font-style: italic; +} +.deprecation-block { + font-size: 14px; + font-family: "DejaVu Serif", Georgia, "Times New Roman", Times, serif; + border-style: solid; + border-width: thin; + border-radius: 10px; + padding: 10px; + margin-bottom: 10px; + margin-right: 10px; + display: inline-block; +} +div.block div.deprecation-comment, +div.block div.block span.emphasized-phrase, +div.block div.block span.interface-name { + font-style: normal; +} +/* + * Styles specific to HTML5 elements. + */ +main, +nav, +header, +footer, +section { + display: block; +} +/* + * Styles for javadoc search. + */ +.ui-autocomplete-category { + font-weight: bold; + font-size: 15px; + padding: 7px 0 7px 3px; + background-color: #4d7a97; + color: #ffffff; +} +.result-item { + font-size: 13px; +} +.ui-autocomplete { + max-height: 85%; + max-width: 65%; + overflow-y: scroll; + overflow-x: scroll; + white-space: nowrap; + box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23); +} +ul.ui-autocomplete { + position: fixed; + z-index: 999999; +} +ul.ui-autocomplete li { + float: left; + clear: both; + width: 100%; +} +.result-highlight { + font-weight: bold; +} +#search { + background-image: url("resources/glass.png"); + background-size: 13px; + background-repeat: no-repeat; + background-position: 2px 3px; + padding-left: 20px; + position: relative; + right: -18px; + width: 400px; +} +#reset { + background-color: rgb(255, 255, 255); + background-image: url("resources/x.png"); + background-position: center; + background-repeat: no-repeat; + background-size: 12px; + border: 0 none; + width: 16px; + height: 16px; + position: relative; + left: -4px; + top: -4px; + font-size: 0px; +} +.watermark { + color: #545454; +} +.search-tag-desc-result { + font-style: italic; + font-size: 11px; +} +.search-tag-holder-result { + font-style: italic; + font-size: 12px; +} +.search-tag-result:target { + background-color: yellow; +} +.module-graph span { + display: none; + position: absolute; +} +.module-graph:hover span { + display: block; + margin: -100px 0 0 100px; + z-index: 1; +} +.inherited-list { + margin: 10px 0 10px 0; +} +section.description { + line-height: 1.4; +} +.summary section[class$="-summary"], +.details section[class$="-details"], +.class-uses .detail, +.serialized-class-details { + padding: 0px 20px 5px 10px; + border: 1px solid #ededed; + background-color: #f8f8f8; +} +.inherited-list, +section[class$="-details"] .detail { + padding: 0 0 5px 8px; + background-color: #ffffff; + border: none; +} +.vertical-separator { + padding: 0 5px; +} +ul.help-section-list { + margin: 0; +} +/* + * Indicator icon for external links. + */ +main a[href*="://"]::after +{ + content: ""; + display: inline-block; + background-image: url('data:image/svg+xml; utf8, \ + \ + \ + '); + background-size: 100% 100%; + width: 7px; + height: 7px; + margin-left: 2px; + margin-bottom: 4px; +} +main a[href*="://"]:hover::after, +main a[href*="://"]:focus::after +{ + background-image: url('data:image/svg+xml; utf8, \ + \ + \ + '); +} + +/* + * Styles for user-provided tables. + * + * borderless: + * No borders, vertical margins, styled caption. + * This style is provided for use with existing doc comments. + * In general, borderless tables should not be used for layout purposes. + * + * plain: + * Plain borders around table and cells, vertical margins, styled caption. + * Best for small tables or for complex tables for tables with cells that span + * rows and columns, when the "striped" style does not work well. + * + * striped: + * Borders around the table and vertical borders between cells, striped rows, + * vertical margins, styled caption. + * Best for tables that have a header row, and a body containing a series of simple rows. + */ + +table.borderless, +table.plain, +table.striped { + margin-top: 10px; + margin-bottom: 10px; +} +table.borderless > caption, +table.plain > caption, +table.striped > caption { + font-weight: bold; + font-size: smaller; +} +table.borderless th, +table.borderless td, +table.plain th, +table.plain td, +table.striped th, +table.striped td { + padding: 2px 5px; +} +table.borderless, +table.borderless > thead > tr > th, +table.borderless > tbody > tr > th, +table.borderless > tr > th, +table.borderless > thead > tr > td, +table.borderless > tbody > tr > td, +table.borderless > tr > td { + border: none; +} +table.borderless > thead > tr, +table.borderless > tbody > tr, +table.borderless > tr { + background-color: transparent; +} +table.plain { + border-collapse: collapse; + border: 1px solid black; +} +table.plain > thead > tr, +table.plain > tbody tr, +table.plain > tr { + background-color: transparent; +} +table.plain > thead > tr > th, +table.plain > tbody > tr > th, +table.plain > tr > th, +table.plain > thead > tr > td, +table.plain > tbody > tr > td, +table.plain > tr > td { + border: 1px solid black; +} +table.striped { + border-collapse: collapse; + border: 1px solid black; +} +table.striped > thead { + background-color: #e3e3e3; +} +table.striped > thead > tr > th, +table.striped > thead > tr > td { + border: 1px solid black; +} +table.striped > tbody > tr:nth-child(even) { + background-color: #eee; +} +table.striped > tbody > tr:nth-child(odd) { + background-color: #fff; +} +table.striped > tbody > tr > th, +table.striped > tbody > tr > td { + border-left: 1px solid black; + border-right: 1px solid black; +} +table.striped > tbody > tr > th { + font-weight: normal; +} +/** + * Tweak font sizes and paddings for small screens. + */ +@media screen and (max-width: 1050px) { + #search { + width: 300px; + } +} +@media screen and (max-width: 800px) { + #search { + width: 200px; + } + .top-nav, + .bottom-nav { + font-size: 11px; + padding-top: 6px; + } + .sub-nav { + font-size: 11px; + } + .about-language { + padding-right: 16px; + } + ul.nav-list li, + .sub-nav .nav-list-search { + padding: 6px; + } + ul.sub-nav-list li { + padding-top: 5px; + } + main { + padding: 10px; + } + .summary section[class$="-summary"], + .details section[class$="-details"], + .class-uses .detail, + .serialized-class-details { + padding: 0 8px 5px 8px; + } + body { + -webkit-text-size-adjust: none; + } +} +@media screen and (max-width: 500px) { + #search { + width: 150px; + } + .top-nav, + .bottom-nav { + font-size: 10px; + } + .sub-nav { + font-size: 10px; + } + .about-language { + font-size: 10px; + padding-right: 12px; + } +} diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 6ca55627..127a6aea 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,5 +1,7 @@ package ru.bclib.api; +import java.util.function.Supplier; + import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -14,8 +16,6 @@ import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; import ru.bclib.util.TagHelper; -import java.util.function.Supplier; - public class TagAPI { // Block Tags public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java index af0364aa..9caf94a4 100644 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -25,12 +25,8 @@ public class TagHelper { * Adds one Tag to multiple Blocks. * * Example: - *
-	 * {@code
-	 * Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
-	 * TagHelper.addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);
-	 * }
-	 * 
+ *
{@code  Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
+	 * TagHelper.addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);}
* * The call will reserve the Tag. The Tag is added to the blocks once * {@link #apply(String, Map)} was executed. @@ -53,12 +49,8 @@ public class TagHelper { * Adds one Tag to multiple Items. * * Example: - *
-	 * {@code
-	 * Tag.Named METALS = makeBlockTag("mymod", "metals");
-	 * TagHelper.addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);
-	 * }
-	 * 
+ *
{@code  Tag.Named METALS = makeBlockTag("mymod", "metals");
+	 * TagHelper.addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);}
* * The call will reserve the Tag. The Tag is added to the items once * {@link #apply(String, Map)} was executed. From f7955e60f0765b75a09f24cff731abb8f1ad919f Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Sat, 17 Jul 2021 15:12:23 +0200 Subject: [PATCH 0040/1033] Propsal for property augmentation --- src/main/java/ru/bclib/blocks/BaseBlock.java | 52 +++++++++++++++++-- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 34 ++++++++++-- 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index bfb52a10..e9e663bd 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -1,29 +1,71 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import ru.bclib.client.models.BlockModelProvider; -import java.util.Collections; -import java.util.List; - +/** + * Base class for a default Block. + * + * This Block-Type will: + *
    + *
  • Drop itself
  • + *
  • Automatically create an Item-Model from the Block-Model
  • + *
+ */ public class BaseBlock extends Block implements BlockModelProvider { + /** + * Creates a new Block with the passed properties + * @param settings The properties of the Block. + */ public BaseBlock(Properties settings) { super(settings); } - + + /** + * {@inheritDoc} + * + * This implementation will drop the Block itself + */ @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + + /** + * {@inheritDoc} + * + * This implementation will load the Block-Model and return it as the Item-Model + */ @Override public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } + + /** + * This method is used internally. + * + * It is called from Block-Contructors, to allow the augmentation of the blocks + * preset properties. + * + * For example in {@link BaseLeavesBlock#BaseLeavesBlock(Block, MaterialColor, Consumer)} + * @param customizeProperties A {@link Consumer} to call with the preset properties + * @param settings The properties as created by the Block + * @return The reconfigured {@code settings} + */ + static FabricBlockSettings acceptAndReturn(Consumer customizeProperties, FabricBlockSettings settings){ + customizeProperties.accept(settings); + return settings; + } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index e77d96c5..c6386ef7 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,6 +1,11 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; @@ -20,19 +25,38 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.MHelper; -import java.util.Collections; -import java.util.List; - public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { private final Block sapling; + + private static FabricBlockSettings makeLeaves(MaterialColor color){ + return FabricBlockSettings + .copyOf(Blocks.OAK_LEAVES) + .mapColor(color) + .breakByTool(FabricToolTags.HOES) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .allowsSpawning((state, world, pos, type) -> false) + .suffocates((state, world, pos) -> false) + .blockVision((state, world, pos) -> false); + } + + public BaseLeavesBlock(Block sapling, MaterialColor color, Consumer customizeProperties) { + super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); + this.sapling = sapling; + } + + public BaseLeavesBlock(Block sapling, MaterialColor color, int light, Consumer customizeProperties) { + super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).luminance(light))); + this.sapling = sapling; + } public BaseLeavesBlock(Block sapling, MaterialColor color) { - super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).breakByHand(true).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); + super(makeLeaves(color)); this.sapling = sapling; } public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { - super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).luminance(light).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); + super(makeLeaves(color).lightLevel(light)); this.sapling = sapling; } From 940dd39e29e1d83d49ceef1bff2a6155e3e6870d Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 14:28:57 +0300 Subject: [PATCH 0041/1033] Test shaders --- .../shaders/core/rendertype_solid.fsh | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh new file mode 100644 index 00000000..f6499103 --- /dev/null +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh @@ -0,0 +1,25 @@ +#version 150 +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec2 texCoord0; + +out vec4 fragColor; + +void main() { + vec4 tex = texture(Sampler0, texCoord0); + vec4 color = tex * ColorModulator; + if (tex.a > 0.9) { + color = color * vertexColor; + } + color.a = 1.0; + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} From 201df3746a4dc115d695acfa2b1f4be69652a9a8 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 17:00:46 +0300 Subject: [PATCH 0042/1033] Emissive textures support --- .../bclib/mixin/client/TextureAtlasMixin.java | 78 +++++++++++++++++++ src/main/resources/bclib.mixins.client.json | 1 + 2 files changed, 79 insertions(+) create mode 100644 src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java new file mode 100644 index 00000000..375fcf18 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java @@ -0,0 +1,78 @@ +package ru.bclib.mixin.client; + +import com.mojang.blaze3d.platform.NativeImage; +import net.fabricmc.fabric.impl.client.texture.FabricSprite; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import ru.bclib.BCLib; + +import java.io.IOException; + +@Mixin(TextureAtlas.class) +public class TextureAtlasMixin { + private boolean bclib_modifyAtlas; + + @Inject(method = "*", at = @At("TAIL")) + private void bclib_onAtlasInit(ResourceLocation resourceLocation, CallbackInfo info) { + bclib_modifyAtlas = resourceLocation.toString().equals("minecraft:textures/atlas/blocks.png"); + } + + @Inject( + method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite$Info;IIIII)Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;", + at = @At("HEAD"), + cancellable = true + ) + private void bclib_loadSprite(ResourceManager resourceManager, TextureAtlasSprite.Info spriteInfo, int atlasWidth, int atlasHeight, int maxLevel, int posX, int posY, CallbackInfoReturnable info) { + ResourceLocation location = spriteInfo.name(); + if (bclib_modifyAtlas && location.getPath().startsWith("block")) { + ResourceLocation emissiveLocation = new ResourceLocation(location.getNamespace(), "textures/" + location.getPath() + "_e.png"); + if (resourceManager.hasResource(emissiveLocation)) { + NativeImage sprite = null; + NativeImage emission = null; + try { + ResourceLocation spriteLocation = new ResourceLocation(location.getNamespace(), "textures/" + location.getPath() + ".png"); + Resource resource = resourceManager.getResource(spriteLocation); + sprite = NativeImage.read(resource.getInputStream()); + resource.close(); + + resource = resourceManager.getResource(emissiveLocation); + emission = NativeImage.read(resource.getInputStream()); + resource.close(); + } + catch (IOException e) { + BCLib.LOGGER.warning(e.getMessage()); + } + if (sprite != null && emission != null) { + int width = Math.min(sprite.getWidth(), emission.getWidth()); + int height = Math.min(sprite.getHeight(), emission.getHeight()); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + int argb = emission.getPixelRGBA(x, y); + int alpha = (argb >> 24) & 255; + if (alpha > 127) { + int r = (argb >> 16) & 255; + int g = (argb >> 8) & 255; + int b = argb & 255; + if (r > 0 || g > 0 || b > 0) { + argb = (argb & 0x00FFFFFF) | (200 << 24); + sprite.setPixelRGBA(x, y, argb); + } + } + } + } + TextureAtlas self = (TextureAtlas) (Object) this; + FabricSprite result = new FabricSprite(self, spriteInfo, maxLevel, atlasWidth, atlasHeight, posX, posY, sprite); + info.setReturnValue(result); + } + } + } + } +} diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 3e95d655..689cb36b 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -6,6 +6,7 @@ "client": [ "EnchantingTableBlockMixin", "BackgroundRendererMixin", + "TextureAtlasMixin", "ModelBakeryMixin", "MinecraftMixin" ], From 71935a746a25aedc442d5da15e4f31d669c12132 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 17:29:23 +0300 Subject: [PATCH 0043/1033] Cutout emission --- .../bclib/mixin/client/TextureAtlasMixin.java | 2 +- .../shaders/core/rendertype_cutout.fsh | 28 +++++++++++++++++++ .../shaders/core/rendertype_cutout_mipped.fsh | 28 +++++++++++++++++++ .../shaders/core/rendertype_solid.fsh | 2 +- 4 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh create mode 100644 src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java index 375fcf18..fbe102ac 100644 --- a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java +++ b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java @@ -62,7 +62,7 @@ public class TextureAtlasMixin { int g = (argb >> 8) & 255; int b = argb & 255; if (r > 0 || g > 0 || b > 0) { - argb = (argb & 0x00FFFFFF) | (200 << 24); + argb = (argb & 0x00FFFFFF) | (250 << 24); sprite.setPixelRGBA(x, y, argb); } } diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh new file mode 100644 index 00000000..441b8209 --- /dev/null +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh @@ -0,0 +1,28 @@ +#version 150 +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec2 texCoord0; + +out vec4 fragColor; + +void main() { + vec4 tex = texture(Sampler0, texCoord0); + if (tex.a < 0.1) { + discard; + } + vec4 color = tex * ColorModulator; + if (tex.a > 0.99) { + color = color * vertexColor; + } + color.a = 1.0; + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh new file mode 100644 index 00000000..441b8209 --- /dev/null +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh @@ -0,0 +1,28 @@ +#version 150 +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec2 texCoord0; + +out vec4 fragColor; + +void main() { + vec4 tex = texture(Sampler0, texCoord0); + if (tex.a < 0.1) { + discard; + } + vec4 color = tex * ColorModulator; + if (tex.a > 0.99) { + color = color * vertexColor; + } + color.a = 1.0; + fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); +} diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh index f6499103..c01d103d 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh @@ -17,7 +17,7 @@ out vec4 fragColor; void main() { vec4 tex = texture(Sampler0, texCoord0); vec4 color = tex * ColorModulator; - if (tex.a > 0.9) { + if (tex.a > 0.99) { color = color * vertexColor; } color.a = 1.0; From 21f33f1fef87e71eff90648ba2889bad493b7855 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 17:30:24 +0300 Subject: [PATCH 0044/1033] Version change --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index e11b676a..e0c580db 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.3 +mod_version = 0.2.4 maven_group = ru.bclib archives_base_name = bclib From 5afaf5f324caa73977415dca10bb93fcdeb3268b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 17:56:57 +0300 Subject: [PATCH 0045/1033] Deprecated mipped shaders --- ..._cutout_mipped.fsh => deprecated_rendertype_cutout_mipped.fsh} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/resources/assets/minecraft/shaders/core/{rendertype_cutout_mipped.fsh => deprecated_rendertype_cutout_mipped.fsh} (100%) diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh b/src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh similarity index 100% rename from src/main/resources/assets/minecraft/shaders/core/rendertype_cutout_mipped.fsh rename to src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh From 5c6c4677b0bd3bcf0c516c1f46b41771178783c0 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 19:27:04 +0300 Subject: [PATCH 0046/1033] Shader update --- .../shaders/core/rendertype_cutout.fsh | 25 ++++++++-- .../shaders/core/rendertype_entity_cutout.fsh | 47 +++++++++++++++++++ ...endertype_item_entity_translucent_cull.fsh | 46 ++++++++++++++++++ .../shaders/core/rendertype_solid.fsh | 25 ++++++++-- 4 files changed, 137 insertions(+), 6 deletions(-) create mode 100644 src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh create mode 100644 src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh index 441b8209..9687414d 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh @@ -14,15 +14,34 @@ in vec2 texCoord0; out vec4 fragColor; +vec3 rgbToHSV(vec3 color) { + vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); + vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsvToRGB(vec3 color) { + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + void main() { vec4 tex = texture(Sampler0, texCoord0); if (tex.a < 0.1) { discard; } vec4 color = tex * ColorModulator; - if (tex.a > 0.99) { - color = color * vertexColor; + vec4 vertex = vertexColor; + if (tex.a < 0.99) { + vec3 hsv = rgbToHSV(vertex.rgb); + hsv.z = 1.0; + vertex.rgb = hsvToRGB(hsv); } + color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); color.a = 1.0; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = color; } diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh new file mode 100644 index 00000000..dbf6cf19 --- /dev/null +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh @@ -0,0 +1,47 @@ +#version 150 +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec2 texCoord0; + +out vec4 fragColor; + +vec3 rgbToHSV(vec3 color) { + vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); + vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsvToRGB(vec3 color) { + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +void main() { + vec4 tex = texture(Sampler0, texCoord0); + if (tex.a < 0.1) { + discard; + } + vec4 color = tex * ColorModulator; + vec4 vertex = vertexColor; + if (tex.a < 0.99) { + vec3 hsv = rgbToHSV(vertex.rgb); + hsv.z = 1.0; + vertex.rgb = hsvToRGB(hsv); + } + color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); + color.a = 1.0; + fragColor = color; +} \ No newline at end of file diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh new file mode 100644 index 00000000..503293f4 --- /dev/null +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh @@ -0,0 +1,46 @@ +#version 150 +#moj_import + +uniform sampler2D Sampler0; + +uniform vec4 ColorModulator; +uniform float FogStart; +uniform float FogEnd; +uniform vec4 FogColor; + +in float vertexDistance; +in vec4 vertexColor; +in vec2 texCoord0; + +out vec4 fragColor; + +vec3 rgbToHSV(vec3 color) { + vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); + vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsvToRGB(vec3 color) { + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +void main() { + vec4 tex = texture(Sampler0, texCoord0); + if (tex.a < 0.1) { + discard; + } + vec4 color = tex * ColorModulator; + vec4 vertex = vertexColor; + if (tex.a < 0.99) { + vec3 hsv = rgbToHSV(vertex.rgb); + hsv.z = 1.0; + vertex.rgb = hsvToRGB(hsv); + } + color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = color; +} \ No newline at end of file diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh index c01d103d..19222825 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh @@ -14,12 +14,31 @@ in vec2 texCoord0; out vec4 fragColor; +vec3 rgbToHSV(vec3 color) { + vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); + vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsvToRGB(vec3 color) { + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + void main() { vec4 tex = texture(Sampler0, texCoord0); vec4 color = tex * ColorModulator; - if (tex.a > 0.99) { - color = color * vertexColor; + vec4 vertex = vertexColor; + if (tex.a < 0.99) { + vec3 hsv = rgbToHSV(vertex.rgb); + hsv.z = 1.0; + vertex.rgb = hsvToRGB(hsv); } + color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); color.a = 1.0; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); + fragColor = color; } From f8b88909cb410610835ce0f75dfdfe6983f62fdc Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sun, 18 Jul 2021 19:51:59 +0300 Subject: [PATCH 0047/1033] Item shaders upgrade --- .../deprecated_rendertype_cutout_mipped.fsh | 28 ------------------- ...endertype_item_entity_translucent_cull.fsh | 2 ++ 2 files changed, 2 insertions(+), 28 deletions(-) delete mode 100644 src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh diff --git a/src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh b/src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh deleted file mode 100644 index 441b8209..00000000 --- a/src/main/resources/assets/minecraft/shaders/core/deprecated_rendertype_cutout_mipped.fsh +++ /dev/null @@ -1,28 +0,0 @@ -#version 150 -#moj_import - -uniform sampler2D Sampler0; - -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; - -in float vertexDistance; -in vec4 vertexColor; -in vec2 texCoord0; - -out vec4 fragColor; - -void main() { - vec4 tex = texture(Sampler0, texCoord0); - if (tex.a < 0.1) { - discard; - } - vec4 color = tex * ColorModulator; - if (tex.a > 0.99) { - color = color * vertexColor; - } - color.a = 1.0; - fragColor = linear_fog(color, vertexDistance, FogStart, FogEnd, FogColor); -} diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh index 503293f4..2293003e 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh @@ -11,6 +11,7 @@ uniform vec4 FogColor; in float vertexDistance; in vec4 vertexColor; in vec2 texCoord0; +in vec4 overlayColor; out vec4 fragColor; @@ -35,6 +36,7 @@ void main() { discard; } vec4 color = tex * ColorModulator; + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); vec4 vertex = vertexColor; if (tex.a < 0.99) { vec3 hsv = rgbToHSV(vertex.rgb); From 42d9f7f887cda67013d680dd7bca3a8ae873df89 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 19 Jul 2021 01:38:13 +0300 Subject: [PATCH 0048/1033] Fixed item entity lights --- .../minecraft/shaders/core/rendertype_entity_cutout.fsh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh index dbf6cf19..f00c54f9 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh @@ -9,6 +9,8 @@ uniform float FogEnd; uniform vec4 FogColor; in float vertexDistance; +in vec4 lightMapColor; +in vec4 overlayColor; in vec4 vertexColor; in vec2 texCoord0; @@ -35,7 +37,8 @@ void main() { discard; } vec4 color = tex * ColorModulator; - vec4 vertex = vertexColor; + color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); + vec4 vertex = vertexColor * lightMapColor; if (tex.a < 0.99) { vec3 hsv = rgbToHSV(vertex.rgb); hsv.z = 1.0; From 280c6d5849ae76fb4d6cdbd67fc545f4840e50d3 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:24:34 +0200 Subject: [PATCH 0049/1033] Fixed hash-calculation for `ConfigKey` --- src/main/java/ru/bclib/config/ConfigKey.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/config/ConfigKey.java b/src/main/java/ru/bclib/config/ConfigKey.java index 88b2083b..ca1d7da0 100644 --- a/src/main/java/ru/bclib/config/ConfigKey.java +++ b/src/main/java/ru/bclib/config/ConfigKey.java @@ -1,5 +1,7 @@ package ru.bclib.config; +import java.util.Arrays; + import net.minecraft.resources.ResourceLocation; public class ConfigKey { @@ -34,7 +36,7 @@ public class ConfigKey { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + path.hashCode(); + result = prime * result + Arrays.hashCode(path); result = prime * result + entry.hashCode(); return result; } From d63aa5b92ef55c08376e0cdd93c4d75aba94939d Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:45:17 +0200 Subject: [PATCH 0050/1033] Added method to register special blocks to correct registries --- .../ru/bclib/registry/BaseBlockEntities.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index f1170bb8..e819029b 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -44,4 +44,25 @@ public class BaseBlockEntities { public static Block[] getFurnaces() { return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } + + public static boolean registerSpecialBlock(Block block) { + if (block instanceof BaseChestBlock) { + BaseBlockEntities.CHEST.registerBlock(block); + return true; + } + if (block instanceof BaseSignBlock) { + BaseBlockEntities.SIGN.registerBlock(block); + return true; + } + if (block instanceof BaseBarrelBlock) { + BaseBlockEntities.BARREL.registerBlock(block); + return true; + } + if (block instanceof BaseFurnaceBlock) { + BaseBlockEntities.FURNACE.registerBlock(block); + return true; + } + + return false; + } } From 8d5f2356849d322f04e46c20da34d6af58c26e20 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:54:16 +0200 Subject: [PATCH 0051/1033] Fixed hash-calculation for `ConfigKey` --- src/main/java/ru/bclib/config/ConfigKey.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/config/ConfigKey.java b/src/main/java/ru/bclib/config/ConfigKey.java index 88b2083b..ca1d7da0 100644 --- a/src/main/java/ru/bclib/config/ConfigKey.java +++ b/src/main/java/ru/bclib/config/ConfigKey.java @@ -1,5 +1,7 @@ package ru.bclib.config; +import java.util.Arrays; + import net.minecraft.resources.ResourceLocation; public class ConfigKey { @@ -34,7 +36,7 @@ public class ConfigKey { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + path.hashCode(); + result = prime * result + Arrays.hashCode(path); result = prime * result + entry.hashCode(); return result; } From fee7cbc93ad0ff6522abc3b768c7f3300d5ecb9e Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:54:16 +0200 Subject: [PATCH 0052/1033] Added possibility to store configs at costum locations --- src/main/java/ru/bclib/config/Config.java | 10 ++++++-- .../java/ru/bclib/config/ConfigKeeper.java | 23 ++++++++++++------- .../java/ru/bclib/config/ConfigWriter.java | 22 +++++++++++++----- 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/main/java/ru/bclib/config/Config.java b/src/main/java/ru/bclib/config/Config.java index a1df5824..9219589a 100644 --- a/src/main/java/ru/bclib/config/Config.java +++ b/src/main/java/ru/bclib/config/Config.java @@ -1,5 +1,7 @@ package ru.bclib.config; +import java.io.File; + import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; import ru.bclib.config.ConfigKeeper.BooleanEntry; @@ -13,9 +15,13 @@ public abstract class Config { protected final ConfigKeeper keeper; protected abstract void registerEntries(); + + public Config(String modID, String group){ + this(modID, group, null); + } - public Config(String modID, String group) { - this.keeper = new ConfigKeeper(modID, group); + protected Config(String modID, String group, File path) { + this.keeper = new ConfigKeeper(modID, group, path); this.registerEntries(); } diff --git a/src/main/java/ru/bclib/config/ConfigKeeper.java b/src/main/java/ru/bclib/config/ConfigKeeper.java index 841e7d27..0b5daf62 100644 --- a/src/main/java/ru/bclib/config/ConfigKeeper.java +++ b/src/main/java/ru/bclib/config/ConfigKeeper.java @@ -1,17 +1,20 @@ package ru.bclib.config; +import java.io.File; +import java.lang.reflect.Type; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import org.jetbrains.annotations.Nullable; + import com.google.common.collect.Maps; import com.google.common.reflect.TypeToken; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.minecraft.util.GsonHelper; -import org.jetbrains.annotations.Nullable; -import ru.bclib.util.JsonFactory; -import java.lang.reflect.Type; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; +import net.minecraft.util.GsonHelper; +import ru.bclib.util.JsonFactory; public final class ConfigKeeper { private final Map> configEntries = Maps.newHashMap(); @@ -21,7 +24,11 @@ public final class ConfigKeeper { private boolean changed = false; public ConfigKeeper(String modID, String group) { - this.writer = new ConfigWriter(modID, group); + this(modID, group, null); + } + + protected ConfigKeeper(String modID, String group, File path) { + this.writer = new ConfigWriter(modID, group, path); this.configObject = writer.load(); } diff --git a/src/main/java/ru/bclib/config/ConfigWriter.java b/src/main/java/ru/bclib/config/ConfigWriter.java index 5884641d..98f70826 100644 --- a/src/main/java/ru/bclib/config/ConfigWriter.java +++ b/src/main/java/ru/bclib/config/ConfigWriter.java @@ -1,13 +1,14 @@ package ru.bclib.config; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.fabricmc.loader.api.FabricLoader; -import ru.bclib.util.JsonFactory; - import java.io.File; import java.nio.file.Path; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import net.fabricmc.loader.api.FabricLoader; +import ru.bclib.util.JsonFactory; + public class ConfigWriter { private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); @@ -15,7 +16,16 @@ public class ConfigWriter { private JsonObject configObject; public ConfigWriter(String modID, String configFile) { - this.configFile = new File(new File(GAME_CONFIG_DIR.toFile(), modID), configFile + ".json"); + this(modID, configFile, null); + } + + public ConfigWriter(String modID, String configFile, File configFolder) { + this.configFile = new File( + (configFolder==null + ? GAME_CONFIG_DIR.resolve(modID).toFile() + : new File(configFolder, modID)), + configFile + ".json" + ); File parent = this.configFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); From 102c9ec0ccd8d4a1087373c9e5a7d5820ed7ca18 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:54:16 +0200 Subject: [PATCH 0053/1033] Added a `SessionConfig` class that can generate config files inside a world folder --- src/main/java/ru/bclib/config/PathConfig.java | 8 +++++- .../java/ru/bclib/config/SessionConfig.java | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/bclib/config/SessionConfig.java diff --git a/src/main/java/ru/bclib/config/PathConfig.java b/src/main/java/ru/bclib/config/PathConfig.java index da3c1d49..1b09efcf 100644 --- a/src/main/java/ru/bclib/config/PathConfig.java +++ b/src/main/java/ru/bclib/config/PathConfig.java @@ -1,5 +1,7 @@ package ru.bclib.config; +import java.io.File; + import org.jetbrains.annotations.Nullable; import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; @@ -8,7 +10,11 @@ import ru.bclib.config.ConfigKeeper.IntegerRange; public class PathConfig extends Config { public PathConfig(String modID, String group) { - super(modID, group); + this(modID, group, null); + } + + protected PathConfig(String modID, String group, File path) { + super(modID, group, path); } @Override diff --git a/src/main/java/ru/bclib/config/SessionConfig.java b/src/main/java/ru/bclib/config/SessionConfig.java new file mode 100644 index 00000000..8fb3b1c2 --- /dev/null +++ b/src/main/java/ru/bclib/config/SessionConfig.java @@ -0,0 +1,25 @@ +package ru.bclib.config; + +import java.io.File; + +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.storage.LevelStorageSource; +import ru.bclib.BCLib; + +public class SessionConfig extends PathConfig{ + private static File getWorldFolder(LevelStorageSource.LevelStorageAccess session, ServerLevel world){ + File dir = session.getDimensionPath(world.dimension()); + if (!new File(dir, "level.dat").exists()) { + dir = dir.getParentFile(); + } + return dir; + } + + public final File levelFolder; + + public SessionConfig(String modID, String group, LevelStorageSource.LevelStorageAccess session, ServerLevel world) { + super(modID, group, new File(getWorldFolder(session, world), BCLib.MOD_ID)); + + this.levelFolder = new File(getWorldFolder(session, world), BCLib.MOD_ID); + } +} From 51235429db3e173d7344df2d3abbcf8d5c6f0218 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:54:37 +0200 Subject: [PATCH 0054/1033] Added alternative `DataFixerAPI` --- src/main/java/ru/bclib/api/DataFixerAPI2.java | 289 ++++++++++++++++++ src/main/java/ru/bclib/config/Configs.java | 4 + 2 files changed, 293 insertions(+) create mode 100644 src/main/java/ru/bclib/api/DataFixerAPI2.java diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java new file mode 100644 index 00000000..3f407b23 --- /dev/null +++ b/src/main/java/ru/bclib/api/DataFixerAPI2.java @@ -0,0 +1,289 @@ +package ru.bclib.api; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import org.jetbrains.annotations.NotNull; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.RegionFile; +import ru.bclib.BCLib; +import ru.bclib.config.Configs; +import ru.bclib.config.PathConfig; +import ru.bclib.config.SessionConfig; +import ru.bclib.util.Logger; + +public class DataFixerAPI2 { + private static final Logger LOGGER = new Logger("DataFixerAPI"); + + public static void fixData(SessionConfig config) { + if (true || !Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)){ + LOGGER.info("World Patches are disabled"); + return; + } + + final File dir = config.levelFolder; + Patch.MigrationData data = Patch.createMigrationData(config); + if (!data.hasAnyFixes()) { + LOGGER.info("Everything up to date"); + return; + } + + List regions = getAllRegions(dir, null); + regions.parallelStream().forEach((file) -> { + try { + LOGGER.info("Inspecting " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + ChunkPos pos = new ChunkPos(x, z); + changed[0] = false; + if (region.hasChunk(pos)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + // } + input.close(); + + ListTag tileEntities = root.getCompound("Level").getList("TileEntities", 10); + fixItemArrayWithID(tileEntities, changed, data, true); + + ListTag sections = root.getCompound("Level").getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); + }); + }); + if (changed[0]) { + LOGGER.warning("Writing '{}': {}/{}", file, x, z); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + } + } + } + } + region.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + }); + + data.markApplied(); + } + + private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, Patch.MigrationData data, boolean recursive){ + items.forEach(inTag -> { + final CompoundTag tag = (CompoundTag) inTag; + + changed[0] |= data.replaceStringFromIDs(tag, "id"); + + if (recursive && tag.contains("Items")){ + changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); + } + }); + + return changed[0]; + } + + private static List getAllRegions(File dir, List list) { + if (list == null) { + list = new ArrayList<>(); + } + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + getAllRegions(file, list); + } + else if (file.isFile() && file.getName().endsWith(".mca")) { + list.add(file); + } + } + return list; + } + + public abstract static class Patch { + private static List ALL = new ArrayList<>(10); + private final int level; + @NotNull + private final String modID; + + static List getALL() { + return ALL; + } + + /** + * register a new Patch + * @param patch A #Supplier that will instantiate the new Patch Object + */ + public static void registerPatch(Supplier patch){ + ALL.add(patch.get()); + } + + /** + * Returns the highest patch-level that is available for the given mod. If no patches were + * registerd for the mod, this will return 0 + * @param modID The ID of the mod you want to query + * @return The highest Patch-Level that was found + */ + public static int maxPatchLevel(@NotNull String modID){ + return ALL.stream() + .filter(p-> p.getModID().equals(modID)) + .mapToInt(p->p.level) + .max() + .orElse(0); + } + + /** + * Called by inheriting classes. + * + * Performs some sanity checks on the values and might throw a #RuntimeException if any + * inconsistencies are found. + * + * @param modID The ID of the Mod you want to register a patch for. This should be your + * ModID only. The ModID can not be {@code null} or an empty String. + * @param level The level of the Patch. This needs to be a non-zero positive value. + * Developers are responsible for registering their patches in the correct + * order (with increasing levels). You are not allowed to register a new + * Patch with a Patch-level lower or equal than + * {@link Patch#maxPatchLevel(String)} + */ + protected Patch(@NotNull String modID, int level) { + //Patchlevels need to be unique and registered in ascending order + if (modID==null || "".equals(modID)){ + throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); + } + if (!ALL.stream().filter(p-> p.getModID().equals(modID)).noneMatch(p -> p.getLevel() >= level) || level <= 0){ + throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); + } + + + BCLib.LOGGER.info("Creating Patchlevel {} ({}, {})", level, ALL, ALL.stream().noneMatch(p -> p.getLevel() >= level)); + this.level = level; + this.modID = modID; + } + + @Override + public String toString() { + return "Patch{" + + "level=" + getModID() + ":" + getLevel() + + '}'; + } + + final public int getLevel() { + return level; + } + + /** + * The Mod-ID that registered this Patch + * @return The ID + */ + final public String getModID() { + return modID; + } + + + /** + * Return block data fixes. Fixes will be applied on world load if current patch-level for + * the linked mod is lower than the {@link #level}. + * + * The default implementation of this method returns an empty map. + * + * @return The returned Map should contain the replacements. All occurences of the + * {@code KeySet} are replaced with the associated value. + */ + public Map getIDReplacements(){ + return new HashMap(); + } + + /** + * Generates ready to use data for all currently registered patches. The list of + * patches is selected by the current patch-level of the world. + * + * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the + * world is less + * @return a new {@link MigrationData} Object. + */ + static MigrationData createMigrationData(PathConfig config){ + return new MigrationData(config); + } + + static class MigrationData{ + final Set mods; + final Map idReplacements; + private final PathConfig config; + + private MigrationData(PathConfig config){ + this.config = config; + + this.mods = Collections.unmodifiableSet(Patch.getALL().stream().map(p -> p.modID).collect(Collectors.toSet())); + + HashMap replacements = new HashMap(); + for(String modID : mods){ + Patch.getALL().stream().filter(p -> p.modID.equals(modID)).forEach(patch -> { + if (currentPatchLevel(modID) < patch.level) { + replacements.putAll(patch.getIDReplacements()); + LOGGER.info("Applying " + patch); + } else { + LOGGER.info("Ignoring " + patch); + } + }); + } + + this.idReplacements = Collections.unmodifiableMap(replacements); + } + + final public void markApplied(){ + for(String modID : mods){ + LOGGER.info("Updating Patch-Level for '{}' from {} to {} -> {}", + modID, + currentPatchLevel(modID), + Patch.maxPatchLevel(modID), + config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID)) + ); + } + + config.saveChanges(); + } + + public int currentPatchLevel(@NotNull String modID){ + return config.getInt(Configs.MAIN_PATCH_CATEGORY, modID, 0); + } + + public boolean hasAnyFixes(){ + return idReplacements.size()>0; + } + + public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key){ + if (!tag.contains(key)) return false; + + final String val = tag.getString(key); + final String replace = idReplacements.get(val); + + if (replace != null){ + LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); + tag.putString(key, replace); + return true; + } + + return false; + } + } + } +} diff --git a/src/main/java/ru/bclib/config/Configs.java b/src/main/java/ru/bclib/config/Configs.java index c847a620..bbfc86b2 100644 --- a/src/main/java/ru/bclib/config/Configs.java +++ b/src/main/java/ru/bclib/config/Configs.java @@ -3,9 +3,13 @@ package ru.bclib.config; import ru.bclib.BCLib; public class Configs { + public static final PathConfig MAIN_CONFIG = new PathConfig(BCLib.MOD_ID, "main"); + public static final String MAIN_PATCH_CATEGORY = "patches"; + public static final PathConfig RECIPE_CONFIG = new PathConfig(BCLib.MOD_ID, "recipes"); public static void save() { + MAIN_CONFIG.saveChanges(); RECIPE_CONFIG.saveChanges(); } } From 5d2bb2c66c51dabf51ef4c9ec985a4785d4ee53e Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 19:54:37 +0200 Subject: [PATCH 0055/1033] Call new DataFixer-API --- .../ru/bclib/mixin/common/ServerLevelMixin.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index af47e301..cffd3b7a 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -1,5 +1,10 @@ package ru.bclib.mixin.common; +import java.io.File; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.function.Supplier; + import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -16,14 +21,11 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import ru.bclib.BCLib; import ru.bclib.api.BiomeAPI; -import ru.bclib.api.DataFixerAPI; +import ru.bclib.api.DataFixerAPI2; import ru.bclib.api.WorldDataAPI; - -import java.io.File; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.function.Supplier; +import ru.bclib.config.SessionConfig; @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level { @@ -49,7 +51,8 @@ public abstract class ServerLevelMixin extends Level { dir = dir.getParentFile(); } - DataFixerAPI.fixData(dir); + //DataFixerAPI.fixData(dir); + DataFixerAPI2.fixData(new SessionConfig(BCLib.MOD_ID, "patches", session, world)); WorldDataAPI.load(new File(dir, "data")); } } From 179ada3296b5feef9d29e2f36511873e615d7318 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Mon, 19 Jul 2021 21:41:07 +0300 Subject: [PATCH 0056/1033] Code style fix & version update --- gradle.properties | 2 +- src/main/java/ru/bclib/api/DataFixerAPI2.java | 539 +++++++++--------- src/main/java/ru/bclib/api/TagAPI.java | 4 +- src/main/java/ru/bclib/blocks/BaseBlock.java | 30 +- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 37 +- .../blocks/properties/StringProperty.java | 23 +- src/main/java/ru/bclib/config/Config.java | 8 +- .../java/ru/bclib/config/ConfigKeeper.java | 20 +- src/main/java/ru/bclib/config/ConfigKey.java | 4 +- .../java/ru/bclib/config/ConfigWriter.java | 16 +- src/main/java/ru/bclib/config/Configs.java | 2 +- src/main/java/ru/bclib/config/PathConfig.java | 6 +- .../java/ru/bclib/config/SessionConfig.java | 34 +- .../ru/bclib/mixin/client/MinecraftMixin.java | 14 +- .../bclib/mixin/client/TextureAtlasMixin.java | 6 +- .../bclib/mixin/common/BoneMealItemMixin.java | 6 +- .../bclib/mixin/common/ServerLevelMixin.java | 10 +- .../ru/bclib/registry/BaseBlockEntities.java | 4 +- src/main/java/ru/bclib/util/JsonFactory.java | 4 +- src/main/java/ru/bclib/util/TagHelper.java | 50 +- 20 files changed, 392 insertions(+), 427 deletions(-) diff --git a/gradle.properties b/gradle.properties index e0c580db..dccb9055 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.4 +mod_version = 0.2.5 maven_group = ru.bclib archives_base_name = bclib diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java index 3f407b23..3863ea49 100644 --- a/src/main/java/ru/bclib/api/DataFixerAPI2.java +++ b/src/main/java/ru/bclib/api/DataFixerAPI2.java @@ -1,5 +1,17 @@ package ru.bclib.api; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.RegionFile; +import org.jetbrains.annotations.NotNull; +import ru.bclib.BCLib; +import ru.bclib.config.Configs; +import ru.bclib.config.PathConfig; +import ru.bclib.config.SessionConfig; +import ru.bclib.util.Logger; + import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; @@ -12,278 +24,259 @@ import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; -import org.jetbrains.annotations.NotNull; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.storage.RegionFile; -import ru.bclib.BCLib; -import ru.bclib.config.Configs; -import ru.bclib.config.PathConfig; -import ru.bclib.config.SessionConfig; -import ru.bclib.util.Logger; - public class DataFixerAPI2 { - private static final Logger LOGGER = new Logger("DataFixerAPI"); - - public static void fixData(SessionConfig config) { - if (true || !Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)){ - LOGGER.info("World Patches are disabled"); - return; - } - - final File dir = config.levelFolder; - Patch.MigrationData data = Patch.createMigrationData(config); - if (!data.hasAnyFixes()) { - LOGGER.info("Everything up to date"); - return; - } - - List regions = getAllRegions(dir, null); - regions.parallelStream().forEach((file) -> { - try { - LOGGER.info("Inspecting " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), true); - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos)) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - // } - input.close(); - - ListTag tileEntities = root.getCompound("Level").getList("TileEntities", 10); - fixItemArrayWithID(tileEntities, changed, data, true); - - ListTag sections = root.getCompound("Level").getList("Sections", 10); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", 10); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); - }); - }); - if (changed[0]) { - LOGGER.warning("Writing '{}': {}/{}", file, x, z); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - }); - - data.markApplied(); - } - - private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, Patch.MigrationData data, boolean recursive){ - items.forEach(inTag -> { - final CompoundTag tag = (CompoundTag) inTag; - - changed[0] |= data.replaceStringFromIDs(tag, "id"); - - if (recursive && tag.contains("Items")){ - changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); - } - }); - - return changed[0]; - } - - private static List getAllRegions(File dir, List list) { - if (list == null) { - list = new ArrayList<>(); - } - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - getAllRegions(file, list); - } - else if (file.isFile() && file.getName().endsWith(".mca")) { - list.add(file); - } - } - return list; - } - - public abstract static class Patch { - private static List ALL = new ArrayList<>(10); - private final int level; - @NotNull - private final String modID; - - static List getALL() { - return ALL; - } - - /** - * register a new Patch - * @param patch A #Supplier that will instantiate the new Patch Object - */ - public static void registerPatch(Supplier patch){ - ALL.add(patch.get()); - } - - /** - * Returns the highest patch-level that is available for the given mod. If no patches were - * registerd for the mod, this will return 0 - * @param modID The ID of the mod you want to query - * @return The highest Patch-Level that was found - */ - public static int maxPatchLevel(@NotNull String modID){ - return ALL.stream() - .filter(p-> p.getModID().equals(modID)) - .mapToInt(p->p.level) - .max() - .orElse(0); - } - - /** - * Called by inheriting classes. - * - * Performs some sanity checks on the values and might throw a #RuntimeException if any - * inconsistencies are found. - * - * @param modID The ID of the Mod you want to register a patch for. This should be your - * ModID only. The ModID can not be {@code null} or an empty String. - * @param level The level of the Patch. This needs to be a non-zero positive value. - * Developers are responsible for registering their patches in the correct - * order (with increasing levels). You are not allowed to register a new - * Patch with a Patch-level lower or equal than - * {@link Patch#maxPatchLevel(String)} - */ - protected Patch(@NotNull String modID, int level) { - //Patchlevels need to be unique and registered in ascending order - if (modID==null || "".equals(modID)){ - throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); - } - if (!ALL.stream().filter(p-> p.getModID().equals(modID)).noneMatch(p -> p.getLevel() >= level) || level <= 0){ - throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); - } - - - BCLib.LOGGER.info("Creating Patchlevel {} ({}, {})", level, ALL, ALL.stream().noneMatch(p -> p.getLevel() >= level)); - this.level = level; - this.modID = modID; - } - - @Override - public String toString() { - return "Patch{" + - "level=" + getModID() + ":" + getLevel() + - '}'; - } - - final public int getLevel() { - return level; - } - - /** - * The Mod-ID that registered this Patch - * @return The ID - */ - final public String getModID() { - return modID; - } - - - /** - * Return block data fixes. Fixes will be applied on world load if current patch-level for - * the linked mod is lower than the {@link #level}. - * - * The default implementation of this method returns an empty map. - * - * @return The returned Map should contain the replacements. All occurences of the - * {@code KeySet} are replaced with the associated value. - */ - public Map getIDReplacements(){ - return new HashMap(); - } - - /** - * Generates ready to use data for all currently registered patches. The list of - * patches is selected by the current patch-level of the world. - * - * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the - * world is less - * @return a new {@link MigrationData} Object. - */ - static MigrationData createMigrationData(PathConfig config){ - return new MigrationData(config); - } - - static class MigrationData{ - final Set mods; - final Map idReplacements; - private final PathConfig config; - - private MigrationData(PathConfig config){ - this.config = config; - - this.mods = Collections.unmodifiableSet(Patch.getALL().stream().map(p -> p.modID).collect(Collectors.toSet())); - - HashMap replacements = new HashMap(); - for(String modID : mods){ - Patch.getALL().stream().filter(p -> p.modID.equals(modID)).forEach(patch -> { - if (currentPatchLevel(modID) < patch.level) { - replacements.putAll(patch.getIDReplacements()); - LOGGER.info("Applying " + patch); - } else { - LOGGER.info("Ignoring " + patch); - } - }); - } - - this.idReplacements = Collections.unmodifiableMap(replacements); - } - - final public void markApplied(){ - for(String modID : mods){ - LOGGER.info("Updating Patch-Level for '{}' from {} to {} -> {}", - modID, - currentPatchLevel(modID), - Patch.maxPatchLevel(modID), - config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID)) - ); - } - - config.saveChanges(); - } - - public int currentPatchLevel(@NotNull String modID){ - return config.getInt(Configs.MAIN_PATCH_CATEGORY, modID, 0); - } - - public boolean hasAnyFixes(){ - return idReplacements.size()>0; - } - - public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key){ - if (!tag.contains(key)) return false; - - final String val = tag.getString(key); - final String replace = idReplacements.get(val); - - if (replace != null){ - LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); - tag.putString(key, replace); - return true; - } - - return false; - } - } - } + private static final Logger LOGGER = new Logger("DataFixerAPI"); + + public static void fixData(SessionConfig config) { + if (true || !Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { + LOGGER.info("World Patches are disabled"); + return; + } + + final File dir = config.levelFolder; + Patch.MigrationData data = Patch.createMigrationData(config); + if (!data.hasAnyFixes()) { + LOGGER.info("Everything up to date"); + return; + } + + List regions = getAllRegions(dir, null); + regions.parallelStream().forEach((file) -> { + try { + LOGGER.info("Inspecting " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + ChunkPos pos = new ChunkPos(x, z); + changed[0] = false; + if (region.hasChunk(pos)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + // } + input.close(); + + ListTag tileEntities = root.getCompound("Level").getList("TileEntities", 10); + fixItemArrayWithID(tileEntities, changed, data, true); + + ListTag sections = root.getCompound("Level").getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); + }); + }); + if (changed[0]) { + LOGGER.warning("Writing '{}': {}/{}", file, x, z); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + } + } + } + } + region.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + }); + + data.markApplied(); + } + + private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, Patch.MigrationData data, boolean recursive) { + items.forEach(inTag -> { + final CompoundTag tag = (CompoundTag) inTag; + + changed[0] |= data.replaceStringFromIDs(tag, "id"); + + if (recursive && tag.contains("Items")) { + changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); + } + }); + + return changed[0]; + } + + private static List getAllRegions(File dir, List list) { + if (list == null) { + list = new ArrayList<>(); + } + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + getAllRegions(file, list); + } + else if (file.isFile() && file.getName().endsWith(".mca")) { + list.add(file); + } + } + return list; + } + + public abstract static class Patch { + private static List ALL = new ArrayList<>(10); + private final int level; + @NotNull + private final String modID; + + static List getALL() { + return ALL; + } + + /** + * register a new Patch + * + * @param patch A #Supplier that will instantiate the new Patch Object + */ + public static void registerPatch(Supplier patch) { + ALL.add(patch.get()); + } + + /** + * Returns the highest patch-level that is available for the given mod. If no patches were + * registerd for the mod, this will return 0 + * + * @param modID The ID of the mod you want to query + * @return The highest Patch-Level that was found + */ + public static int maxPatchLevel(@NotNull String modID) { + return ALL.stream().filter(p -> p.getModID().equals(modID)).mapToInt(p -> p.level).max().orElse(0); + } + + /** + * Called by inheriting classes. + *

+ * Performs some sanity checks on the values and might throw a #RuntimeException if any + * inconsistencies are found. + * + * @param modID The ID of the Mod you want to register a patch for. This should be your + * ModID only. The ModID can not be {@code null} or an empty String. + * @param level The level of the Patch. This needs to be a non-zero positive value. + * Developers are responsible for registering their patches in the correct + * order (with increasing levels). You are not allowed to register a new + * Patch with a Patch-level lower or equal than + * {@link Patch#maxPatchLevel(String)} + */ + protected Patch(@NotNull String modID, int level) { + //Patchlevels need to be unique and registered in ascending order + if (modID == null || "".equals(modID)) { + throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); + } + if (!ALL.stream().filter(p -> p.getModID().equals(modID)).noneMatch(p -> p.getLevel() >= level) || level <= 0) { + throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); + } + + + BCLib.LOGGER.info("Creating Patchlevel {} ({}, {})", level, ALL, ALL.stream().noneMatch(p -> p.getLevel() >= level)); + this.level = level; + this.modID = modID; + } + + @Override + public String toString() { + return "Patch{" + "level=" + getModID() + ":" + getLevel() + '}'; + } + + final public int getLevel() { + return level; + } + + /** + * The Mod-ID that registered this Patch + * + * @return The ID + */ + final public String getModID() { + return modID; + } + + + /** + * Return block data fixes. Fixes will be applied on world load if current patch-level for + * the linked mod is lower than the {@link #level}. + *

+ * The default implementation of this method returns an empty map. + * + * @return The returned Map should contain the replacements. All occurences of the + * {@code KeySet} are replaced with the associated value. + */ + public Map getIDReplacements() { + return new HashMap(); + } + + /** + * Generates ready to use data for all currently registered patches. The list of + * patches is selected by the current patch-level of the world. + *

+ * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the + * world is less + * + * @return a new {@link MigrationData} Object. + */ + static MigrationData createMigrationData(PathConfig config) { + return new MigrationData(config); + } + + static class MigrationData { + final Set mods; + final Map idReplacements; + private final PathConfig config; + + private MigrationData(PathConfig config) { + this.config = config; + + this.mods = Collections.unmodifiableSet(Patch.getALL().stream().map(p -> p.modID).collect(Collectors.toSet())); + + HashMap replacements = new HashMap(); + for (String modID : mods) { + Patch.getALL().stream().filter(p -> p.modID.equals(modID)).forEach(patch -> { + if (currentPatchLevel(modID) < patch.level) { + replacements.putAll(patch.getIDReplacements()); + LOGGER.info("Applying " + patch); + } + else { + LOGGER.info("Ignoring " + patch); + } + }); + } + + this.idReplacements = Collections.unmodifiableMap(replacements); + } + + final public void markApplied() { + for (String modID : mods) { + LOGGER.info("Updating Patch-Level for '{}' from {} to {} -> {}", modID, currentPatchLevel(modID), Patch.maxPatchLevel(modID), config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID))); + } + + config.saveChanges(); + } + + public int currentPatchLevel(@NotNull String modID) { + return config.getInt(Configs.MAIN_PATCH_CATEGORY, modID, 0); + } + + public boolean hasAnyFixes() { + return idReplacements.size() > 0; + } + + public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key) { + if (!tag.contains(key)) return false; + + final String val = tag.getString(key); + final String replace = idReplacements.get(val); + + if (replace != null) { + LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); + tag.putString(key, replace); + return true; + } + + return false; + } + } + } } diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 127a6aea..6ca55627 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,7 +1,5 @@ package ru.bclib.api; -import java.util.function.Supplier; - import net.fabricmc.fabric.api.tag.TagRegistry; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; @@ -16,6 +14,8 @@ import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; import ru.bclib.util.TagHelper; +import java.util.function.Supplier; + public class TagAPI { // Block Tags public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index e9e663bd..0f17e517 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -1,9 +1,5 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; @@ -14,9 +10,13 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import ru.bclib.client.models.BlockModelProvider; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + /** * Base class for a default Block. - * + *

* This Block-Type will: *

    *
  • Drop itself
  • @@ -26,15 +26,16 @@ import ru.bclib.client.models.BlockModelProvider; public class BaseBlock extends Block implements BlockModelProvider { /** * Creates a new Block with the passed properties + * * @param settings The properties of the Block. */ public BaseBlock(Properties settings) { super(settings); } - + /** * {@inheritDoc} - * + *

    * This implementation will drop the Block itself */ @Override @@ -42,29 +43,30 @@ public class BaseBlock extends Block implements BlockModelProvider { public List getDrops(BlockState state, LootContext.Builder builder) { return Collections.singletonList(new ItemStack(this)); } - + /** * {@inheritDoc} - * + *

    * This implementation will load the Block-Model and return it as the Item-Model */ @Override public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + /** * This method is used internally. - * + *

    * It is called from Block-Contructors, to allow the augmentation of the blocks * preset properties. - * + *

    * For example in {@link BaseLeavesBlock#BaseLeavesBlock(Block, MaterialColor, Consumer)} + * * @param customizeProperties A {@link Consumer} to call with the preset properties - * @param settings The properties as created by the Block + * @param settings The properties as created by the Block * @return The reconfigured {@code settings} */ - static FabricBlockSettings acceptAndReturn(Consumer customizeProperties, FabricBlockSettings settings){ + static FabricBlockSettings acceptAndReturn(Consumer customizeProperties, FabricBlockSettings settings) { customizeProperties.accept(settings); return settings; } diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index c6386ef7..3bbcb5aa 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,11 +1,6 @@ package ru.bclib.blocks; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - import com.google.common.collect.Lists; - import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; @@ -25,29 +20,25 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.MHelper; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { private final Block sapling; - - private static FabricBlockSettings makeLeaves(MaterialColor color){ - return FabricBlockSettings - .copyOf(Blocks.OAK_LEAVES) - .mapColor(color) - .breakByTool(FabricToolTags.HOES) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .allowsSpawning((state, world, pos, type) -> false) - .suffocates((state, world, pos) -> false) - .blockVision((state, world, pos) -> false); + + private static FabricBlockSettings makeLeaves(MaterialColor color) { + return FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).breakByHand(true).allowsSpawning((state, world, pos, type) -> false).suffocates((state, world, pos) -> false).blockVision((state, world, pos) -> false); } - + public BaseLeavesBlock(Block sapling, MaterialColor color, Consumer customizeProperties) { - super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); - this.sapling = sapling; + super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); + this.sapling = sapling; } - - public BaseLeavesBlock(Block sapling, MaterialColor color, int light, Consumer customizeProperties) { - super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).luminance(light))); - this.sapling = sapling; + + public BaseLeavesBlock(Block sapling, MaterialColor color, int light, Consumer customizeProperties) { + super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).luminance(light))); + this.sapling = sapling; } public BaseLeavesBlock(Block sapling, MaterialColor color) { diff --git a/src/main/java/ru/bclib/blocks/properties/StringProperty.java b/src/main/java/ru/bclib/blocks/properties/StringProperty.java index 8d7fc09b..8aaff298 100644 --- a/src/main/java/ru/bclib/blocks/properties/StringProperty.java +++ b/src/main/java/ru/bclib/blocks/properties/StringProperty.java @@ -3,16 +3,20 @@ package ru.bclib.blocks.properties; import com.google.common.collect.Sets; import net.minecraft.world.level.block.state.properties.Property; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; @Deprecated public class StringProperty extends Property { private final Set values; - + public static StringProperty create(String name, String... values) { return new StringProperty(name, values); } - + protected StringProperty(String string, String... values) { super(string, String.class); this.values = Sets.newHashSet(values); @@ -21,31 +25,32 @@ public class StringProperty extends Property { public void addValue(String name) { values.add(name); } - + @Override public Collection getPossibleValues() { return Collections.unmodifiableSet(values); } - + @Override public String getName(String comparable) { return comparable; } - + @Override public Optional getValue(String string) { if (values.contains(string)) { return Optional.of(string); - } else { + } + else { return Optional.empty(); } } - + @Override public int generateHashCode() { return super.generateHashCode() + Objects.hashCode(values); } - + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/ru/bclib/config/Config.java b/src/main/java/ru/bclib/config/Config.java index 9219589a..d5672efe 100644 --- a/src/main/java/ru/bclib/config/Config.java +++ b/src/main/java/ru/bclib/config/Config.java @@ -1,7 +1,5 @@ package ru.bclib.config; -import java.io.File; - import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; import ru.bclib.config.ConfigKeeper.BooleanEntry; @@ -11,12 +9,14 @@ import ru.bclib.config.ConfigKeeper.IntegerEntry; import ru.bclib.config.ConfigKeeper.RangeEntry; import ru.bclib.config.ConfigKeeper.StringEntry; +import java.io.File; + public abstract class Config { protected final ConfigKeeper keeper; protected abstract void registerEntries(); - - public Config(String modID, String group){ + + public Config(String modID, String group) { this(modID, group, null); } diff --git a/src/main/java/ru/bclib/config/ConfigKeeper.java b/src/main/java/ru/bclib/config/ConfigKeeper.java index 0b5daf62..12c1e75e 100644 --- a/src/main/java/ru/bclib/config/ConfigKeeper.java +++ b/src/main/java/ru/bclib/config/ConfigKeeper.java @@ -1,21 +1,19 @@ package ru.bclib.config; +import com.google.common.collect.Maps; +import com.google.common.reflect.TypeToken; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.minecraft.util.GsonHelper; +import org.jetbrains.annotations.Nullable; +import ru.bclib.util.JsonFactory; + import java.io.File; import java.lang.reflect.Type; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; -import org.jetbrains.annotations.Nullable; - -import com.google.common.collect.Maps; -import com.google.common.reflect.TypeToken; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import net.minecraft.util.GsonHelper; -import ru.bclib.util.JsonFactory; - public final class ConfigKeeper { private final Map> configEntries = Maps.newHashMap(); private final JsonObject configObject; @@ -26,7 +24,7 @@ public final class ConfigKeeper { public ConfigKeeper(String modID, String group) { this(modID, group, null); } - + protected ConfigKeeper(String modID, String group, File path) { this.writer = new ConfigWriter(modID, group, path); this.configObject = writer.load(); diff --git a/src/main/java/ru/bclib/config/ConfigKey.java b/src/main/java/ru/bclib/config/ConfigKey.java index ca1d7da0..0c770a3e 100644 --- a/src/main/java/ru/bclib/config/ConfigKey.java +++ b/src/main/java/ru/bclib/config/ConfigKey.java @@ -1,9 +1,9 @@ package ru.bclib.config; -import java.util.Arrays; - import net.minecraft.resources.ResourceLocation; +import java.util.Arrays; + public class ConfigKey { private final String path[]; private final String entry; diff --git a/src/main/java/ru/bclib/config/ConfigWriter.java b/src/main/java/ru/bclib/config/ConfigWriter.java index 98f70826..b6a54594 100644 --- a/src/main/java/ru/bclib/config/ConfigWriter.java +++ b/src/main/java/ru/bclib/config/ConfigWriter.java @@ -1,14 +1,13 @@ package ru.bclib.config; -import java.io.File; -import java.nio.file.Path; - import com.google.gson.JsonElement; import com.google.gson.JsonObject; - import net.fabricmc.loader.api.FabricLoader; import ru.bclib.util.JsonFactory; +import java.io.File; +import java.nio.file.Path; + public class ConfigWriter { private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); @@ -18,14 +17,9 @@ public class ConfigWriter { public ConfigWriter(String modID, String configFile) { this(modID, configFile, null); } - + public ConfigWriter(String modID, String configFile, File configFolder) { - this.configFile = new File( - (configFolder==null - ? GAME_CONFIG_DIR.resolve(modID).toFile() - : new File(configFolder, modID)), - configFile + ".json" - ); + this.configFile = new File((configFolder == null ? GAME_CONFIG_DIR.resolve(modID).toFile() : new File(configFolder, modID)), configFile + ".json"); File parent = this.configFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); diff --git a/src/main/java/ru/bclib/config/Configs.java b/src/main/java/ru/bclib/config/Configs.java index bbfc86b2..c29aed63 100644 --- a/src/main/java/ru/bclib/config/Configs.java +++ b/src/main/java/ru/bclib/config/Configs.java @@ -5,7 +5,7 @@ import ru.bclib.BCLib; public class Configs { public static final PathConfig MAIN_CONFIG = new PathConfig(BCLib.MOD_ID, "main"); public static final String MAIN_PATCH_CATEGORY = "patches"; - + public static final PathConfig RECIPE_CONFIG = new PathConfig(BCLib.MOD_ID, "recipes"); public static void save() { diff --git a/src/main/java/ru/bclib/config/PathConfig.java b/src/main/java/ru/bclib/config/PathConfig.java index 1b09efcf..ca9d960e 100644 --- a/src/main/java/ru/bclib/config/PathConfig.java +++ b/src/main/java/ru/bclib/config/PathConfig.java @@ -1,18 +1,18 @@ package ru.bclib.config; -import java.io.File; - import org.jetbrains.annotations.Nullable; import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.IntegerRange; +import java.io.File; + public class PathConfig extends Config { public PathConfig(String modID, String group) { this(modID, group, null); } - + protected PathConfig(String modID, String group, File path) { super(modID, group, path); } diff --git a/src/main/java/ru/bclib/config/SessionConfig.java b/src/main/java/ru/bclib/config/SessionConfig.java index 8fb3b1c2..3c311417 100644 --- a/src/main/java/ru/bclib/config/SessionConfig.java +++ b/src/main/java/ru/bclib/config/SessionConfig.java @@ -1,25 +1,25 @@ package ru.bclib.config; -import java.io.File; - import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.storage.LevelStorageSource; import ru.bclib.BCLib; -public class SessionConfig extends PathConfig{ - private static File getWorldFolder(LevelStorageSource.LevelStorageAccess session, ServerLevel world){ - File dir = session.getDimensionPath(world.dimension()); - if (!new File(dir, "level.dat").exists()) { - dir = dir.getParentFile(); - } - return dir; - } +import java.io.File; - public final File levelFolder; - - public SessionConfig(String modID, String group, LevelStorageSource.LevelStorageAccess session, ServerLevel world) { - super(modID, group, new File(getWorldFolder(session, world), BCLib.MOD_ID)); - - this.levelFolder = new File(getWorldFolder(session, world), BCLib.MOD_ID); - } +public class SessionConfig extends PathConfig { + private static File getWorldFolder(LevelStorageSource.LevelStorageAccess session, ServerLevel world) { + File dir = session.getDimensionPath(world.dimension()); + if (!new File(dir, "level.dat").exists()) { + dir = dir.getParentFile(); + } + return dir; + } + + public final File levelFolder; + + public SessionConfig(String modID, String group, LevelStorageSource.LevelStorageAccess session, ServerLevel world) { + super(modID, group, new File(getWorldFolder(session, world), BCLib.MOD_ID)); + + this.levelFolder = new File(getWorldFolder(session, world), BCLib.MOD_ID); + } } diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index a497e0b6..98d56db3 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -3,36 +3,26 @@ package ru.bclib.mixin.client; import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.WinScreen; import net.minecraft.client.main.GameConfig; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.Registry; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.Musics; -import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.interfaces.IColorProvider; -import ru.bclib.util.MHelper; @Mixin(Minecraft.class) public class MinecraftMixin { @Final @Shadow private BlockColors blockColors; - + @Final @Shadow private ItemColors itemColors; - + @Inject(method = "*", at = @At("TAIL")) private void bclib_onMCInit(GameConfig args, CallbackInfo info) { Registry.BLOCK.forEach(block -> { diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java index fbe102ac..ef8019bc 100644 --- a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java +++ b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java @@ -25,11 +25,7 @@ public class TextureAtlasMixin { bclib_modifyAtlas = resourceLocation.toString().equals("minecraft:textures/atlas/blocks.png"); } - @Inject( - method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite$Info;IIIII)Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;", - at = @At("HEAD"), - cancellable = true - ) + @Inject(method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite$Info;IIIII)Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;", at = @At("HEAD"), cancellable = true) private void bclib_loadSprite(ResourceManager resourceManager, TextureAtlasSprite.Info spriteInfo, int atlasWidth, int atlasHeight, int maxLevel, int posX, int posY, CallbackInfoReturnable info) { ResourceLocation location = spriteInfo.name(); if (bclib_modifyAtlas && location.getPath().startsWith("block")) { diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index cd84cb8a..89945814 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -7,7 +7,6 @@ import net.minecraft.world.InteractionResult; import net.minecraft.world.item.BoneMealItem; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome.BiomeCategory; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; @@ -18,12 +17,9 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; import ru.bclib.api.BonemealAPI; -import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; -import java.util.Collection; - @Mixin(BoneMealItem.class) public class BoneMealItemMixin { private static final MutableBlockPos bclib_BLOCK_POS = new MutableBlockPos(); @@ -139,7 +135,7 @@ public class BoneMealItemMixin { Block terrain = BonemealAPI.getSpreadable(state.getBlock()); if (center.is(terrain)) { if (haveSameProperties(state, center)) { - for (Property property: center.getProperties()) { + for (Property property : center.getProperties()) { state = state.setValue(property, center.getValue(property)); } } diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index cffd3b7a..eaf365c0 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -1,10 +1,5 @@ package ru.bclib.mixin.common; -import java.io.File; -import java.util.List; -import java.util.concurrent.Executor; -import java.util.function.Supplier; - import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -27,6 +22,11 @@ import ru.bclib.api.DataFixerAPI2; import ru.bclib.api.WorldDataAPI; import ru.bclib.config.SessionConfig; +import java.io.File; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.function.Supplier; + @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level { private static String bclib_lastWorld = null; diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index e819029b..c9958888 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -44,7 +44,7 @@ public class BaseBlockEntities { public static Block[] getFurnaces() { return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static boolean registerSpecialBlock(Block block) { if (block instanceof BaseChestBlock) { BaseBlockEntities.CHEST.registerBlock(block); @@ -62,7 +62,7 @@ public class BaseBlockEntities { BaseBlockEntities.FURNACE.registerBlock(block); return true; } - + return false; } } diff --git a/src/main/java/ru/bclib/util/JsonFactory.java b/src/main/java/ru/bclib/util/JsonFactory.java index 07ddc606..d856ed78 100644 --- a/src/main/java/ru/bclib/util/JsonFactory.java +++ b/src/main/java/ru/bclib/util/JsonFactory.java @@ -52,6 +52,7 @@ public class JsonFactory { /** * Loads {@link JsonObject} from resource location using Minecraft resource manager. Can be used to load JSON from resourcepacks and resources. + * * @param location {@link ResourceLocation} to JSON file * @return {@link JsonObject} */ @@ -70,7 +71,8 @@ public class JsonFactory { stream.close(); } } - catch (IOException ex) {} + catch (IOException ex) { + } return obj; } diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java index 9caf94a4..d21df3ff 100644 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -1,11 +1,7 @@ package ru.bclib.util; -import java.util.Map; -import java.util.Set; - import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; @@ -14,24 +10,27 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; +import java.util.Map; +import java.util.Set; + /** * Utility functions to manage Minecraft Tags */ public class TagHelper { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); - + /** * Adds one Tag to multiple Blocks. - * + *

    * Example: *

    {@code  Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
     	 * TagHelper.addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);}
    - * + *

    * The call will reserve the Tag. The Tag is added to the blocks once * {@link #apply(String, Map)} was executed. * - * @param tag The new Tag + * @param tag The new Tag * @param blocks One or more blocks that should receive the Tag. */ public static void addTag(Tag.Named tag, Block... blocks) { @@ -44,18 +43,18 @@ public class TagHelper { } } } - + /** * Adds one Tag to multiple Items. - * + *

    * Example: *

    {@code  Tag.Named METALS = makeBlockTag("mymod", "metals");
     	 * TagHelper.addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);}
    - * + *

    * The call will reserve the Tag. The Tag is added to the items once * {@link #apply(String, Map)} was executed. * - * @param tag The new Tag + * @param tag The new Tag * @param items One or more item that should receive the Tag. */ public static void addTag(Tag.Named tag, ItemLike... items) { @@ -68,12 +67,12 @@ public class TagHelper { } } } - + /** * Adds multiple Tags to one Item. - * + *

    * The call will reserve the Tags. The Tags are added to the Item once - * * {@link #apply(String, Map)} was executed. + * * {@link #apply(String, Map)} was executed. * * @param item The Item that will receive all Tags * @param tags One or more Tags @@ -84,15 +83,15 @@ public class TagHelper { addTag(tag, item); } } - + /** * Adds multiple Tags to one Block. - * + *

    * The call will reserve the Tags. The Tags are added to the Block once - * * {@link #apply(String, Map)} was executed. + * * {@link #apply(String, Map)} was executed. * * @param block The Block that will receive all Tags - * @param tags One or more Tags + * @param tags One or more Tags */ @SafeVarargs public static void addTags(Block block, Tag.Named... tags) { @@ -100,28 +99,27 @@ public class TagHelper { addTag(tag, block); } } - + /** * Adds all {@code ids} to the {@code builder}. + * * @param builder * @param ids - * * @return The Builder passed as {@code builder}. */ public static Tag.Builder apply(Tag.Builder builder, Set ids) { ids.forEach(value -> builder.addElement(value, "Better End Code")); return builder; } - + /** * Automatically called in {@link net.minecraft.tags.TagLoader#loadAndBuild(ResourceManager)}. - * + *

    * In most cases there is no need to call this Method manually. * * @param directory The name of the Tag-directory. Should be either "tags/blocks" or - * "tags/items". - * @param tagsMap The map that will hold the registered Tags - * + * "tags/items". + * @param tagsMap The map that will hold the registered Tags * @return The {@code tagsMap} Parameter. */ public static Map apply(String directory, Map tagsMap) { From 9728dc8dc36d56be0d813fb2a7b902632e8d5c41 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 22:38:27 +0200 Subject: [PATCH 0057/1033] Use version String for DataFixer --- src/main/java/ru/bclib/api/DataFixerAPI2.java | 235 +++++++++++++----- 1 file changed, 166 insertions(+), 69 deletions(-) diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java index 3863ea49..5046dee7 100644 --- a/src/main/java/ru/bclib/api/DataFixerAPI2.java +++ b/src/main/java/ru/bclib/api/DataFixerAPI2.java @@ -6,7 +6,6 @@ import net.minecraft.nbt.NbtIo; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.RegionFile; import org.jetbrains.annotations.NotNull; -import ru.bclib.BCLib; import ru.bclib.config.Configs; import ru.bclib.config.PathConfig; import ru.bclib.config.SessionConfig; @@ -19,9 +18,12 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; public class DataFixerAPI2 { @@ -41,49 +43,52 @@ public class DataFixerAPI2 { } List regions = getAllRegions(dir, null); - regions.parallelStream().forEach((file) -> { - try { - LOGGER.info("Inspecting " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), true); - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos)) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - // } - input.close(); + regions.parallelStream() + .forEach((file) -> { + try { + LOGGER.info("Inspecting " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + ChunkPos pos = new ChunkPos(x, z); + changed[0] = false; + if (region.hasChunk(pos)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + // } + input.close(); - ListTag tileEntities = root.getCompound("Level").getList("TileEntities", 10); - fixItemArrayWithID(tileEntities, changed, data, true); + ListTag tileEntities = root.getCompound("Level") + .getList("TileEntities", 10); + fixItemArrayWithID(tileEntities, changed, data, true); - ListTag sections = root.getCompound("Level").getList("Sections", 10); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", 10); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); - }); - }); - if (changed[0]) { - LOGGER.warning("Writing '{}': {}/{}", file, x, z); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - }); + ListTag sections = root.getCompound("Level") + .getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); + }); + }); + if (changed[0]) { + LOGGER.warning("Writing '{}': {}/{}", file, x, z); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + } + } + } + } + region.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + }); data.markApplied(); } @@ -110,16 +115,59 @@ public class DataFixerAPI2 { if (file.isDirectory()) { getAllRegions(file, list); } - else if (file.isFile() && file.getName().endsWith(".mca")) { + else if (file.isFile() && file.getName() + .endsWith(".mca")) { list.add(file); } } return list; } + /** + * Get mod version from string. String should be in format: %d.%d.%d + * + * @param version - {@link String} mod version. + * @return int mod version. + */ + public static int getModVersion(String version) { + if (version.isEmpty()) { + return 0; + } + try { + int res = 0; + final String semanticVersionPattern = "\\D*(\\d+)\\D*\\.\\D*(\\d+)\\D*\\.\\D*(\\d+)\\D*"; + final Matcher matcher = Pattern.compile(semanticVersionPattern) + .matcher(version); + if (matcher.find()) { + if (matcher.groupCount() > 0) res = Integer.parseInt(matcher.group(0)) << 20; + if (matcher.groupCount() > 1) res |= Integer.parseInt(matcher.group(1)) << 12; + if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(2)); + } + + return res; + } + catch (Exception e) { + return 0; + } + } + + /** + * Get mod version from integer. String will be in format %d.%d.%d + * + * @param version - mod version in integer form. + * @return {@link String} mod version. + */ + public static String getModVersion(int version) { + int a = (version >> 20) & 0xFF; + int b = (version >> 12) & 0xFF; + int c = version & 0xFFF; + return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); + } + public abstract static class Patch { private static List ALL = new ArrayList<>(10); private final int level; + private final String version; @NotNull private final String modID; @@ -136,6 +184,22 @@ public class DataFixerAPI2 { ALL.add(patch.get()); } + /** + * Returns the highest Patch-Version that is available for the given mod. If no patches were + * registerd for the mod, this will return 0.0.0 + * + * @param modID The ID of the mod you want to query + * @return The highest Patch-Version that was found + */ + public static String maxPatchVersion(@NotNull String modID) { + return ALL.stream() + .filter(p -> p.getModID() + .equals(modID)) + .map(p -> p.version) + .reduce((p, c) -> c) + .orElse("0.0.0"); + } + /** * Returns the highest patch-level that is available for the given mod. If no patches were * registerd for the mod, this will return 0 @@ -144,7 +208,12 @@ public class DataFixerAPI2 { * @return The highest Patch-Level that was found */ public static int maxPatchLevel(@NotNull String modID) { - return ALL.stream().filter(p -> p.getModID().equals(modID)).mapToInt(p -> p.level).max().orElse(0); + return ALL.stream() + .filter(p -> p.getModID() + .equals(modID)) + .mapToInt(p -> p.level) + .max() + .orElse(0); } /** @@ -153,38 +222,50 @@ public class DataFixerAPI2 { * Performs some sanity checks on the values and might throw a #RuntimeException if any * inconsistencies are found. * - * @param modID The ID of the Mod you want to register a patch for. This should be your - * ModID only. The ModID can not be {@code null} or an empty String. - * @param level The level of the Patch. This needs to be a non-zero positive value. - * Developers are responsible for registering their patches in the correct - * order (with increasing levels). You are not allowed to register a new - * Patch with a Patch-level lower or equal than - * {@link Patch#maxPatchLevel(String)} + * @param modID The ID of the Mod you want to register a patch for. This should be your + * ModID only. The ModID can not be {@code null} or an empty String. + * @param version The mod-version that introduces the patch. This needs Semantic-Version String + * like x.x.x. Developers are responsible for registering their patches in the correct + * order (with increasing versions). You are not allowed to register a new + * Patch with a version lower or equal than + * {@link Patch#maxPatchVersion(String)} */ - protected Patch(@NotNull String modID, int level) { + protected Patch(@NotNull String modID, String version) { //Patchlevels need to be unique and registered in ascending order if (modID == null || "".equals(modID)) { throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); } - if (!ALL.stream().filter(p -> p.getModID().equals(modID)).noneMatch(p -> p.getLevel() >= level) || level <= 0) { + + if (version == null || "".equals(version)) { + throw new RuntimeException("Invalid Mod-Version"); + } + + this.version = version; + this.level = getModVersion(version); + if (!ALL.stream() + .filter(p -> p.getModID() + .equals(modID) + ) + .noneMatch(p -> p.getLevel() >= this.level) || this.level <= 0) { throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); } - - BCLib.LOGGER.info("Creating Patchlevel {} ({}, {})", level, ALL, ALL.stream().noneMatch(p -> p.getLevel() >= level)); - this.level = level; this.modID = modID; } @Override public String toString() { - return "Patch{" + "level=" + getModID() + ":" + getLevel() + '}'; + return "Patch{" + getModID() + ':' + getVersion() + ':' + getLevel() + '}'; } final public int getLevel() { return level; } + final public String getVersion() { + return version; + } + /** * The Mod-ID that registered this Patch * @@ -229,19 +310,25 @@ public class DataFixerAPI2 { private MigrationData(PathConfig config) { this.config = config; - this.mods = Collections.unmodifiableSet(Patch.getALL().stream().map(p -> p.modID).collect(Collectors.toSet())); + this.mods = Collections.unmodifiableSet(Patch.getALL() + .stream() + .map(p -> p.modID) + .collect(Collectors.toSet())); HashMap replacements = new HashMap(); for (String modID : mods) { - Patch.getALL().stream().filter(p -> p.modID.equals(modID)).forEach(patch -> { - if (currentPatchLevel(modID) < patch.level) { - replacements.putAll(patch.getIDReplacements()); - LOGGER.info("Applying " + patch); - } - else { - LOGGER.info("Ignoring " + patch); - } - }); + Patch.getALL() + .stream() + .filter(p -> p.modID.equals(modID)) + .forEach(patch -> { + if (currentPatchLevel(modID) < patch.level) { + replacements.putAll(patch.getIDReplacements()); + LOGGER.info("Applying " + patch); + } + else { + LOGGER.info("Ignoring " + patch); + } + }); } this.idReplacements = Collections.unmodifiableMap(replacements); @@ -249,14 +336,24 @@ public class DataFixerAPI2 { final public void markApplied() { for (String modID : mods) { - LOGGER.info("Updating Patch-Level for '{}' from {} to {} -> {}", modID, currentPatchLevel(modID), Patch.maxPatchLevel(modID), config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID))); + LOGGER.info( + "Updating Patch-Level for '{}' from {} to {}", + modID, + currentPatchLevel(modID), + Patch.maxPatchLevel(modID) + ); + config.setString(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchVersion(modID)); } config.saveChanges(); } + public String currentPatchVersion(@NotNull String modID) { + return config.getString(Configs.MAIN_PATCH_CATEGORY, modID, "0.0.0"); + } + public int currentPatchLevel(@NotNull String modID) { - return config.getInt(Configs.MAIN_PATCH_CATEGORY, modID, 0); + return getModVersion(currentPatchVersion(modID)); } public boolean hasAnyFixes() { From 5cc430de6f921499fa15a2956be062c74eb9059b Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 23:03:43 +0200 Subject: [PATCH 0058/1033] Fixed regex api use --- src/main/java/ru/bclib/api/DataFixerAPI2.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java index 5046dee7..4f68809d 100644 --- a/src/main/java/ru/bclib/api/DataFixerAPI2.java +++ b/src/main/java/ru/bclib/api/DataFixerAPI2.java @@ -30,7 +30,7 @@ public class DataFixerAPI2 { private static final Logger LOGGER = new Logger("DataFixerAPI"); public static void fixData(SessionConfig config) { - if (true || !Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { + if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { LOGGER.info("World Patches are disabled"); return; } @@ -135,13 +135,13 @@ public class DataFixerAPI2 { } try { int res = 0; - final String semanticVersionPattern = "\\D*(\\d+)\\D*\\.\\D*(\\d+)\\D*\\.\\D*(\\d+)\\D*"; + final String semanticVersionPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\D*"; final Matcher matcher = Pattern.compile(semanticVersionPattern) .matcher(version); if (matcher.find()) { - if (matcher.groupCount() > 0) res = Integer.parseInt(matcher.group(0)) << 20; - if (matcher.groupCount() > 1) res |= Integer.parseInt(matcher.group(1)) << 12; - if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(2)); + if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 20; + if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 12; + if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0xFFF; } return res; From c6afa7452903d8c76af3609bfc9a96ee59b8a9ab Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 00:10:00 +0300 Subject: [PATCH 0059/1033] Code style fix, interface rename, custom item getter --- src/main/java/ru/bclib/api/BiomeAPI.java | 19 +- src/main/java/ru/bclib/api/DataFixerAPI2.java | 27 +- .../blockentities/BaseBarrelBlockEntity.java | 11 +- .../java/ru/bclib/blocks/BaseAnvilBlock.java | 13 +- .../java/ru/bclib/blocks/BaseBarrelBlock.java | 4 +- src/main/java/ru/bclib/blocks/BaseBlock.java | 4 +- .../java/ru/bclib/blocks/BaseButtonBlock.java | 9 +- .../java/ru/bclib/blocks/BaseChainBlock.java | 6 +- .../java/ru/bclib/blocks/BaseChestBlock.java | 4 +- .../ru/bclib/blocks/BaseComposterBlock.java | 4 +- .../bclib/blocks/BaseCraftingTableBlock.java | 4 +- .../java/ru/bclib/blocks/BaseCropBlock.java | 7 +- .../java/ru/bclib/blocks/BaseDoorBlock.java | 11 +- .../ru/bclib/blocks/BaseDoublePlantBlock.java | 30 +- .../java/ru/bclib/blocks/BaseFenceBlock.java | 22 +- .../ru/bclib/blocks/BaseFurnaceBlock.java | 12 +- .../java/ru/bclib/blocks/BaseGateBlock.java | 14 +- .../java/ru/bclib/blocks/BaseLadderBlock.java | 6 +- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 20 +- .../ru/bclib/blocks/BaseMetalBarsBlock.java | 29 +- .../java/ru/bclib/blocks/BaseOreBlock.java | 10 +- .../java/ru/bclib/blocks/BasePlantBlock.java | 30 +- .../bclib/blocks/BasePlantWithAgeBlock.java | 7 +- .../bclib/blocks/BasePressurePlateBlock.java | 4 +- .../bclib/blocks/BaseRotatedPillarBlock.java | 4 +- .../java/ru/bclib/blocks/BaseSignBlock.java | 41 +- .../java/ru/bclib/blocks/BaseSlabBlock.java | 9 +- .../java/ru/bclib/blocks/BaseStairsBlock.java | 4 +- .../bclib/blocks/BaseStripableLogBlock.java | 6 +- .../ru/bclib/blocks/BaseTerrainBlock.java | 15 +- .../ru/bclib/blocks/BaseTrapdoorBlock.java | 25 +- .../blocks/BaseUnderwaterWallPlantBlock.java | 13 +- .../java/ru/bclib/blocks/BaseVineBlock.java | 16 +- .../java/ru/bclib/blocks/BaseWallBlock.java | 50 +- .../ru/bclib/blocks/BaseWallPlantBlock.java | 24 +- .../bclib/blocks/BaseWeightedPlateBlock.java | 9 +- .../ru/bclib/blocks/FeatureSaplingBlock.java | 35 +- .../ru/bclib/blocks/SimpleLeavesBlock.java | 23 +- .../java/ru/bclib/blocks/StalactiteBlock.java | 14 +- .../ru/bclib/blocks/StripableBarkBlock.java | 6 +- .../ru/bclib/blocks/TripleTerrainBlock.java | 12 +- .../ru/bclib/blocks/UnderwaterPlantBlock.java | 30 +- .../blocks/UnderwaterPlantWithAgeBlock.java | 7 +- .../ru/bclib/blocks/UpDownPlantBlock.java | 15 +- .../ru/bclib/blocks/WallMushroomBlock.java | 9 +- .../java/ru/bclib/client/BCLibClient.java | 12 +- .../bclib/client/gui/BlockSignEditScreen.java | 74 +- .../client/models/BaseChestBlockModel.java | 58 +- .../ru/bclib/client/models/ModelsHelper.java | 7 +- .../bclib/client/models/PatternsHelper.java | 3 +- .../render/BaseChestBlockEntityRenderer.java | 65 +- .../render/BaseSignBlockEntityRenderer.java | 41 +- .../ru/bclib/client/sound/BlockSounds.java | 10 +- .../java/ru/bclib/config/ConfigWriter.java | 5 +- .../BlockModelGetter.java} | 6 +- ...Provider.java => ColorProviderGetter.java} | 2 +- .../ru/bclib/interfaces/CustomItemGetter.java | 15 + .../ru/bclib/interfaces/ISpetialItem.java | 7 - .../ItemModelGetter.java} | 5 +- .../{IPostInit.java => PostInitable.java} | 2 +- ...enderTyped.java => RenderLayerGetter.java} | 2 +- .../java/ru/bclib/items/BaseAnvilItem.java | 6 +- .../java/ru/bclib/items/BaseArmorItem.java | 30 +- .../java/ru/bclib/items/BaseBucketItem.java | 4 +- .../java/ru/bclib/items/BaseDiscItem.java | 4 +- .../java/ru/bclib/items/BaseSpawnEggItem.java | 4 +- .../ru/bclib/items/ModelProviderItem.java | 4 +- .../java/ru/bclib/items/tool/BaseAxeItem.java | 4 +- .../java/ru/bclib/items/tool/BaseHoeItem.java | 4 +- .../ru/bclib/items/tool/BasePickaxeItem.java | 9 +- .../ru/bclib/items/tool/BaseShovelItem.java | 9 +- .../ru/bclib/items/tool/BaseSwordItem.java | 4 +- .../client/EnchantingTableBlockMixin.java | 10 +- .../ru/bclib/mixin/client/MinecraftMixin.java | 6 +- .../bclib/mixin/client/ModelBakeryMixin.java | 35 +- .../bclib/mixin/client/TextureAtlasMixin.java | 21 +- .../bclib/mixin/common/BoneMealItemMixin.java | 3 +- .../mixin/common/EnchantmentMenuMixin.java | 9 +- .../java/ru/bclib/noise/OpenSimplexNoise.java | 367 +++++++- .../java/ru/bclib/noise/VoronoiNoise.java | 12 +- .../ru/bclib/recipes/CraftingRecipes.java | 84 +- .../java/ru/bclib/recipes/FurnaceRecipe.java | 36 +- .../java/ru/bclib/recipes/GridRecipe.java | 9 +- .../ru/bclib/registry/BaseBlockEntities.java | 42 +- .../java/ru/bclib/registry/BaseRegistry.java | 5 +- .../ru/bclib/registry/BlocksRegistry.java | 24 +- .../java/ru/bclib/registry/ItemsRegistry.java | 10 +- .../bclib/sdf/operator/SDFRadialNoiseMap.java | 5 +- .../ru/bclib/sdf/primitive/SDFCappedCone.java | 6 +- .../java/ru/bclib/server/BCLibServer.java | 6 +- src/main/java/ru/bclib/util/SplineHelper.java | 10 +- .../java/ru/bclib/util/StructureHelper.java | 43 +- .../java/ru/bclib/world/biomes/BCLBiome.java | 6 +- .../ru/bclib/world/biomes/BCLBiomeDef.java | 34 +- .../ru/bclib/world/features/BCLFeature.java | 44 +- .../world/features/NBTStructureFeature.java | 19 +- .../DestructionStructureProcessor.java | 6 +- .../processors/TerrainStructureProcessor.java | 5 +- .../world/structures/BCLStructureFeature.java | 5 +- .../surface/DoubleBlockSurfaceBuilder.java | 16 +- .../assets/bclib/models/block/chest_item.json | 350 ++++---- .../assets/bclib/models/block/ladder.json | 828 +++++++++--------- .../assets/bclib/models/block/path.json | 97 +- .../bclib/models/block/sided_door_bottom.json | 85 +- .../models/block/sided_door_bottom_rh.json | 85 +- .../bclib/models/block/sided_door_top.json | 85 +- .../bclib/models/block/sided_door_top_rh.json | 85 +- .../bclib/models/block/sided_trapdoor.json | 101 ++- .../assets/bclib/models/block/tint_cube.json | 86 +- .../assets/bclib/patterns/block/anvil.json | 273 +++++- .../bclib/patterns/block/bars_post.json | 76 +- .../bclib/patterns/block/bars_side.json | 77 +- .../assets/bclib/patterns/block/block.json | 8 +- .../assets/bclib/patterns/block/button.json | 8 +- .../bclib/patterns/block/button_pressed.json | 8 +- .../bclib/patterns/block/composter.json | 150 +++- .../bclib/patterns/block/cross_shaded.json | 88 +- .../bclib/patterns/block/furnace_glow.json | 77 +- .../assets/bclib/patterns/block/path.json | 13 +- .../patterns/block/pressure_plate_down.json | 8 +- .../patterns/block/pressure_plate_up.json | 8 +- .../assets/bclib/patterns/block/slab.json | 12 +- .../assets/bclib/patterns/block/stairs.json | 12 +- .../bclib/patterns/block/stairs_inner.json | 12 +- .../bclib/patterns/block/stairs_outer.json | 12 +- .../bclib/patterns/block/wall_inventory.json | 8 +- .../bclib/patterns/block/wall_post.json | 8 +- .../bclib/patterns/block/wall_side.json | 8 +- .../bclib/patterns/block/wall_side_tall.json | 8 +- .../bclib/patterns/item/pattern_button.json | 8 +- .../patterns/item/pattern_item_spawn_egg.json | 2 +- .../bclib/patterns/item/pattern_wall.json | 8 +- src/main/resources/bclib.mixins.client.json | 2 +- src/main/resources/fabric.mod.json | 4 - 134 files changed, 3404 insertions(+), 1244 deletions(-) rename src/main/java/ru/bclib/{client/models/BlockModelProvider.java => interfaces/BlockModelGetter.java} (90%) rename src/main/java/ru/bclib/interfaces/{IColorProvider.java => ColorProviderGetter.java} (83%) create mode 100644 src/main/java/ru/bclib/interfaces/CustomItemGetter.java delete mode 100644 src/main/java/ru/bclib/interfaces/ISpetialItem.java rename src/main/java/ru/bclib/{client/models/ItemModelProvider.java => interfaces/ItemModelGetter.java} (76%) rename src/main/java/ru/bclib/interfaces/{IPostInit.java => PostInitable.java} (60%) rename src/main/java/ru/bclib/interfaces/{IRenderTyped.java => RenderLayerGetter.java} (75%) diff --git a/src/main/java/ru/bclib/api/BiomeAPI.java b/src/main/java/ru/bclib/api/BiomeAPI.java index a63db6fd..81026c3d 100644 --- a/src/main/java/ru/bclib/api/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/BiomeAPI.java @@ -24,7 +24,12 @@ public class BiomeAPI { * Empty biome used as default value if requested biome doesn't exist or linked. Shouldn't be registered anywhere to prevent bugs. * Have {@code Biomes.THE_VOID} as the reference biome. */ - public static final BCLBiome EMPTY_BIOME = new BCLBiome(Biomes.THE_VOID.location(), BuiltinRegistries.BIOME.get(Biomes.THE_VOID), 1, 0); + public static final BCLBiome EMPTY_BIOME = new BCLBiome( + Biomes.THE_VOID.location(), + BuiltinRegistries.BIOME.get(Biomes.THE_VOID), + 1, + 0 + ); private static final HashMap ID_MAP = Maps.newHashMap(); private static final HashMap CLIENT = Maps.newHashMap(); @@ -55,7 +60,13 @@ public class BiomeAPI { public static void addNetherBiomeToFabricApi(BCLBiome biome) { ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); Random random = new Random(biome.getID().toString().hashCode()); - ClimateParameters parameters = new ClimateParameters(MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random), MHelper.randRange(-2F, 2F, random)); + ClimateParameters parameters = new ClimateParameters( + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random) + ); InternalBiomeData.addNetherBiome(key, parameters); } @@ -106,7 +117,9 @@ public class BiomeAPI { BCLBiome endBiome = CLIENT.get(biome); if (endBiome == null) { Minecraft minecraft = Minecraft.getInstance(); - ResourceLocation id = minecraft.level.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(biome); + ResourceLocation id = minecraft.level.registryAccess() + .registryOrThrow(Registry.BIOME_REGISTRY) + .getKey(biome); endBiome = id == null ? EMPTY_BIOME : ID_MAP.getOrDefault(id, EMPTY_BIOME); CLIENT.put(biome, endBiome); } diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java index 3863ea49..fa660ead 100644 --- a/src/main/java/ru/bclib/api/DataFixerAPI2.java +++ b/src/main/java/ru/bclib/api/DataFixerAPI2.java @@ -166,12 +166,20 @@ public class DataFixerAPI2 { if (modID == null || "".equals(modID)) { throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); } - if (!ALL.stream().filter(p -> p.getModID().equals(modID)).noneMatch(p -> p.getLevel() >= level) || level <= 0) { - throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); + if (!ALL.stream() + .filter(p -> p.getModID().equals(modID)) + .noneMatch(p -> p.getLevel() >= level) || level <= 0) { + throw new RuntimeException( + "[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); } - BCLib.LOGGER.info("Creating Patchlevel {} ({}, {})", level, ALL, ALL.stream().noneMatch(p -> p.getLevel() >= level)); + BCLib.LOGGER.info( + "Creating Patchlevel {} ({}, {})", + level, + ALL, + ALL.stream().noneMatch(p -> p.getLevel() >= level) + ); this.level = level; this.modID = modID; } @@ -229,7 +237,10 @@ public class DataFixerAPI2 { private MigrationData(PathConfig config) { this.config = config; - this.mods = Collections.unmodifiableSet(Patch.getALL().stream().map(p -> p.modID).collect(Collectors.toSet())); + this.mods = Collections.unmodifiableSet(Patch.getALL() + .stream() + .map(p -> p.modID) + .collect(Collectors.toSet())); HashMap replacements = new HashMap(); for (String modID : mods) { @@ -249,7 +260,13 @@ public class DataFixerAPI2 { final public void markApplied() { for (String modID : mods) { - LOGGER.info("Updating Patch-Level for '{}' from {} to {} -> {}", modID, currentPatchLevel(modID), Patch.maxPatchLevel(modID), config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID))); + LOGGER.info( + "Updating Patch-Level for '{}' from {} to {} -> {}", + modID, + currentPatchLevel(modID), + Patch.maxPatchLevel(modID), + config.setInt(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchLevel(modID)) + ); } config.saveChanges(); diff --git a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java index 571fb407..314503d4 100644 --- a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java @@ -134,7 +134,16 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { double d = (double) this.worldPosition.getX() + 0.5D + (double) vec3i.getX() / 2.0D; double e = (double) this.worldPosition.getY() + 0.5D + (double) vec3i.getY() / 2.0D; double f = (double) this.worldPosition.getZ() + 0.5D + (double) vec3i.getZ() / 2.0D; - level.playSound(null, d, e, f, soundEvent, SoundSource.BLOCKS, 0.5F, this.level.random.nextFloat() * 0.1F + 0.9F); + level.playSound( + null, + d, + e, + f, + soundEvent, + SoundSource.BLOCKS, + 0.5F, + this.level.random.nextFloat() * 0.1F + 0.9F + ); } } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 192624c2..69283002 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -4,10 +4,12 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.AnvilBlock; @@ -20,16 +22,18 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.CustomItemGetter; import ru.bclib.items.BaseAnvilItem; +import ru.bclib.registry.BlocksRegistry; import java.util.List; import java.util.Map; import java.util.Optional; -public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider { +public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelGetter, CustomItemGetter { public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; public BaseAnvilBlock(MaterialColor color) { @@ -91,4 +95,9 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro registerBlockModel(stateId, modelLocation, blockState, modelCache); return ModelsHelper.createFacingModel(modelLocation, blockState.getValue(FACING), false, false); } + + @Override + public BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings) { + return new BaseAnvilItem(this, settings); + } } diff --git a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java index cde83356..baca4bdb 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java @@ -28,9 +28,9 @@ import net.minecraft.world.phys.BlockHitResult; import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseBarrelBlockEntity; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import ru.bclib.registry.BaseBlockEntities; import java.util.List; @@ -38,7 +38,7 @@ import java.util.Map; import java.util.Optional; import java.util.Random; -public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { +public class BaseBarrelBlock extends BarrelBlock implements BlockModelGetter { public BaseBarrelBlock(Block source) { super(FabricBlockSettings.copyOf(source).noOcclusion()); } diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index 0f17e517..da796ab1 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -8,7 +8,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; -import ru.bclib.client.models.BlockModelProvider; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; @@ -23,7 +23,7 @@ import java.util.function.Consumer; *

  • Automatically create an Item-Model from the Block-Model
  • *
*/ -public class BaseBlock extends Block implements BlockModelProvider { +public class BaseBlock extends Block implements BlockModelGetter { /** * Creates a new Block with the passed properties * diff --git a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java index 5fbd0d2c..5afd08e1 100644 --- a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java @@ -15,16 +15,16 @@ import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { +public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelGetter { private final Block parent; @@ -51,7 +51,10 @@ public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelP @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = blockState.getValue(POWERED) ? PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON_PRESSED, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId); + Optional pattern = blockState.getValue(POWERED) ? PatternsHelper.createJson( + BasePatterns.BLOCK_BUTTON_PRESSED, + parentId + ) : PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId); return ModelsHelper.fromPattern(pattern); } diff --git a/src/main/java/ru/bclib/blocks/BaseChainBlock.java b/src/main/java/ru/bclib/blocks/BaseChainBlock.java index 4b3cc0ef..97257e9a 100644 --- a/src/main/java/ru/bclib/blocks/BaseChainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChainBlock.java @@ -15,18 +15,18 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped { +public class BaseChainBlock extends ChainBlock implements BlockModelGetter, RenderLayerGetter { public BaseChainBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); } diff --git a/src/main/java/ru/bclib/blocks/BaseChestBlock.java b/src/main/java/ru/bclib/blocks/BaseChestBlock.java index a38d3b28..94f7c722 100644 --- a/src/main/java/ru/bclib/blocks/BaseChestBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChestBlock.java @@ -15,15 +15,15 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.Optional; -public class BaseChestBlock extends ChestBlock implements BlockModelProvider { +public class BaseChestBlock extends ChestBlock implements BlockModelGetter { private final Block parent; public BaseChestBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java index b7735daf..44ee2ddd 100644 --- a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java @@ -13,17 +13,17 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { +public class BaseComposterBlock extends ComposterBlock implements BlockModelGetter { public BaseComposterBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } diff --git a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java index f4718e40..5addddc0 100644 --- a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java @@ -12,16 +12,16 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; -public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { +public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelGetter { public BaseCraftingTableBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } diff --git a/src/main/java/ru/bclib/blocks/BaseCropBlock.java b/src/main/java/ru/bclib/blocks/BaseCropBlock.java index ec0ce04b..18a16c06 100644 --- a/src/main/java/ru/bclib/blocks/BaseCropBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCropBlock.java @@ -38,7 +38,12 @@ public class BaseCropBlock extends BasePlantBlock { private final Item drop; public BaseCropBlock(Item drop, Block... terrain) { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.HOES).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.HOES) + .breakByHand(true) + .sound(SoundType.GRASS) + .randomTicks() + .noCollission()); this.drop = drop; this.terrain = terrain; this.registerDefaultState(defaultBlockState().setValue(AGE, 0)); diff --git a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java index c903f642..540a5638 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java @@ -18,18 +18,18 @@ import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModelProvider { +public class BaseDoorBlock extends DoorBlock implements RenderLayerGetter, BlockModelGetter { public BaseDoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion()); } @@ -114,7 +114,10 @@ public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModel } break; } - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + doorType); + ResourceLocation modelId = new ResourceLocation( + stateId.getNamespace(), + "block/" + stateId.getPath() + "_" + doorType + ); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); } diff --git a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index 05bf1f15..837fcee2 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -31,25 +31,34 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.util.BlocksHelper; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { +public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); public static final IntegerProperty ROTATION = BlockProperties.ROTATION; public static final BooleanProperty TOP = BooleanProperty.create("top"); public BaseDoublePlantBlock() { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } public BaseDoublePlantBlock(int light) { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).lightLevel((state) -> state.getValue(TOP) ? light : 0).noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .lightLevel((state) -> state.getValue(TOP) ? light : 0) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } @@ -101,7 +110,10 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I } ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -126,7 +138,13 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements I @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); + ItemEntity item = new ItemEntity( + world, + pos.getX() + 0.5, + pos.getY() + 0.5, + pos.getZ() + 0.5, + new ItemStack(this) + ); world.addFreshEntity(item); } diff --git a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java index 7c721437..fecd6ecb 100644 --- a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java @@ -15,17 +15,17 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { +public class BaseFenceBlock extends FenceBlock implements BlockModelGetter { private final Block parent; public BaseFenceBlock(Block source) { @@ -72,9 +72,21 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideId) + .setCondition(state -> state.getValue(EAST)) + .setTransformation(BlockModelRotation.X0_Y90.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(SOUTH)) + .setTransformation(BlockModelRotation.X0_Y180.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(WEST)) + .setTransformation(BlockModelRotation.X0_Y270.getRotation()) + .setUVLock(true) + .add(); builder.part(postId).add(); return builder.build(); diff --git a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index ac6624ba..062f7ee5 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -26,18 +26,18 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseFurnaceBlockEntity; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, IRenderTyped { +public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelGetter, RenderLayerGetter { public BaseFurnaceBlock(Block source) { super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0)); } @@ -119,6 +119,10 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider @Nullable protected static BlockEntityTicker createFurnaceTicker(Level level, BlockEntityType blockEntityType, BlockEntityType blockEntityType2) { - return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick); + return level.isClientSide ? null : createTickerHelper( + blockEntityType, + blockEntityType2, + AbstractFurnaceBlockEntity::serverTick + ); } } diff --git a/src/main/java/ru/bclib/blocks/BaseGateBlock.java b/src/main/java/ru/bclib/blocks/BaseGateBlock.java index 7b239a7e..c2e6a1c1 100644 --- a/src/main/java/ru/bclib/blocks/BaseGateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseGateBlock.java @@ -14,16 +14,16 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { +public class BaseGateBlock extends FenceGateBlock implements BlockModelGetter { private final Block parent; public BaseGateBlock(Block source) { @@ -51,10 +51,16 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider ResourceLocation parentId = Registry.BLOCK.getKey(parent); Optional pattern; if (inWall) { - pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN_WALL, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); + pattern = isOpen ? PatternsHelper.createJson( + BasePatterns.BLOCK_GATE_OPEN_WALL, + parentId + ) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); } else { - pattern = isOpen ? PatternsHelper.createJson(BasePatterns.BLOCK_GATE_OPEN, parentId) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId); + pattern = isOpen ? PatternsHelper.createJson( + BasePatterns.BLOCK_GATE_OPEN, + parentId + ) : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId); } return ModelsHelper.fromPattern(pattern); } diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index d5020846..404e6e28 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -28,18 +28,18 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.util.BlocksHelper; import java.util.Map; import java.util.Optional; @SuppressWarnings("deprecation") -public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider { +public class BaseLadderBlock extends BaseBlockNotFull implements RenderLayerGetter, BlockModelGetter { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; protected static final VoxelShape EAST_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 3bbcb5aa..d89887b5 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -15,20 +15,27 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.util.MHelper; import java.util.Collections; import java.util.List; import java.util.function.Consumer; -public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { +public class BaseLeavesBlock extends LeavesBlock implements BlockModelGetter, RenderLayerGetter { private final Block sapling; private static FabricBlockSettings makeLeaves(MaterialColor color) { - return FabricBlockSettings.copyOf(Blocks.OAK_LEAVES).mapColor(color).breakByTool(FabricToolTags.HOES).breakByTool(FabricToolTags.SHEARS).breakByHand(true).allowsSpawning((state, world, pos, type) -> false).suffocates((state, world, pos) -> false).blockVision((state, world, pos) -> false); + return FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) + .mapColor(color) + .breakByTool(FabricToolTags.HOES) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .allowsSpawning((state, world, pos, type) -> false) + .suffocates((state, world, pos) -> false) + .blockVision((state, world, pos) -> false); } public BaseLeavesBlock(Block sapling, MaterialColor color, Consumer customizeProperties) { @@ -61,7 +68,10 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null) { - if (FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Collections.singletonList(new ItemStack(this)); } int fortune = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); diff --git a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java index d29ff46d..5ed2ecec 100644 --- a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java @@ -16,18 +16,18 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, IRenderTyped { +public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelGetter, RenderLayerGetter { public BaseMetalBarsBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion()); } @@ -81,11 +81,26 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi registerBlockModel(sideId, sideId, blockState, modelCache); ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - builder.part(postId).setCondition(state -> !state.getValue(NORTH) && !state.getValue(EAST) && !state.getValue(SOUTH) && !state.getValue(WEST)).add(); + builder.part(postId) + .setCondition(state -> !state.getValue(NORTH) && !state.getValue(EAST) && !state.getValue(SOUTH) && !state + .getValue(WEST)) + .add(); builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST)).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH)).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST)).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideId) + .setCondition(state -> state.getValue(EAST)) + .setTransformation(BlockModelRotation.X0_Y90.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(SOUTH)) + .setTransformation(BlockModelRotation.X0_Y180.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(WEST)) + .setTransformation(BlockModelRotation.X0_Y270.getRotation()) + .setUVLock(true) + .add(); return builder.build(); } diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index ebf88679..e5c17f15 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -16,19 +16,23 @@ import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import ru.bclib.client.models.BlockModelProvider; +import ru.bclib.interfaces.BlockModelGetter; import ru.bclib.util.MHelper; import java.util.Collections; import java.util.List; -public class BaseOreBlock extends OreBlock implements BlockModelProvider { +public class BaseOreBlock extends OreBlock implements BlockModelGetter { private final Item dropItem; private final int minCount; private final int maxCount; public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { - super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND).hardness(3F).resistance(9F).requiresCorrectToolForDrops().sound(SoundType.STONE), UniformInt.of(1, experience)); + super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) + .hardness(3F) + .resistance(9F) + .requiresCorrectToolForDrops() + .sound(SoundType.STONE), UniformInt.of(1, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index c7818a90..a9fe59fa 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -27,13 +27,13 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { +public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public BasePlantBlock() { @@ -45,11 +45,20 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender } public BasePlantBlock(boolean replaceable) { - super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); + super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } public BasePlantBlock(boolean replaceable, int light) { - super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission()); + super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.GRASS) + .noCollission()); } public BasePlantBlock(Properties settings) { @@ -88,7 +97,10 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -113,7 +125,13 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements IRender @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); + ItemEntity item = new ItemEntity( + world, + pos.getX() + 0.5, + pos.getY() + 0.5, + pos.getZ() + 0.5, + new ItemStack(this) + ); world.addFreshEntity(item); } } diff --git a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java index 89749c6e..4d8ce1b0 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java @@ -19,7 +19,12 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public BasePlantWithAgeBlock() { - this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).randomTicks().noCollission()); + this(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .randomTicks() + .noCollission()); } public BasePlantWithAgeBlock(Properties settings) { diff --git a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java index dd76e216..a7f834c4 100644 --- a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java @@ -14,16 +14,16 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { +public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelGetter { private final Block parent; public BasePressurePlateBlock(Sensitivity rule, Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java index d866c9d2..9eac0d81 100644 --- a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java @@ -12,16 +12,16 @@ import net.minecraft.world.level.block.RotatedPillarBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { +public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelGetter { public BaseRotatedPillarBlock(Properties settings) { super(settings); } diff --git a/src/main/java/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index 98ed4864..05ec9de3 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -2,6 +2,7 @@ package ru.bclib.blocks; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; @@ -13,6 +14,7 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; @@ -39,25 +41,34 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseSignBlockEntity; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ISpetialItem; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.CustomItemGetter; +import ru.bclib.registry.BlocksRegistry; import ru.bclib.util.BlocksHelper; import java.util.Collections; import java.util.List; @SuppressWarnings("deprecation") -public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem { +public class BaseSignBlock extends SignBlock implements BlockModelGetter, CustomItemGetter { public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); - private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] {Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D)}; + private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] { + Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), + Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), + Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), + Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D) + }; private final Block parent; public BaseSignBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(1.0F, 1.0F).noCollission().noOcclusion(), WoodType.OAK); - this.registerDefaultState(this.stateDefinition.any().setValue(ROTATION, 0).setValue(FLOOR, false).setValue(WATERLOGGED, false)); + this.registerDefaultState(this.stateDefinition.any() + .setValue(ROTATION, 0) + .setValue(FLOOR, false) + .setValue(WATERLOGGED, false)); this.parent = source; } @@ -98,7 +109,8 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); } if (!canSurvive(state, world, pos)) { - return state.getValue(WATERLOGGED) ? state.getFluidState().createLegacyBlock() : Blocks.AIR.defaultBlockState(); + return state.getValue(WATERLOGGED) ? state.getFluidState() + .createLegacyBlock() : Blocks.AIR.defaultBlockState(); } return super.updateShape(state, facing, neighborState, world, pos, neighborPos); } @@ -118,7 +130,10 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe public BlockState getStateForPlacement(BlockPlaceContext ctx) { if (ctx.getClickedFace() == Direction.UP) { FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); - return this.defaultBlockState().setValue(FLOOR, true).setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15).setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + return this.defaultBlockState() + .setValue(FLOOR, true) + .setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15) + .setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); } else if (ctx.getClickedFace() != Direction.DOWN) { BlockState blockState = this.defaultBlockState(); @@ -133,7 +148,8 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe int rot = Mth.floor((180.0 + dir.toYRot() * 16.0 / 360.0) + 0.5 + 4) & 15; blockState = blockState.setValue(ROTATION, rot); if (blockState.canSurvive(worldView, blockPos)) { - return blockState.setValue(FLOOR, false).setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + return blockState.setValue(FLOOR, false) + .setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); } } } @@ -177,12 +193,7 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpe } @Override - public int getStackSize() { - return 16; - } - - @Override - public boolean canPlaceOnWater() { - return false; + public BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings) { + return new BlockItem(this, settings.maxCount(16)); } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java index 4d949ca5..dfdb1894 100644 --- a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java @@ -16,16 +16,16 @@ import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { +public class BaseSlabBlock extends SlabBlock implements BlockModelGetter { private final Block parent; public BaseSlabBlock(Block source) { @@ -63,7 +63,10 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { SlabType type = blockState.getValue(TYPE); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_" + type); + ResourceLocation modelId = new ResourceLocation( + stateId.getNamespace(), + "block/" + stateId.getPath() + "_" + type + ); registerBlockModel(stateId, modelId, blockState, modelCache); if (type == SlabType.TOP) { return ModelsHelper.createMultiVariant(modelId, BlockModelRotation.X180_Y0.getRotation(), true); diff --git a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java index 5c0c176c..2f444a1e 100644 --- a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java @@ -17,16 +17,16 @@ import net.minecraft.world.level.block.state.properties.StairsShape; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseStairsBlock extends StairBlock implements BlockModelProvider { +public class BaseStairsBlock extends StairBlock implements BlockModelGetter { private final Block parent; diff --git a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java index a552e9fc..eb82ebbe 100644 --- a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java @@ -30,7 +30,11 @@ public class BaseStripableLogBlock extends BaseRotatedPillarBlock { if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { - world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); + world.setBlock(pos, + striped.defaultBlockState() + .setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), + 11 + ); if (!player.isCreative()) { player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); } diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index 5516246e..cd53cc56 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -51,7 +51,10 @@ public class BaseTerrainBlock extends BaseBlock { private Block pathBlock; public BaseTerrainBlock(Block baseBlock, MaterialColor color) { - super(FabricBlockSettings.copyOf(baseBlock).materialColor(color).sound(BlockSounds.TERRAIN_SOUND).randomTicks()); + super(FabricBlockSettings.copyOf(baseBlock) + .materialColor(color) + .sound(BlockSounds.TERRAIN_SOUND) + .randomTicks()); this.baseBlock = baseBlock; } @@ -104,7 +107,15 @@ public class BaseTerrainBlock extends BaseBlock { return false; } else { - int i = LayerLightEngine.getLightBlockInto(worldView, state, pos, blockState, blockPos, Direction.UP, blockState.getLightBlock(worldView, blockPos)); + int i = LayerLightEngine.getLightBlockInto( + worldView, + state, + pos, + blockState, + blockPos, + Direction.UP, + blockState.getLightBlock(worldView, blockPos) + ); return i < 5; } } diff --git a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java index fd2c4d5b..84a3b1b1 100644 --- a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java @@ -15,11 +15,11 @@ import net.minecraft.world.level.block.state.properties.Half; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Collections; import java.util.HashMap; @@ -27,7 +27,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, BlockModelProvider { +public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerGetter, BlockModelGetter { public BaseTrapdoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion()); } @@ -53,15 +53,18 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, Bl @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { String name = resourceLocation.getPath(); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TRAPDOOR, new HashMap() { - private static final long serialVersionUID = 1L; - - { - put("%modid%", resourceLocation.getNamespace()); - put("%texture%", name); - put("%side%", name.replace("trapdoor", "door_side")); + Optional pattern = PatternsHelper.createJson( + BasePatterns.BLOCK_TRAPDOOR, + new HashMap() { + private static final long serialVersionUID = 1L; + + { + put("%modid%", resourceLocation.getNamespace()); + put("%texture%", name); + put("%side%", name.replace("trapdoor", "door_side")); + } } - }); + ); return ModelsHelper.fromPattern(pattern); } diff --git a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java index 50201937..2c226cf4 100644 --- a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java @@ -17,11 +17,20 @@ import net.minecraft.world.level.material.Material; public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock implements LiquidBlockContainer { public BaseUnderwaterWallPlantBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); } public BaseUnderwaterWallPlantBlock(int light) { - super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.WET_GRASS) + .noCollission()); } public BaseUnderwaterWallPlantBlock(Properties settings) { diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 3437a49b..7b473eb2 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -30,14 +30,14 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.util.BlocksHelper; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { +public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; private static final VoxelShape VOXEL_SHAPE = Block.box(2, 0, 2, 14, 16, 14); @@ -50,7 +50,12 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon } public BaseVineBlock(int light, boolean bottomOnly) { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light).noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM)); } @@ -99,7 +104,10 @@ public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, Bon @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/BaseWallBlock.java b/src/main/java/ru/bclib/blocks/BaseWallBlock.java index 682bea1e..349f1e3e 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallBlock.java @@ -16,16 +16,16 @@ import net.minecraft.world.level.block.state.properties.WallSide; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseWallBlock extends WallBlock implements BlockModelProvider { +public class BaseWallBlock extends WallBlock implements BlockModelGetter { private final Block parent; @@ -71,20 +71,50 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); - ResourceLocation sideTallId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side_tall"); + ResourceLocation sideTallId = new ResourceLocation( + stateId.getNamespace(), + "block/" + stateId.getPath() + "_side_tall" + ); registerBlockModel(postId, postId, blockState, modelCache); registerBlockModel(sideId, sideId, blockState, modelCache); registerBlockModel(sideTallId, sideTallId, blockState, modelCache); ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); builder.part(sideId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.LOW).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y90.getRotation()).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y180.getRotation()).setUVLock(true).add(); - builder.part(sideTallId).setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL).setTransformation(BlockModelRotation.X0_Y270.getRotation()).setUVLock(true).add(); + builder.part(sideId) + .setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW) + .setTransformation(BlockModelRotation.X0_Y90.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW) + .setTransformation(BlockModelRotation.X0_Y180.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideId) + .setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW) + .setTransformation(BlockModelRotation.X0_Y270.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideTallId) + .setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL) + .setUVLock(true) + .add(); + builder.part(sideTallId) + .setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL) + .setTransformation(BlockModelRotation.X0_Y90.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideTallId) + .setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL) + .setTransformation(BlockModelRotation.X0_Y180.getRotation()) + .setUVLock(true) + .add(); + builder.part(sideTallId) + .setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL) + .setTransformation(BlockModelRotation.X0_Y270.getRotation()) + .setUVLock(true) + .add(); builder.part(postId).setCondition(state -> state.getValue(UP)).add(); return builder.build(); diff --git a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java index 5a398081..ee022070 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java @@ -28,15 +28,33 @@ import ru.bclib.util.BlocksHelper; import java.util.EnumMap; public abstract class BaseWallPlantBlock extends BasePlantBlock { - private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of(Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16), Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8), Direction.WEST, Block.box(8, 1, 1, 16, 15, 15), Direction.EAST, Block.box(0, 1, 1, 8, 15, 15))); + private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of( + Direction.NORTH, + Block.box(1, 1, 8, 15, 15, 16), + Direction.SOUTH, + Block.box(1, 1, 0, 15, 15, 8), + Direction.WEST, + Block.box(8, 1, 1, 16, 15, 15), + Direction.EAST, + Block.box(0, 1, 1, 8, 15, 15) + )); public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public BaseWallPlantBlock() { - this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); + this(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } public BaseWallPlantBlock(int light) { - this(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.GRASS).noCollission()); + this(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.GRASS) + .noCollission()); } public BaseWallPlantBlock(Properties settings) { diff --git a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java index 20b2f8f7..6b396c71 100644 --- a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java @@ -14,20 +14,23 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.BlockModelGetter; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { +public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelGetter { private final Block parent; public BaseWeightedPlateBlock(Block source) { - super(15, FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F)); + super( + 15, + FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F) + ); this.parent = source; } diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index 42c727b6..c5492614 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -25,11 +25,11 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Collections; import java.util.List; @@ -37,15 +37,32 @@ import java.util.Optional; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider { +public abstract class FeatureSaplingBlock extends SaplingBlock implements RenderLayerGetter, BlockModelGetter { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public FeatureSaplingBlock() { - super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).instabreak().sound(SoundType.GRASS).randomTicks()); + super( + null, + FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks() + ); } public FeatureSaplingBlock(int light) { - super(null, FabricBlockSettings.of(Material.PLANT).breakByHand(true).collidable(false).luminance(light).instabreak().sound(SoundType.GRASS).randomTicks()); + super( + null, + FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .luminance(light) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks() + ); } protected abstract Feature getFeature(); @@ -73,7 +90,13 @@ public abstract class FeatureSaplingBlock extends SaplingBlock implements IRende @Override public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { - FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null); + FeaturePlaceContext context = new FeaturePlaceContext( + world, + world.getChunkSource().getGenerator(), + random, + pos, + null + ); getFeature().place(context); } diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 8fe7c375..4c17edd0 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -5,15 +5,30 @@ import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; -public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped { +public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerGetter { public SimpleLeavesBlock(MaterialColor color) { - super(FabricBlockSettings.of(Material.LEAVES).strength(0.2F).mapColor(color).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.of(Material.LEAVES) + .strength(0.2F) + .mapColor(color) + .sound(SoundType.GRASS) + .noOcclusion() + .isValidSpawn((state, world, pos, type) -> false) + .isSuffocating((state, world, pos) -> false) + .isViewBlocking((state, world, pos) -> false)); } public SimpleLeavesBlock(MaterialColor color, int light) { - super(FabricBlockSettings.of(Material.LEAVES).luminance(light).mapColor(color).strength(0.2F).sound(SoundType.GRASS).noOcclusion().isValidSpawn((state, world, pos, type) -> false).isSuffocating((state, world, pos) -> false).isViewBlocking((state, world, pos) -> false)); + super(FabricBlockSettings.of(Material.LEAVES) + .luminance(light) + .mapColor(color) + .strength(0.2F) + .sound(SoundType.GRASS) + .noOcclusion() + .isValidSpawn((state, world, pos, type) -> false) + .isSuffocating((state, world, pos) -> false) + .isViewBlocking((state, world, pos) -> false)); } @Override diff --git a/src/main/java/ru/bclib/blocks/StalactiteBlock.java b/src/main/java/ru/bclib/blocks/StalactiteBlock.java index 11ae5224..04dd00b9 100644 --- a/src/main/java/ru/bclib/blocks/StalactiteBlock.java +++ b/src/main/java/ru/bclib/blocks/StalactiteBlock.java @@ -37,13 +37,13 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.Map; import java.util.Optional; @SuppressWarnings("deprecation") -public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped { +public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, RenderLayerGetter { public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; public static final IntegerProperty SIZE = BlockProperties.SIZE; @@ -51,7 +51,10 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg public StalactiteBlock(Block source) { super(FabricBlockSettings.copy(source).noOcclusion()); - this.registerDefaultState(getStateDefinition().any().setValue(SIZE, 0).setValue(IS_FLOOR, true).setValue(WATERLOGGED, false)); + this.registerDefaultState(getStateDefinition().any() + .setValue(SIZE, 0) + .setValue(IS_FLOOR, true) + .setValue(WATERLOGGED, false)); } @Override @@ -212,7 +215,10 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { BlockModelRotation rotation = blockState.getValue(IS_FLOOR) ? BlockModelRotation.X0_Y0 : BlockModelRotation.X180_Y0; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), stateId.getPath() + "_" + blockState.getValue(SIZE)); + ResourceLocation modelId = new ResourceLocation( + stateId.getNamespace(), + stateId.getPath() + "_" + blockState.getValue(SIZE) + ); registerBlockModel(modelId, modelId, blockState, modelCache); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); } diff --git a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java index d0195177..d87f973a 100644 --- a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java @@ -30,7 +30,11 @@ public class StripableBarkBlock extends BaseBarkBlock { if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { - world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); + world.setBlock(pos, + striped.defaultBlockState() + .setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), + 11 + ); if (!player.isCreative()) { player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); } diff --git a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java index e04b13c3..9cc581c2 100644 --- a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java @@ -153,7 +153,17 @@ public class TripleTerrainBlock extends BaseTerrainBlock { return new MultiVariant(variants); } else if (blockState.getValue(SHAPE) == TripleShape.TOP) { - return new MultiVariant(Lists.newArrayList(new Variant(modelId, BlockModelRotation.X180_Y0.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1))); + return new MultiVariant(Lists.newArrayList( + new Variant( + modelId, + BlockModelRotation.X180_Y0.getRotation(), + false, + 1 + ), + new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), + new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), + new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1) + )); } return ModelsHelper.createRandomTopModel(modelId); } diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index dd92f183..86c21d86 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -31,21 +31,30 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer { +public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public UnderwaterPlantBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); } public UnderwaterPlantBlock(int light) { - super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).luminance(light).sound(SoundType.WET_GRASS).noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.WET_GRASS) + .noCollission()); } public UnderwaterPlantBlock(Properties settings) { @@ -86,7 +95,10 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -111,7 +123,13 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements I @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); + ItemEntity item = new ItemEntity( + world, + pos.getX() + 0.5, + pos.getY() + 0.5, + pos.getZ() + 0.5, + new ItemStack(this) + ); world.addFreshEntity(item); } diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java index 9855d9d2..a2ad3dd0 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java @@ -18,7 +18,12 @@ public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public UnderwaterPlantWithAgeBlock() { - super(FabricBlockSettings.of(Material.WATER_PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.WET_GRASS).randomTicks().noCollission()); + super(FabricBlockSettings.of(Material.WATER_PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .randomTicks() + .noCollission()); } @Override diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index 92941bbf..593edcab 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -24,16 +24,20 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.RenderLayerGetter; import java.util.List; @SuppressWarnings("deprecation") -public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped { +public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerGetter { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); public UpDownPlantBlock() { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.SHEARS).breakByHand(true).sound(SoundType.GRASS).noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } protected abstract boolean isTerrain(BlockState state); @@ -67,7 +71,10 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRend @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + Enchantments.SILK_TOUCH, + tool + ) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java index 4f483977..a4aabaf3 100644 --- a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java +++ b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java @@ -16,7 +16,14 @@ import java.util.List; public abstract class WallMushroomBlock extends BaseWallPlantBlock { public WallMushroomBlock(int light) { - super(FabricBlockSettings.of(Material.PLANT).breakByTool(FabricToolTags.AXES).breakByHand(true).luminance(light).hardness(0.2F).sound(SoundType.GRASS).sound(SoundType.WOOD).noCollission()); + super(FabricBlockSettings.of(Material.PLANT) + .breakByTool(FabricToolTags.AXES) + .breakByHand(true) + .luminance(light) + .hardness(0.2F) + .sound(SoundType.GRASS) + .sound(SoundType.WOOD) + .noCollission()); } @Override diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 5cb2d390..56a82c37 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -6,8 +6,8 @@ import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.IPostInit; -import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.interfaces.PostInitable; +import ru.bclib.interfaces.RenderLayerGetter; import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @@ -17,8 +17,8 @@ public class BCLibClient implements ClientModInitializer { BaseBlockEntityRenders.register(); registerRenderLayers(); Registry.BLOCK.forEach(block -> { - if (block instanceof IPostInit) { - ((IPostInit) block).postInit(); + if (block instanceof PostInitable) { + ((PostInitable) block).postInit(); } }); } @@ -27,8 +27,8 @@ public class BCLibClient implements ClientModInitializer { RenderType cutout = RenderType.cutout(); RenderType translucent = RenderType.translucent(); Registry.BLOCK.forEach(block -> { - if (block instanceof IRenderTyped) { - BCLRenderLayer layer = ((IRenderTyped) block).getRenderLayer(); + if (block instanceof RenderLayerGetter) { + BCLRenderLayer layer = ((RenderLayerGetter) block).getRenderLayer(); if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); } diff --git a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java index 22121169..76f22816 100644 --- a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java +++ b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java @@ -53,28 +53,48 @@ public class BlockSignEditScreen extends Screen { protected void init() { //set up a default model - model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); + model = new SignRenderer.SignModel(this.minecraft.getEntityModels() + .bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); minecraft.keyboardHandler.setSendRepeatsToGui(true); - this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, (buttonWidget) -> { - this.finishEditing(); - })); + this.addRenderableWidget(new Button( + this.width / 2 - 100, + this.height / 4 + 120, + 200, + 20, + CommonComponents.GUI_DONE, + (buttonWidget) -> { + this.finishEditing(); + } + )); this.sign.setEditable(false); - this.selectionManager = new TextFieldHelper(() -> { - return this.text[this.currentRow]; - }, (string) -> { - this.text[this.currentRow] = string; - this.sign.setMessage(this.currentRow, new TextComponent(string)); - }, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), (string) -> { - return this.minecraft.font.width(string) <= 90; - }); + this.selectionManager = new TextFieldHelper( + () -> { + return this.text[this.currentRow]; + }, + (string) -> { + this.text[this.currentRow] = string; + this.sign.setMessage(this.currentRow, new TextComponent(string)); + }, + TextFieldHelper.createClipboardGetter(this.minecraft), + TextFieldHelper.createClipboardSetter(this.minecraft), + (string) -> { + return this.minecraft.font.width(string) <= 90; + } + ); } public void removed() { minecraft.keyboardHandler.setSendRepeatsToGui(false); ClientPacketListener clientPlayNetworkHandler = this.minecraft.getConnection(); if (clientPlayNetworkHandler != null) { - clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], this.text[2], this.text[3])); + clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket( + this.sign.getBlockPos(), + this.text[0], + this.text[1], + this.text[2], + this.text[3] + )); } this.sign.setEditable(true); @@ -167,12 +187,36 @@ public class BlockSignEditScreen extends Screen { } float n = (float) (-this.minecraft.font.width(string2) / 2); - this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, immediate, false, 0, 15728880, false); + this.minecraft.font.drawInBatch( + string2, + n, + (float) (m * 10 - this.text.length * 5), + i, + false, + matrix4f, + immediate, + false, + 0, + 15728880, + false + ); if (m == this.currentRow && j >= 0 && bl2) { s = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); t = s - this.minecraft.font.width(string2) / 2; if (j >= string2.length()) { - this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, 0, 15728880, false); + this.minecraft.font.drawInBatch( + "_", + (float) t, + (float) l, + i, + false, + matrix4f, + immediate, + false, + 0, + 15728880, + false + ); } } } diff --git a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java index bdea5197..745e12f0 100644 --- a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java +++ b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java @@ -23,31 +23,71 @@ public class BaseChestBlockModel { MeshDefinition modelData = new MeshDefinition(); PartDefinition modelPartData = modelData.getRoot(); CubeDeformation deformation_partC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), PartPose.ZERO); + modelPartData.addOrReplaceChild( + "partC", + CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), + PartPose.ZERO + ); CubeDeformation deformation_partA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), PartPose.offset(0.0f, 9.0f, 1.0f)); + modelPartData.addOrReplaceChild( + "partA", + CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), + PartPose.offset(0.0f, 9.0f, 1.0f) + ); CubeDeformation deformation_partB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partB", CubeListBuilder.create().texOffs(0, 0).addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), PartPose.offset(0.0f, 8.0f, 0.0f)); + modelPartData.addOrReplaceChild( + "partB", + CubeListBuilder.create().texOffs(0, 0).addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), + PartPose.offset(0.0f, 8.0f, 0.0f) + ); CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partRightC", CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), PartPose.ZERO); + modelPartData.addOrReplaceChild( + "partRightC", + CubeListBuilder.create() + .texOffs(0, 19) + .addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), + PartPose.ZERO + ); CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partRightA", CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), PartPose.offset(0.0f, 9.0f, 1.0f)); + modelPartData.addOrReplaceChild( + "partRightA", + CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), + PartPose.offset(0.0f, 9.0f, 1.0f) + ); CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); - PartDefinition partRightB = modelPartData.addOrReplaceChild("partRightB", CubeListBuilder.create().texOffs(0, 0).addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), PartPose.offset(0.0f, 8.0f, 0.0f)); + PartDefinition partRightB = modelPartData.addOrReplaceChild( + "partRightB", + CubeListBuilder.create() + .texOffs(0, 0) + .addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), + PartPose.offset(0.0f, 8.0f, 0.0f) + ); CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftC", CubeListBuilder.create().texOffs(0, 19).addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), PartPose.ZERO); + modelPartData.addOrReplaceChild( + "partLeftC", + CubeListBuilder.create().texOffs(0, 19).addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), + PartPose.ZERO + ); CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftA", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), PartPose.offset(0.0f, 9.0f, 1.0f)); + modelPartData.addOrReplaceChild( + "partLeftA", + CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), + PartPose.offset(0.0f, 9.0f, 1.0f) + ); CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild("partLeftB", CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), PartPose.offset(0.0f, 8.0f, 0.0f)); + modelPartData.addOrReplaceChild( + "partLeftB", + CubeListBuilder.create().texOffs(0, 0).addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), + PartPose.offset(0.0f, 8.0f, 0.0f) + ); return LayerDefinition.create(modelData, 64, 64); } diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index 8e9b2382..e8992cbe 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -78,7 +78,12 @@ public class ModelsHelper { } public static MultiVariant createRandomTopModel(ResourceLocation resourceLocation) { - return new MultiVariant(Lists.newArrayList(new Variant(resourceLocation, Transformation.identity(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1))); + return new MultiVariant(Lists.newArrayList( + new Variant(resourceLocation, Transformation.identity(), false, 1), + new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), + new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), + new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1) + )); } public static class MultiPartBuilder { diff --git a/src/main/java/ru/bclib/client/models/PatternsHelper.java b/src/main/java/ru/bclib/client/models/PatternsHelper.java index 134e59c9..ace06642 100644 --- a/src/main/java/ru/bclib/client/models/PatternsHelper.java +++ b/src/main/java/ru/bclib/client/models/PatternsHelper.java @@ -52,7 +52,8 @@ public class PatternsHelper { public static Optional createJson(ResourceLocation patternId, Map textures) { ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); try (InputStream input = resourceManager.getResource(patternId).getInputStream()) { - String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines().collect(Collectors.joining()); + String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines() + .collect(Collectors.joining()); for (Map.Entry texture : textures.entrySet()) { json = json.replace(texture.getKey(), texture.getValue()); } diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index ab661e2c..2ac5e080 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -51,7 +51,11 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { - List list = this.font.split(component, 90); - return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); - }); + FormattedCharSequence[] formattedCharSequences = signBlockEntity.getRenderMessages( + Minecraft.getInstance() + .isTextFilteringEnabled(), + (component) -> { + List list = this.font.split(component, 90); + return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); + } + ); int drawColor; boolean drawOutlined; int drawLight; @@ -109,10 +113,30 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer pattern = PatternsHelper.createBlockSimple(resourceLocation); diff --git a/src/main/java/ru/bclib/interfaces/IColorProvider.java b/src/main/java/ru/bclib/interfaces/ColorProviderGetter.java similarity index 83% rename from src/main/java/ru/bclib/interfaces/IColorProvider.java rename to src/main/java/ru/bclib/interfaces/ColorProviderGetter.java index b10ffe31..7433981e 100644 --- a/src/main/java/ru/bclib/interfaces/IColorProvider.java +++ b/src/main/java/ru/bclib/interfaces/ColorProviderGetter.java @@ -3,7 +3,7 @@ package ru.bclib.interfaces; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.item.ItemColor; -public interface IColorProvider { +public interface ColorProviderGetter { BlockColor getProvider(); ItemColor getItemProvider(); diff --git a/src/main/java/ru/bclib/interfaces/CustomItemGetter.java b/src/main/java/ru/bclib/interfaces/CustomItemGetter.java new file mode 100644 index 00000000..0964f996 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/CustomItemGetter.java @@ -0,0 +1,15 @@ +package ru.bclib.interfaces; + +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; +import ru.bclib.registry.BlocksRegistry; + +public interface CustomItemGetter { + /** + * Used to replace default Block Item when block is registered. + * + * @return {@link BlockItem} + */ + BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings); +} diff --git a/src/main/java/ru/bclib/interfaces/ISpetialItem.java b/src/main/java/ru/bclib/interfaces/ISpetialItem.java deleted file mode 100644 index e54e5d3c..00000000 --- a/src/main/java/ru/bclib/interfaces/ISpetialItem.java +++ /dev/null @@ -1,7 +0,0 @@ -package ru.bclib.interfaces; - -public interface ISpetialItem { - boolean canPlaceOnWater(); - - int getStackSize(); -} diff --git a/src/main/java/ru/bclib/client/models/ItemModelProvider.java b/src/main/java/ru/bclib/interfaces/ItemModelGetter.java similarity index 76% rename from src/main/java/ru/bclib/client/models/ItemModelProvider.java rename to src/main/java/ru/bclib/interfaces/ItemModelGetter.java index 50930e6c..162959ca 100644 --- a/src/main/java/ru/bclib/client/models/ItemModelProvider.java +++ b/src/main/java/ru/bclib/interfaces/ItemModelGetter.java @@ -1,11 +1,12 @@ -package ru.bclib.client.models; +package ru.bclib.interfaces; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; +import ru.bclib.client.models.ModelsHelper; -public interface ItemModelProvider { +public interface ItemModelGetter { @Environment(EnvType.CLIENT) default BlockModel getItemModel(ResourceLocation resourceLocation) { return ModelsHelper.createItemModel(resourceLocation); diff --git a/src/main/java/ru/bclib/interfaces/IPostInit.java b/src/main/java/ru/bclib/interfaces/PostInitable.java similarity index 60% rename from src/main/java/ru/bclib/interfaces/IPostInit.java rename to src/main/java/ru/bclib/interfaces/PostInitable.java index 341a6229..23073c9c 100644 --- a/src/main/java/ru/bclib/interfaces/IPostInit.java +++ b/src/main/java/ru/bclib/interfaces/PostInitable.java @@ -1,5 +1,5 @@ package ru.bclib.interfaces; -public interface IPostInit { +public interface PostInitable { void postInit(); } diff --git a/src/main/java/ru/bclib/interfaces/IRenderTyped.java b/src/main/java/ru/bclib/interfaces/RenderLayerGetter.java similarity index 75% rename from src/main/java/ru/bclib/interfaces/IRenderTyped.java rename to src/main/java/ru/bclib/interfaces/RenderLayerGetter.java index 445f9e6b..2d4e94dc 100644 --- a/src/main/java/ru/bclib/interfaces/IRenderTyped.java +++ b/src/main/java/ru/bclib/interfaces/RenderLayerGetter.java @@ -2,6 +2,6 @@ package ru.bclib.interfaces; import ru.bclib.client.render.BCLRenderLayer; -public interface IRenderTyped { +public interface RenderLayerGetter { BCLRenderLayer getRenderLayer(); } diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index 5abab41d..e3c3b075 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -16,11 +16,11 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; -import ru.bclib.client.models.ItemModelProvider; +import ru.bclib.interfaces.ItemModelGetter; import java.util.List; -public class BaseAnvilItem extends BlockItem implements ItemModelProvider { +public class BaseAnvilItem extends BlockItem implements ItemModelGetter { public final static String DESTRUCTION = "destruction"; @@ -54,6 +54,6 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { public BlockModel getItemModel(ResourceLocation resourceLocation) { Block anvilBlock = getBlock(); ResourceLocation blockId = Registry.BLOCK.getKey(anvilBlock); - return ((ItemModelProvider) anvilBlock).getItemModel(blockId); + return ((ItemModelGetter) anvilBlock).getItemModel(blockId); } } diff --git a/src/main/java/ru/bclib/items/BaseArmorItem.java b/src/main/java/ru/bclib/items/BaseArmorItem.java index 39e1cf00..ea99dd98 100644 --- a/src/main/java/ru/bclib/items/BaseArmorItem.java +++ b/src/main/java/ru/bclib/items/BaseArmorItem.java @@ -8,13 +8,18 @@ import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; -import ru.bclib.client.models.ItemModelProvider; +import ru.bclib.interfaces.ItemModelGetter; import java.util.UUID; -public class BaseArmorItem extends ArmorItem implements ItemModelProvider { +public class BaseArmorItem extends ArmorItem implements ItemModelGetter { - protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] {UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150")}; + protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] { + UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), + UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), + UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), + UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150") + }; protected final Multimap defaultModifiers; @@ -22,10 +27,23 @@ public class BaseArmorItem extends ArmorItem implements ItemModelProvider { super(material, equipmentSlot, settings); this.defaultModifiers = HashMultimap.create(); UUID uuid = ARMOR_MODIFIER_UUID_PER_SLOT[equipmentSlot.getIndex()]; - addAttributeModifier(Attributes.ARMOR, new AttributeModifier(uuid, "Armor modifier", getDefense(), AttributeModifier.Operation.ADDITION)); - addAttributeModifier(Attributes.ARMOR_TOUGHNESS, new AttributeModifier(uuid, "Armor toughness", getToughness(), AttributeModifier.Operation.ADDITION)); + addAttributeModifier( + Attributes.ARMOR, + new AttributeModifier(uuid, "Armor modifier", getDefense(), AttributeModifier.Operation.ADDITION) + ); + addAttributeModifier( + Attributes.ARMOR_TOUGHNESS, + new AttributeModifier(uuid, "Armor toughness", getToughness(), AttributeModifier.Operation.ADDITION) + ); if (knockbackResistance > 0.0F) { - addAttributeModifier(Attributes.KNOCKBACK_RESISTANCE, new AttributeModifier(uuid, "Armor knockback resistance", knockbackResistance, AttributeModifier.Operation.ADDITION)); + addAttributeModifier( + Attributes.KNOCKBACK_RESISTANCE, + new AttributeModifier(uuid, + "Armor knockback resistance", + knockbackResistance, + AttributeModifier.Operation.ADDITION + ) + ); } } diff --git a/src/main/java/ru/bclib/items/BaseBucketItem.java b/src/main/java/ru/bclib/items/BaseBucketItem.java index fae47053..9d98f969 100644 --- a/src/main/java/ru/bclib/items/BaseBucketItem.java +++ b/src/main/java/ru/bclib/items/BaseBucketItem.java @@ -5,9 +5,9 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.MobBucketItem; import net.minecraft.world.level.material.Fluids; -import ru.bclib.client.models.ItemModelProvider; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseBucketItem extends MobBucketItem implements ItemModelProvider { +public class BaseBucketItem extends MobBucketItem implements ItemModelGetter { public BaseBucketItem(EntityType type, FabricItemSettings settings) { super(type, Fluids.WATER, SoundEvents.BUCKET_EMPTY_FISH, settings.stacksTo(1)); } diff --git a/src/main/java/ru/bclib/items/BaseDiscItem.java b/src/main/java/ru/bclib/items/BaseDiscItem.java index 3b6a8e46..5c39b6e4 100644 --- a/src/main/java/ru/bclib/items/BaseDiscItem.java +++ b/src/main/java/ru/bclib/items/BaseDiscItem.java @@ -2,9 +2,9 @@ package ru.bclib.items; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.RecordItem; -import ru.bclib.client.models.ItemModelProvider; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseDiscItem extends RecordItem implements ItemModelProvider { +public class BaseDiscItem extends RecordItem implements ItemModelGetter { public BaseDiscItem(int comparatorOutput, SoundEvent sound, Properties settings) { super(comparatorOutput, sound, settings); } diff --git a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java index 6a221400..e3b078f5 100644 --- a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java +++ b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java @@ -8,13 +8,13 @@ import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.item.SpawnEggItem; import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; +import ru.bclib.interfaces.ItemModelGetter; import java.util.Optional; -public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { +public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelGetter { public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { super(type, primaryColor, secondaryColor, settings); } diff --git a/src/main/java/ru/bclib/items/ModelProviderItem.java b/src/main/java/ru/bclib/items/ModelProviderItem.java index 4fbd6a00..1562651c 100644 --- a/src/main/java/ru/bclib/items/ModelProviderItem.java +++ b/src/main/java/ru/bclib/items/ModelProviderItem.java @@ -5,10 +5,10 @@ import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class ModelProviderItem extends Item implements ItemModelProvider { +public class ModelProviderItem extends Item implements ItemModelGetter { public ModelProviderItem(Properties settings) { super(settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java index 92099882..caaf5df8 100644 --- a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java @@ -13,10 +13,10 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelGetter { public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java index 6e1aeab4..8ad78f00 100644 --- a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java @@ -6,10 +6,10 @@ import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.HoeItem; import net.minecraft.world.item.Tier; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseHoeItem extends HoeItem implements ItemModelProvider { +public class BaseHoeItem extends HoeItem implements ItemModelGetter { public BaseHoeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java index 213c530b..7be7301a 100644 --- a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java @@ -15,10 +15,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelProvider { +public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelGetter { public BasePickaxeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } @@ -34,7 +34,10 @@ public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool @Override public float getDestroySpeed(ItemStack stack, BlockState state) { Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.PICKAXES) >= 0) ? speed : super.getDestroySpeed(stack, state); + return (entry != null && entry.getMiningLevel(FabricToolTags.PICKAXES) >= 0) ? speed : super.getDestroySpeed( + stack, + state + ); } @Override diff --git a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java index 1a84ee98..d91aa55e 100644 --- a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java @@ -15,10 +15,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelGetter { public BaseShovelItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } @@ -34,7 +34,10 @@ public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, @Override public float getDestroySpeed(ItemStack stack, BlockState state) { Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.SHOVELS) >= 0) ? speed : super.getDestroySpeed(stack, state); + return (entry != null && entry.getMiningLevel(FabricToolTags.SHOVELS) >= 0) ? speed : super.getDestroySpeed( + stack, + state + ); } @Override diff --git a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java index f78098a3..56615a1f 100644 --- a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java @@ -7,10 +7,10 @@ import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.SwordItem; import net.minecraft.world.item.Tier; -import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; +import ru.bclib.interfaces.ItemModelGetter; -public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelGetter { public BaseSwordItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java index 99fe6e8f..53ed82db 100644 --- a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java @@ -34,7 +34,15 @@ public abstract class EnchantingTableBlockMixin extends Block { if (!world.isEmptyBlock(pos.offset(px / 2, 0, pz / 2))) { break; } - world.addParticle(ParticleTypes.ENCHANT, pos.getX() + 0.5, pos.getY() + 2.0, pos.getZ() + 0.5, px + random.nextFloat() - 0.5, py - random.nextFloat() - 1.0, pz + random.nextFloat() - 0.5); + world.addParticle( + ParticleTypes.ENCHANT, + pos.getX() + 0.5, + pos.getY() + 2.0, + pos.getZ() + 0.5, + px + random.nextFloat() - 0.5, + py - random.nextFloat() - 1.0, + pz + random.nextFloat() - 0.5 + ); } } } diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 98d56db3..6f9e45c2 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -11,7 +11,7 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import ru.bclib.interfaces.IColorProvider; +import ru.bclib.interfaces.ColorProviderGetter; @Mixin(Minecraft.class) public class MinecraftMixin { @@ -26,8 +26,8 @@ public class MinecraftMixin { @Inject(method = "*", at = @At("TAIL")) private void bclib_onMCInit(GameConfig args, CallbackInfo info) { Registry.BLOCK.forEach(block -> { - if (block instanceof IColorProvider) { - IColorProvider provider = (IColorProvider) block; + if (block instanceof ColorProviderGetter) { + ColorProviderGetter provider = (ColorProviderGetter) block; blockColors.register(provider.getProvider(), block); itemColors.register(provider.getItemProvider(), block.asItem()); } diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index cee9f054..33719f1f 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -20,8 +20,8 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.BCLib; -import ru.bclib.client.models.BlockModelProvider; -import ru.bclib.client.models.ItemModelProvider; +import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.ItemModelGetter; import java.util.List; import java.util.Map; @@ -51,14 +51,14 @@ public abstract class ModelBakeryMixin { ResourceLocation itemModelLoc = new ResourceLocation(modId, "models/" + itemLoc.getPath() + ".json"); if (!resourceManager.hasResource(itemModelLoc)) { Item item = Registry.ITEM.get(clearLoc); - ItemModelProvider modelProvider = null; - if (item instanceof ItemModelProvider) { - modelProvider = (ItemModelProvider) item; + ItemModelGetter modelProvider = null; + if (item instanceof ItemModelGetter) { + modelProvider = (ItemModelGetter) item; } else if (item instanceof BlockItem) { Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof ItemModelProvider) { - modelProvider = (ItemModelProvider) block; + if (block instanceof ItemModelGetter) { + modelProvider = (ItemModelGetter) block; } } if (modelProvider != null) { @@ -79,15 +79,28 @@ public abstract class ModelBakeryMixin { ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); if (!resourceManager.hasResource(stateLoc)) { Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof BlockModelProvider) { + if (block instanceof BlockModelGetter) { List possibleStates = block.getStateDefinition().getPossibleStates(); - Optional possibleState = possibleStates.stream().filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state))).findFirst(); + Optional possibleState = possibleStates.stream() + .filter(state -> modelId.equals( + BlockModelShaper.stateToModelLocation( + clearLoc, + state + ))) + .findFirst(); if (possibleState.isPresent()) { - UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant(modelId, possibleState.get(), unbakedCache); + UnbakedModel modelVariant = ((BlockModelGetter) block).getModelVariant( + modelId, + possibleState.get(), + unbakedCache + ); if (modelVariant != null) { if (modelVariant instanceof MultiPart) { possibleStates.forEach(state -> { - ResourceLocation stateId = BlockModelShaper.stateToModelLocation(clearLoc, state); + ResourceLocation stateId = BlockModelShaper.stateToModelLocation( + clearLoc, + state + ); cacheAndQueueDependencies(stateId, modelVariant); }); } diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java index ef8019bc..fc6ba619 100644 --- a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java +++ b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java @@ -29,12 +29,18 @@ public class TextureAtlasMixin { private void bclib_loadSprite(ResourceManager resourceManager, TextureAtlasSprite.Info spriteInfo, int atlasWidth, int atlasHeight, int maxLevel, int posX, int posY, CallbackInfoReturnable info) { ResourceLocation location = spriteInfo.name(); if (bclib_modifyAtlas && location.getPath().startsWith("block")) { - ResourceLocation emissiveLocation = new ResourceLocation(location.getNamespace(), "textures/" + location.getPath() + "_e.png"); + ResourceLocation emissiveLocation = new ResourceLocation( + location.getNamespace(), + "textures/" + location.getPath() + "_e.png" + ); if (resourceManager.hasResource(emissiveLocation)) { NativeImage sprite = null; NativeImage emission = null; try { - ResourceLocation spriteLocation = new ResourceLocation(location.getNamespace(), "textures/" + location.getPath() + ".png"); + ResourceLocation spriteLocation = new ResourceLocation( + location.getNamespace(), + "textures/" + location.getPath() + ".png" + ); Resource resource = resourceManager.getResource(spriteLocation); sprite = NativeImage.read(resource.getInputStream()); resource.close(); @@ -65,7 +71,16 @@ public class TextureAtlasMixin { } } TextureAtlas self = (TextureAtlas) (Object) this; - FabricSprite result = new FabricSprite(self, spriteInfo, maxLevel, atlasWidth, atlasHeight, posX, posY, sprite); + FabricSprite result = new FabricSprite( + self, + spriteInfo, + maxLevel, + atlasWidth, + atlasHeight, + posX, + posY, + sprite + ); info.setReturnValue(result); } } diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index 89945814..52357c1a 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -99,7 +99,8 @@ public class BoneMealItemMixin { for (int y = y1; y >= y2; y--) { bclib_BLOCK_POS.setY(y); BlockPos down = bclib_BLOCK_POS.below(); - if (BlocksHelper.isFluid(world.getBlockState(bclib_BLOCK_POS)) && !BlocksHelper.isFluid(world.getBlockState(down))) { + if (BlocksHelper.isFluid(world.getBlockState(bclib_BLOCK_POS)) && !BlocksHelper.isFluid(world.getBlockState( + down))) { BlockState grass = bclib_getWaterGrassState(world, down); if (grass != null) { BlocksHelper.setWithoutUpdate(world, bclib_BLOCK_POS, grass); diff --git a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java index c5595382..3c5c66cf 100644 --- a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java @@ -66,7 +66,11 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { int j; for (j = -1; j <= 1; ++j) { for (int k = -1; k <= 1; ++k) { - if ((j != 0 || k != 0) && world.isEmptyBlock(blockPos.offset(k, 0, j)) && world.isEmptyBlock(blockPos.offset(k, 1, j))) { + if ((j != 0 || k != 0) && world.isEmptyBlock(blockPos.offset( + k, + 0, + j + )) && world.isEmptyBlock(blockPos.offset(k, 1, j))) { if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } @@ -111,7 +115,8 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { if (this.costs[j] > 0) { List list = this.getEnchantmentList(itemStack, j, this.costs[j]); if (list != null && !list.isEmpty()) { - EnchantmentInstance enchantmentLevelEntry = (EnchantmentInstance) list.get(this.random.nextInt(list.size())); + EnchantmentInstance enchantmentLevelEntry = (EnchantmentInstance) list.get(this.random.nextInt( + list.size())); enchantClue[j] = Registry.ENCHANTMENT.getId(enchantmentLevelEntry.enchantment); levelClue[j] = enchantmentLevelEntry.level; } diff --git a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java index 0c2ef0dd..9a59f424 100644 --- a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java +++ b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java @@ -2256,21 +2256,48 @@ public class OpenSimplexNoise { double attn_ext0 = 2 - dx_ext0 * dx_ext0 - dy_ext0 * dy_ext0 - dz_ext0 * dz_ext0 - dw_ext0 * dw_ext0; if (attn_ext0 > 0) { attn_ext0 *= attn_ext0; - value += attn_ext0 * attn_ext0 * extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, wsv_ext0, dx_ext0, dy_ext0, dz_ext0, dw_ext0); + value += attn_ext0 * attn_ext0 * extrapolate( + xsv_ext0, + ysv_ext0, + zsv_ext0, + wsv_ext0, + dx_ext0, + dy_ext0, + dz_ext0, + dw_ext0 + ); } // Second extra vertex double attn_ext1 = 2 - dx_ext1 * dx_ext1 - dy_ext1 * dy_ext1 - dz_ext1 * dz_ext1 - dw_ext1 * dw_ext1; if (attn_ext1 > 0) { attn_ext1 *= attn_ext1; - value += attn_ext1 * attn_ext1 * extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, wsv_ext1, dx_ext1, dy_ext1, dz_ext1, dw_ext1); + value += attn_ext1 * attn_ext1 * extrapolate( + xsv_ext1, + ysv_ext1, + zsv_ext1, + wsv_ext1, + dx_ext1, + dy_ext1, + dz_ext1, + dw_ext1 + ); } // Third extra vertex double attn_ext2 = 2 - dx_ext2 * dx_ext2 - dy_ext2 * dy_ext2 - dz_ext2 * dz_ext2 - dw_ext2 * dw_ext2; if (attn_ext2 > 0) { attn_ext2 *= attn_ext2; - value += attn_ext2 * attn_ext2 * extrapolate(xsv_ext2, ysv_ext2, zsv_ext2, wsv_ext2, dx_ext2, dy_ext2, dz_ext2, dw_ext2); + value += attn_ext2 * attn_ext2 * extrapolate( + xsv_ext2, + ysv_ext2, + zsv_ext2, + wsv_ext2, + dx_ext2, + dy_ext2, + dz_ext2, + dw_ext2 + ); } return value / NORM_CONSTANT_4D; @@ -2304,11 +2331,341 @@ public class OpenSimplexNoise { // vertices of a rhombicuboctahedron from the center, skewed so // that the triangular and square facets can be inscribed inside // circles of the same radius. - private static byte[] gradients3D = new byte[] {-11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11, -11, -4, 4, -4, -11, 4, -4, -4, 11, 11, -4, 4, 4, -11, 4, 4, -4, 11, -11, 4, -4, -4, 11, -4, -4, 4, -11, 11, 4, -4, 4, 11, -4, 4, 4, -11, -11, -4, -4, -4, -11, -4, -4, -4, -11, 11, -4, -4, 4, -11, -4, 4, -4, -11,}; + private static byte[] gradients3D = new byte[] { + -11, + 4, + 4, + -4, + 11, + 4, + -4, + 4, + 11, + 11, + 4, + 4, + 4, + 11, + 4, + 4, + 4, + 11, + -11, + -4, + 4, + -4, + -11, + 4, + -4, + -4, + 11, + 11, + -4, + 4, + 4, + -11, + 4, + 4, + -4, + 11, + -11, + 4, + -4, + -4, + 11, + -4, + -4, + 4, + -11, + 11, + 4, + -4, + 4, + 11, + -4, + 4, + 4, + -11, + -11, + -4, + -4, + -4, + -11, + -4, + -4, + -4, + -11, + 11, + -4, + -4, + 4, + -11, + -4, + 4, + -4, + -11, + }; // Gradients for 4D. They approximate the directions to the // vertices of a disprismatotesseractihexadecachoron from the center, // skewed so that the tetrahedral and cubic facets can be inscribed inside // spheres of the same radius. - private static byte[] gradients4D = new byte[] {3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, 1, 1, 1, 1, 3, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, 1, 1, -1, 1, 3, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, 1, 1, 1, -1, 3, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, 1, 1, -1, -1, 3, -3, -1, -1, 1, -1, -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, 3, 1, 1, -1, 1, 3, 1, -1, 1, 1, 3, -1, 1, 1, 1, -3, -3, 1, 1, -1, -1, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, 3, -1, 1, -1, 1, -3, 1, -1, 1, -1, 3, -1, 1, -1, 1, -3, -3, -1, 1, -1, -1, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, 3, 1, -1, -1, 1, 3, -1, -1, 1, 1, -3, -1, 1, 1, -1, -3, -3, 1, -1, -1, -1, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, 3, -1, -1, -1, 1, -3, -1, -1, 1, -1, -3, -1, 1, -1, -1, -3, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3, -1, -1, -1, -1, -3,}; + private static byte[] gradients4D = new byte[] { + 3, + 1, + 1, + 1, + 1, + 3, + 1, + 1, + 1, + 1, + 3, + 1, + 1, + 1, + 1, + 3, + -3, + 1, + 1, + 1, + -1, + 3, + 1, + 1, + -1, + 1, + 3, + 1, + -1, + 1, + 1, + 3, + 3, + -1, + 1, + 1, + 1, + -3, + 1, + 1, + 1, + -1, + 3, + 1, + 1, + -1, + 1, + 3, + -3, + -1, + 1, + 1, + -1, + -3, + 1, + 1, + -1, + -1, + 3, + 1, + -1, + -1, + 1, + 3, + 3, + 1, + -1, + 1, + 1, + 3, + -1, + 1, + 1, + 1, + -3, + 1, + 1, + 1, + -1, + 3, + -3, + 1, + -1, + 1, + -1, + 3, + -1, + 1, + -1, + 1, + -3, + 1, + -1, + 1, + -1, + 3, + 3, + -1, + -1, + 1, + 1, + -3, + -1, + 1, + 1, + -1, + -3, + 1, + 1, + -1, + -1, + 3, + -3, + -1, + -1, + 1, + -1, + -3, + -1, + 1, + -1, + -1, + -3, + 1, + -1, + -1, + -1, + 3, + 3, + 1, + 1, + -1, + 1, + 3, + 1, + -1, + 1, + 1, + 3, + -1, + 1, + 1, + 1, + -3, + -3, + 1, + 1, + -1, + -1, + 3, + 1, + -1, + -1, + 1, + 3, + -1, + -1, + 1, + 1, + -3, + 3, + -1, + 1, + -1, + 1, + -3, + 1, + -1, + 1, + -1, + 3, + -1, + 1, + -1, + 1, + -3, + -3, + -1, + 1, + -1, + -1, + -3, + 1, + -1, + -1, + -1, + 3, + -1, + -1, + -1, + 1, + -3, + 3, + 1, + -1, + -1, + 1, + 3, + -1, + -1, + 1, + 1, + -3, + -1, + 1, + 1, + -1, + -3, + -3, + 1, + -1, + -1, + -1, + 3, + -1, + -1, + -1, + 1, + -3, + -1, + -1, + 1, + -1, + -3, + 3, + -1, + -1, + -1, + 1, + -3, + -1, + -1, + 1, + -1, + -3, + -1, + 1, + -1, + -1, + -3, + -3, + -1, + -1, + -1, + -1, + -3, + -1, + -1, + -1, + -1, + -3, + -1, + -1, + -1, + -1, + -3, + }; } \ No newline at end of file diff --git a/src/main/java/ru/bclib/noise/VoronoiNoise.java b/src/main/java/ru/bclib/noise/VoronoiNoise.java index 3e1424ec..5575b203 100644 --- a/src/main/java/ru/bclib/noise/VoronoiNoise.java +++ b/src/main/java/ru/bclib/noise/VoronoiNoise.java @@ -133,8 +133,16 @@ public class VoronoiNoise { } } - BlockPos p1 = new BlockPos((ix + (double) selX) * scale, (iy + (double) selY) * scale, (iz + (double) selZ) * scale); - BlockPos p2 = new BlockPos((ix + (double) selXPre) * scale, (iy + (double) selYPre) * scale, (iz + (double) selZPre) * scale); + BlockPos p1 = new BlockPos( + (ix + (double) selX) * scale, + (iy + (double) selY) * scale, + (iz + (double) selZ) * scale + ); + BlockPos p2 = new BlockPos( + (ix + (double) selXPre) * scale, + (iy + (double) selYPre) * scale, + (iz + (double) selZPre) * scale + ); return new BlockPos[] {p1, p2}; } } diff --git a/src/main/java/ru/bclib/recipes/CraftingRecipes.java b/src/main/java/ru/bclib/recipes/CraftingRecipes.java index ec9788e5..1d43873a 100644 --- a/src/main/java/ru/bclib/recipes/CraftingRecipes.java +++ b/src/main/java/ru/bclib/recipes/CraftingRecipes.java @@ -9,19 +9,79 @@ import ru.bclib.config.Configs; public class CraftingRecipes { public static void init() { - GridRecipe.make(BCLib.MOD_ID, "tag_smith_table", Blocks.SMITHING_TABLE).setShape("II", "##", "##").addMaterial('#', ItemTags.PLANKS).addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_cauldron", Blocks.CAULDRON).setShape("I I", "I I", "III").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER).setShape("I I", "ICI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_piston", Blocks.PISTON).setShape("WWW", "CIC", "CDC").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('D', Items.REDSTONE).addMaterial('C', Items.COBBLESTONE).addMaterial('W', ItemTags.PLANKS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_rail", Blocks.RAIL).setOutputCount(16).setShape("I I", "ISI", "I I").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('S', Items.STICK).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_stonecutter", Blocks.STONECUTTER).setShape(" I ", "SSS").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('S', Items.STONE).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_bucket", Items.BUCKET).setShape("I I", " I ").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_compass", Items.COMPASS).setShape(" I ", "IDI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('D', Items.REDSTONE).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART).setShape("I I", "III").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); - GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD).setShape("WIW", "WWW", " W ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('W', ItemTags.PLANKS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_smith_table", Blocks.SMITHING_TABLE) + .setShape("II", "##", "##") + .addMaterial('#', ItemTags.PLANKS) + .addMaterial('I', TagAPI.IRON_INGOTS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_cauldron", Blocks.CAULDRON) + .setShape("I I", "I I", "III") + .addMaterial('I', TagAPI.IRON_INGOTS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) + .setShape("I I", "ICI", " I ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('C', TagAPI.ITEM_CHEST) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_piston", Blocks.PISTON) + .setShape("WWW", "CIC", "CDC") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('D', Items.REDSTONE) + .addMaterial('C', Items.COBBLESTONE) + .addMaterial('W', ItemTags.PLANKS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_rail", Blocks.RAIL) + .setOutputCount(16) + .setShape("I I", "ISI", "I I") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('S', Items.STICK) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_stonecutter", Blocks.STONECUTTER) + .setShape(" I ", "SSS") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('S', Items.STONE) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_bucket", Items.BUCKET) + .setShape("I I", " I ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_compass", Items.COMPASS) + .setShape(" I ", "IDI", " I ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('D', Items.REDSTONE) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART) + .setShape("I I", "III") + .addMaterial('I', TagAPI.IRON_INGOTS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD) + .setShape("WIW", "WWW", " W ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('W', ItemTags.PLANKS) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER).setShape("I I", "ICI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) + .setShape("I I", "ICI", " I ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('C', TagAPI.ITEM_CHEST) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_shulker_box", Blocks.SHULKER_BOX).setShape("S", "C", "S").addMaterial('S', Items.SHULKER_SHELL).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_shulker_box", Blocks.SHULKER_BOX) + .setShape("S", "C", "S") + .addMaterial('S', Items.SHULKER_SHELL) + .addMaterial('C', TagAPI.ITEM_CHEST) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); } } diff --git a/src/main/java/ru/bclib/recipes/FurnaceRecipe.java b/src/main/java/ru/bclib/recipes/FurnaceRecipe.java index 38d20a4b..fbdd57ea 100644 --- a/src/main/java/ru/bclib/recipes/FurnaceRecipe.java +++ b/src/main/java/ru/bclib/recipes/FurnaceRecipe.java @@ -77,21 +77,49 @@ public class FurnaceRecipe { public void build(boolean blasting, boolean campfire, boolean smoker) { if (exist) { - SmeltingRecipe recipe = new SmeltingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time); + SmeltingRecipe recipe = new SmeltingRecipe( + id, + group, + Ingredient.of(input), + new ItemStack(output, count), + xp, + time + ); BCLRecipeManager.addRecipe(RecipeType.SMELTING, recipe); if (blasting) { - BlastingRecipe recipe2 = new BlastingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time / 2); + BlastingRecipe recipe2 = new BlastingRecipe( + id, + group, + Ingredient.of(input), + new ItemStack(output, count), + xp, + time / 2 + ); BCLRecipeManager.addRecipe(RecipeType.BLASTING, recipe2); } if (campfire) { - CampfireCookingRecipe recipe2 = new CampfireCookingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time * 3); + CampfireCookingRecipe recipe2 = new CampfireCookingRecipe( + id, + group, + Ingredient.of(input), + new ItemStack(output, count), + xp, + time * 3 + ); BCLRecipeManager.addRecipe(RecipeType.CAMPFIRE_COOKING, recipe2); } if (smoker) { - SmokingRecipe recipe2 = new SmokingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time / 2); + SmokingRecipe recipe2 = new SmokingRecipe( + id, + group, + Ingredient.of(input), + new ItemStack(output, count), + xp, + time / 2 + ); BCLRecipeManager.addRecipe(RecipeType.SMOKING, recipe2); } } diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index c74f3117..cc902a35 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -116,7 +116,14 @@ public class GridRecipe { ItemStack result = new ItemStack(output, count); NonNullList materials = this.getMaterials(width, height); - CraftingRecipe recipe = shaped ? new ShapedRecipe(id, group, width, height, materials, result) : new ShapelessRecipe(id, group, result, materials); + CraftingRecipe recipe = shaped ? new ShapedRecipe( + id, + group, + width, + height, + materials, + result + ) : new ShapelessRecipe(id, group, result, materials); BCLRecipeManager.addRecipe(type, recipe); } else { diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index c9958888..7e3c0bcb 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -18,10 +18,16 @@ import ru.bclib.blocks.BaseFurnaceBlock; import ru.bclib.blocks.BaseSignBlock; public class BaseBlockEntities { - public static final DynamicBlockEntityType CHEST = registerBlockEntityType(BCLib.makeID("chest"), BaseChestBlockEntity::new); - public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID("barrel"), BaseBarrelBlockEntity::new); - public static final DynamicBlockEntityType SIGN = registerBlockEntityType(BCLib.makeID("sign"), BaseSignBlockEntity::new); - public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID("furnace"), BaseFurnaceBlockEntity::new); + public static final DynamicBlockEntityType CHEST = registerBlockEntityType(BCLib.makeID( + "chest"), BaseChestBlockEntity::new); + public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID( + "barrel"), BaseBarrelBlockEntity::new); + public static final DynamicBlockEntityType SIGN = registerBlockEntityType( + BCLib.makeID("sign"), + BaseSignBlockEntity::new + ); + public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID( + "furnace"), BaseFurnaceBlockEntity::new); public static DynamicBlockEntityType registerBlockEntityType(ResourceLocation typeId, BlockEntitySupplier supplier) { return Registry.register(Registry.BLOCK_ENTITY_TYPE, typeId, new DynamicBlockEntityType<>(supplier)); @@ -30,19 +36,39 @@ public class BaseBlockEntities { public static void register() {} public static Block[] getChests() { - return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks() + .values() + .stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock) + .map(item -> ((BlockItem) item).getBlock()) + .toArray(Block[]::new); } public static Block[] getBarrels() { - return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks() + .values() + .stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock) + .map(item -> ((BlockItem) item).getBlock()) + .toArray(Block[]::new); } public static Block[] getSigns() { - return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks() + .values() + .stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock) + .map(item -> ((BlockItem) item).getBlock()) + .toArray(Block[]::new); } public static Block[] getFurnaces() { - return BaseRegistry.getRegisteredBlocks().values().stream().filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock).map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks() + .values() + .stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock) + .map(item -> ((BlockItem) item).getBlock()) + .toArray(Block[]::new); } public static boolean registerSpecialBlock(Block block) { diff --git a/src/main/java/ru/bclib/registry/BaseRegistry.java b/src/main/java/ru/bclib/registry/BaseRegistry.java index 9369bc72..a6e985d8 100644 --- a/src/main/java/ru/bclib/registry/BaseRegistry.java +++ b/src/main/java/ru/bclib/registry/BaseRegistry.java @@ -14,11 +14,12 @@ import java.util.List; import java.util.Map; public abstract class BaseRegistry { - private static final List> REGISTRIES = Lists.newArrayList(); private static final Map> MOD_BLOCKS = Maps.newHashMap(); private static final Map> MOD_ITEMS = Maps.newHashMap(); + protected final CreativeModeTab creativeTab; + public static Map> getRegisteredBlocks() { return MOD_BLOCKS; } @@ -49,8 +50,6 @@ public abstract class BaseRegistry { REGISTRIES.forEach(BaseRegistry::registerInternal); } - protected final CreativeModeTab creativeTab; - protected BaseRegistry(CreativeModeTab creativeTab) { this.creativeTab = creativeTab; REGISTRIES.add(this); diff --git a/src/main/java/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlocksRegistry.java index 3da2f9c4..d6d4cee2 100644 --- a/src/main/java/ru/bclib/registry/BlocksRegistry.java +++ b/src/main/java/ru/bclib/registry/BlocksRegistry.java @@ -6,10 +6,8 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; -import net.minecraft.world.item.Item.Properties; -import net.minecraft.world.item.WaterLilyBlockItem; import net.minecraft.world.level.block.Block; -import ru.bclib.interfaces.ISpetialItem; +import ru.bclib.interfaces.CustomItemGetter; public abstract class BlocksRegistry extends BaseRegistry { @@ -19,21 +17,17 @@ public abstract class BlocksRegistry extends BaseRegistry { @Override public Block register(ResourceLocation id, Block block) { - int maxCount = 64; - boolean placeOnWater = false; - if (block instanceof ISpetialItem) { - ISpetialItem item = (ISpetialItem) block; - maxCount = item.getStackSize(); - placeOnWater = item.canPlaceOnWater(); - } - Properties item = makeItemSettings().stacksTo(maxCount); - if (placeOnWater) { - registerBlockItem(id, new WaterLilyBlockItem(block, item)); + BlockItem item = null; + if (block instanceof CustomItemGetter) { + item = ((CustomItemGetter) block).getCustomItem(id, makeItemSettings()); } else { - registerBlockItem(id, new BlockItem(block, item)); + item = new BlockItem(block, makeItemSettings()); } - if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance().get(block).getBurnChance() == 0) { + registerBlockItem(id, item); + if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance() + .get(block) + .getBurnChance() == 0) { FlammableBlockRegistry.getDefaultInstance().add(block, 5, 5); } return Registry.register(Registry.BLOCK, id, block); diff --git a/src/main/java/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemsRegistry.java index fd9b728a..2f491b49 100644 --- a/src/main/java/ru/bclib/registry/ItemsRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemsRegistry.java @@ -78,7 +78,15 @@ public abstract class ItemsRegistry extends BaseRegistry { public ItemStack execute(BlockSource pointer, ItemStack stack) { Direction direction = pointer.getBlockState().getValue(DispenserBlock.FACING); EntityType entityType = ((SpawnEggItem) stack.getItem()).getType(stack.getTag()); - entityType.spawn(pointer.getLevel(), stack, null, pointer.getPos().relative(direction), MobSpawnType.DISPENSER, direction != Direction.UP, false); + entityType.spawn( + pointer.getLevel(), + stack, + null, + pointer.getPos().relative(direction), + MobSpawnType.DISPENSER, + direction != Direction.UP, + false + ); stack.shrink(1); return stack; } diff --git a/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java b/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java index 921768db..3e3be641 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java @@ -34,7 +34,10 @@ public class SDFRadialNoiseMap extends SDFDisplacement { } private float getNoise(double x, double z) { - return (float) noise.eval(x, z) + (float) noise.eval(x * 3 + 1000, z * 3) * 0.5F + (float) noise.eval(x * 9 + 1000, z * 9) * 0.2F; + return (float) noise.eval(x, z) + (float) noise.eval( + x * 3 + 1000, + z * 3 + ) * 0.5F + (float) noise.eval(x * 9 + 1000, z * 9) * 0.2F; } public SDFRadialNoiseMap setSeed(long seed) { diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java index d66e0f46..bd3230ba 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java @@ -30,7 +30,11 @@ public class SDFCappedCone extends SDFPrimitive { float k2y = 2 * height; float cax = qx - MHelper.min(qx, (y < 0F) ? radius1 : radius2); float cay = Math.abs(y) - height; - float mlt = Mth.clamp(MHelper.dot(radius2 - qx, height - y, k2x, k2y) / MHelper.dot(k2x, k2y, k2x, k2y), 0F, 1F); + float mlt = Mth.clamp( + MHelper.dot(radius2 - qx, height - y, k2x, k2y) / MHelper.dot(k2x, k2y, k2x, k2y), + 0F, + 1F + ); float cbx = qx - radius2 + k2x * mlt; float cby = y - height + k2y * mlt; float s = (cbx < 0F && cay < 0F) ? -1F : 1F; diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index de5bf700..35520c02 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -3,15 +3,15 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; -import ru.bclib.interfaces.IPostInit; +import ru.bclib.interfaces.PostInitable; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); Registry.BLOCK.forEach(block -> { - if (block instanceof IPostInit) { - ((IPostInit) block).postInit(); + if (block instanceof PostInitable) { + ((PostInitable) block).postInit(); } }); } diff --git a/src/main/java/ru/bclib/util/SplineHelper.java b/src/main/java/ru/bclib/util/SplineHelper.java index 844e357a..de5b9a0a 100644 --- a/src/main/java/ru/bclib/util/SplineHelper.java +++ b/src/main/java/ru/bclib/util/SplineHelper.java @@ -85,7 +85,10 @@ public class SplineHelper { for (int i = 1; i < count; i++) { Vector3f pos = spline.get(i); float delta = (float) (i - 1) / max; - SDF line = new SDFLine().setRadius(Mth.lerp(delta, radius1, radius2)).setStart(start.x(), start.y(), start.z()).setEnd(pos.x(), pos.y(), pos.z()).setBlock(placerFunction); + SDF line = new SDFLine().setRadius(Mth.lerp(delta, radius1, radius2)) + .setStart(start.x(), start.y(), start.z()) + .setEnd(pos.x(), pos.y(), pos.z()) + .setBlock(placerFunction); result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); start = pos; } @@ -100,7 +103,10 @@ public class SplineHelper { for (int i = 1; i < count; i++) { Vector3f pos = spline.get(i); float delta = (float) (i - 1) / max; - SDF line = new SDFLine().setRadius(radiusFunction.apply(delta)).setStart(start.x(), start.y(), start.z()).setEnd(pos.x(), pos.y(), pos.z()).setBlock(placerFunction); + SDF line = new SDFLine().setRadius(radiusFunction.apply(delta)) + .setStart(start.x(), start.y(), start.z()) + .setEnd(pos.x(), pos.y(), pos.z()) + .setBlock(placerFunction); result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); start = pos; } diff --git a/src/main/java/ru/bclib/util/StructureHelper.java b/src/main/java/ru/bclib/util/StructureHelper.java index aed50005..536a25ec 100644 --- a/src/main/java/ru/bclib/util/StructureHelper.java +++ b/src/main/java/ru/bclib/util/StructureHelper.java @@ -87,7 +87,12 @@ public class StructureHelper { } public static BlockPos offsetPos(BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror) { - Vec3 offset = StructureTemplate.transform(Vec3.atCenterOf(structure.getSize()), mirror, rotation, BlockPos.ZERO); + Vec3 offset = StructureTemplate.transform( + Vec3.atCenterOf(structure.getSize()), + mirror, + rotation, + BlockPos.ZERO + ); return pos.offset(-offset.x * 0.5, 0, -offset.z * 0.5); } @@ -97,7 +102,9 @@ public class StructureHelper { public static void placeCenteredBottom(WorldGenLevel world, BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror, BoundingBox bounds, Random random) { BlockPos offset = offsetPos(pos, structure, rotation, mirror); - StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); + StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation) + .setMirror(mirror) + .setBoundingBox(bounds); structure.placeInWorld(world, offset, offset, placementData, random, 4); } @@ -140,7 +147,11 @@ public class StructureHelper { mut.setY(y); BlockState state = world.getBlockState(mut); boolean ignore = ignore(state, world, mut); - if (canDestruct && BlocksHelper.isInvulnerable(state, world, mut) && random.nextInt(8) == 0 && world.isEmptyBlock(mut.below(2))) { + if (canDestruct && BlocksHelper.isInvulnerable( + state, + world, + mut + ) && random.nextInt(8) == 0 && world.isEmptyBlock(mut.below(2))) { int r = MHelper.randRange(1, 4, random); int cx = mut.getX(); int cy = mut.getY(); @@ -163,7 +174,11 @@ public class StructureHelper { int dz = pz - cz; dz *= dz; mut.setZ(pz); - if (dx + dy + dz <= r && BlocksHelper.isInvulnerable(world.getBlockState(mut), world, mut)) { + if (dx + dy + dz <= r && BlocksHelper.isInvulnerable( + world.getBlockState(mut), + world, + mut + )) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); } } @@ -181,7 +196,8 @@ public class StructureHelper { if (!state.isAir() && random.nextBoolean()) { MHelper.shuffle(DIR, random); for (Direction dir : DIR) { - if (world.isEmptyBlock(mut.relative(dir)) && world.isEmptyBlock(mut.below().relative(dir))) { + if (world.isEmptyBlock(mut.relative(dir)) && world.isEmptyBlock(mut.below() + .relative(dir))) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); mut.move(dir).move(Direction.DOWN); for (int py = mut.getY(); y >= bounds.minY() - 10; y--) { @@ -196,7 +212,11 @@ public class StructureHelper { } break; } - else if (random.nextInt(8) == 0 && !BlocksHelper.isInvulnerable(world.getBlockState(mut.above()), world, mut)) { + else if (random.nextInt(8) == 0 && !BlocksHelper.isInvulnerable( + world.getBlockState(mut.above()), + world, + mut + )) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); } } @@ -344,7 +364,12 @@ public class StructureHelper { } private static boolean ignore(BlockState state, WorldGenLevel world, BlockPos pos) { - return state.getMaterial().isReplaceable() || !state.getFluidState().isEmpty() || state.is(TagAPI.END_GROUND) || state.is(BlockTags.LOGS) || state.is(BlockTags.LEAVES) || state.getMaterial().equals(Material.PLANT) || state.getMaterial().equals(Material.LEAVES) || BlocksHelper.isInvulnerable(state, world, pos); + return state.getMaterial().isReplaceable() || !state.getFluidState() + .isEmpty() || state.is(TagAPI.END_GROUND) || state.is( + BlockTags.LOGS) || state.is(BlockTags.LEAVES) || state.getMaterial() + .equals(Material.PLANT) || state.getMaterial() + .equals(Material.LEAVES) || BlocksHelper + .isInvulnerable(state, world, pos); } public static void cover(WorldGenLevel world, BoundingBox bounds, Random random) { @@ -357,7 +382,9 @@ public class StructureHelper { for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); - if (state.is(TagAPI.END_GROUND) && !world.getBlockState(mut.above()).getMaterial().isSolidBlocking()) { + if (state.is(TagAPI.END_GROUND) && !world.getBlockState(mut.above()) + .getMaterial() + .isSolidBlocking()) { BlocksHelper.setWithoutUpdate(world, mut, top); } } diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiome.java b/src/main/java/ru/bclib/world/biomes/BCLBiome.java index 7b021574..0cf21cbb 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiome.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiome.java @@ -142,7 +142,11 @@ public class BCLBiome { list.add(new StructureInfo(structure, offsetY, terrainMerge)); }); if (!list.isEmpty()) { - structuresFeature = BCLFeature.makeChansedFeature(new ResourceLocation(ns, nm + "_structures"), new ListFeature(list), 10); + structuresFeature = BCLFeature.makeChansedFeature( + new ResourceLocation(ns, nm + "_structures"), + new ListFeature(list), + 10 + ); } } } diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index 3c5e6013..cc405214 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -140,12 +140,19 @@ public class BCLBiomeDef { } public BCLBiomeDef setSurface(Block block) { - setSurface(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderBaseConfiguration(block.defaultBlockState(), Blocks.END_STONE.defaultBlockState(), Blocks.END_STONE.defaultBlockState()))); + setSurface(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderBaseConfiguration( + block.defaultBlockState(), + Blocks.END_STONE.defaultBlockState(), + Blocks.END_STONE.defaultBlockState() + ))); return this; } public BCLBiomeDef setSurface(Block block1, Block block2) { - setSurface(DoubleBlockSurfaceBuilder.register("bclib_" + id.getPath() + "_surface").setBlock1(block1).setBlock2(block2).configured()); + setSurface(DoubleBlockSurfaceBuilder.register("bclib_" + id.getPath() + "_surface") + .setBlock1(block1) + .setBlock2(block2) + .configured()); return this; } @@ -299,7 +306,10 @@ public class BCLBiomeDef { Builder effects = new Builder(); mobs.forEach((spawn) -> { - spawnSettings.addSpawn(spawn.type.getCategory(), new MobSpawnSettings.SpawnerData(spawn.type, spawn.weight, spawn.minGroupSize, spawn.maxGroupSize)); + spawnSettings.addSpawn( + spawn.type.getCategory(), + new MobSpawnSettings.SpawnerData(spawn.type, spawn.weight, spawn.minGroupSize, spawn.maxGroupSize) + ); }); spawns.forEach((entry) -> { @@ -311,14 +321,28 @@ public class BCLBiomeDef { features.forEach((info) -> generationSettings.addFeature(info.featureStep, info.feature)); carvers.forEach((info) -> generationSettings.addCarver(info.carverStep, info.carver)); - effects.skyColor(0).waterColor(waterColor).waterFogColor(waterFogColor).fogColor(fogColor).foliageColorOverride(foliageColor).grassColorOverride(grassColor); + effects.skyColor(0) + .waterColor(waterColor) + .waterFogColor(waterFogColor) + .fogColor(fogColor) + .foliageColorOverride(foliageColor) + .grassColorOverride(grassColor); if (loop != null) effects.ambientLoopSound(loop); if (mood != null) effects.ambientMoodSound(mood); if (additions != null) effects.ambientAdditionsSound(additions); if (particleConfig != null) effects.ambientParticle(particleConfig); effects.backgroundMusic(music != null ? new Music(music, 600, 2400, true) : Musics.END); - return new Biome.BiomeBuilder().precipitation(precipitation).biomeCategory(category).depth(depth).scale(0.2F).temperature(temperature).downfall(downfall).specialEffects(effects.build()).mobSpawnSettings(spawnSettings.build()).generationSettings(generationSettings.build()).build(); + return new Biome.BiomeBuilder().precipitation(precipitation) + .biomeCategory(category) + .depth(depth) + .scale(0.2F) + .temperature(temperature) + .downfall(downfall) + .specialEffects(effects.build()) + .mobSpawnSettings(spawnSettings.build()) + .generationSettings(generationSettings.build()) + .build(); } private static final class SpawnInfo { diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index df27a021..1c3f9f0c 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -39,39 +39,65 @@ public class BCLFeature { } public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(BCLDecorators.HEIGHTMAP_SQUARE).countRandom(density); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(BCLDecorators.HEIGHTMAP_SQUARE) + .countRandom(density); return new BCLFeature(id, feature, GenerationStep.Decoration.VEGETAL_DECORATION, configured); } public static BCLFeature makeRawGenFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration( + chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } public static BCLFeature makeLakeFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration( + chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.LAKES, configured); } public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, int veins, int veinSize, int offset, int minY, int maxY) { - OreConfiguration featureConfig = new OreConfiguration(new BlockMatchTest(Blocks.END_STONE), blockOre.defaultBlockState(), veinSize); + OreConfiguration featureConfig = new OreConfiguration( + new BlockMatchTest(Blocks.END_STONE), + blockOre.defaultBlockState(), + veinSize + ); OreConfiguration config = new OreConfiguration(ANY_TERRAIN, blockOre.defaultBlockState(), 33); - ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig).rangeUniform(VerticalAnchor.absolute(minY), VerticalAnchor.absolute(maxY)).squared().count(veins); - return new BCLFeature(Feature.ORE, Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), GenerationStep.Decoration.UNDERGROUND_ORES); + ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig) + .rangeUniform( + VerticalAnchor.absolute(minY), + VerticalAnchor.absolute(maxY) + ) + .squared() + .count(veins); + return new BCLFeature( + Feature.ORE, + Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), + GenerationStep.Decoration.UNDERGROUND_ORES + ); } public static BCLFeature makeChunkFeature(ResourceLocation id, Feature feature) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(1))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration( + 1))); return new BCLFeature(id, feature, GenerationStep.Decoration.LOCAL_MODIFICATIONS, configured); } public static BCLFeature makeChansedFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration( + chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.SURFACE_STRUCTURES, configured); } public static BCLFeature makeCountRawFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration( + chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index afbad417..5d5201c5 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -93,11 +93,18 @@ public abstract class NBTStructureFeature extends DefaultFeature { StructureTemplate structure = getStructure(world, center, random); Rotation rotation = getRotation(world, center, random); Mirror mirror = getMirror(world, center, random); - BlockPos offset = StructureTemplate.transform(new BlockPos(structure.getSize()), mirror, rotation, BlockPos.ZERO); + BlockPos offset = StructureTemplate.transform( + new BlockPos(structure.getSize()), + mirror, + rotation, + BlockPos.ZERO + ); center = center.offset(0, getYOffset(structure, world, center, random) + 0.5, 0); BoundingBox bounds = makeBox(center); - StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); + StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation) + .setMirror(mirror) + .setBoundingBox(bounds); addStructureData(placementData); center = center.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); structure.placeInWorld(world, center, center, placementData, random, 4); @@ -135,7 +142,9 @@ public abstract class NBTStructureFeature extends DefaultFeature { BlockState stateSt = world.getBlockState(mut); if (!stateSt.is(TagAPI.GEN_TERRAIN)) { if (merge == TerrainMerge.SURFACE) { - SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings().getSurfaceBuilderConfig(); + SurfaceBuilderConfiguration config = world.getBiome(mut) + .getGenerationSettings() + .getSurfaceBuilderConfig(); boolean isTop = mut.getY() == surfMax && state.getMaterial().isSolidBlocking(); BlockState top = isTop ? config.getTopMaterial() : config.getUnderMaterial(); BlocksHelper.setWithoutUpdate(world, mut, top); @@ -147,7 +156,9 @@ public abstract class NBTStructureFeature extends DefaultFeature { else { if (stateSt.is(TagAPI.END_GROUND) && state.getMaterial().isSolidBlocking()) { if (merge == TerrainMerge.SURFACE) { - SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings().getSurfaceBuilderConfig(); + SurfaceBuilderConfiguration config = world.getBiome(mut) + .getGenerationSettings() + .getSurfaceBuilderConfig(); BlocksHelper.setWithoutUpdate(world, mut, config.getUnderMaterial()); } else { diff --git a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java index 4c63a7e7..381bd324 100644 --- a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java @@ -18,7 +18,11 @@ public class DestructionStructureProcessor extends StructureProcessor { @Override public StructureBlockInfo processBlock(LevelReader worldView, BlockPos pos, BlockPos blockPos, StructureBlockInfo structureBlockInfo, StructureBlockInfo structureBlockInfo2, StructurePlaceSettings structurePlacementData) { - if (!BlocksHelper.isInvulnerable(structureBlockInfo2.state, worldView, structureBlockInfo2.pos) && MHelper.RANDOM.nextInt(chance) == 0) { + if (!BlocksHelper.isInvulnerable( + structureBlockInfo2.state, + worldView, + structureBlockInfo2.pos + ) && MHelper.RANDOM.nextInt(chance) == 0) { return null; } return structureBlockInfo2; diff --git a/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java index 8231cde8..1f758427 100644 --- a/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java @@ -14,7 +14,10 @@ public class TerrainStructureProcessor extends StructureProcessor { public StructureBlockInfo processBlock(LevelReader worldView, BlockPos pos, BlockPos blockPos, StructureBlockInfo structureBlockInfo, StructureBlockInfo structureBlockInfo2, StructurePlaceSettings structurePlacementData) { BlockPos bpos = structureBlockInfo2.pos; if (structureBlockInfo2.state.is(Blocks.END_STONE) && worldView.isEmptyBlock(bpos.above())) { - BlockState top = worldView.getBiome(structureBlockInfo2.pos).getGenerationSettings().getSurfaceBuilderConfig().getTopMaterial(); + BlockState top = worldView.getBiome(structureBlockInfo2.pos) + .getGenerationSettings() + .getSurfaceBuilderConfig() + .getTopMaterial(); return new StructureBlockInfo(bpos, top, structureBlockInfo2.nbt); } return structureBlockInfo2; diff --git a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java index d8655332..4497bfc7 100644 --- a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java +++ b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java @@ -19,7 +19,10 @@ public class BCLStructureFeature { public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation) { this.featureStep = step; - this.structure = FabricStructureBuilder.create(id, structure).step(step).defaultConfig(spacing, separation, RANDOM.nextInt(8192)).register(); + this.structure = FabricStructureBuilder.create(id, structure) + .step(step) + .defaultConfig(spacing, separation, RANDOM.nextInt(8192)) + .register(); this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); BuiltinRegistries.register(BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE, id, this.featureConfigured); FlatChunkGeneratorConfigAccessor.getStructureToFeatures().put(this.structure, this.featureConfigured); diff --git a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java index 9e78a08c..434b1a39 100644 --- a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java +++ b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java @@ -47,6 +47,20 @@ public class DoubleBlockSurfaceBuilder extends SurfaceBuilder 0 ? config1 : config2); + SurfaceBuilder.DEFAULT.apply( + random, + chunkAccess, + biome, + x, + z, + height, + noise, + defaultBlock, + defaultFluid, + l, + m, + seed, + noise > 0 ? config1 : config2 + ); } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/models/block/chest_item.json b/src/main/resources/assets/bclib/models/block/chest_item.json index c0a3265f..4f96625e 100644 --- a/src/main/resources/assets/bclib/models/block/chest_item.json +++ b/src/main/resources/assets/bclib/models/block/chest_item.json @@ -3,188 +3,188 @@ "parent": "block/block", "elements": [ { - "__comment": "Box1", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 3.5, - 4.75, - 7, - 8.25 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 3.5, - 10.75, - 7, - 8.25 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 10.5, - 10.75, - 14, - 8.25 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 0, - 10.75, - 3.5, - 8.25 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 7, - 10.75, - 10.5, - 8.25 - ] - } + "__comment": "Box1", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 3.5, + 4.75, + 7, + 8.25 + ] }, - "from": [ - 1, - 0, - 1 - ], - "to": [ - 15, - 10, - 15 - ] + "east": { + "texture": "#texture", + "uv": [ + 3.5, + 10.75, + 7, + 8.25 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 10.5, + 10.75, + 14, + 8.25 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 0, + 10.75, + 3.5, + 8.25 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 7, + 10.75, + 10.5, + 8.25 + ] + } + }, + "from": [ + 1, + 0, + 1 + ], + "to": [ + 15, + 10, + 15 + ] }, { - "__comment": "Box1", - "faces": { - "east": { - "texture": "#texture", - "uv": [ - 3.5, - 4.75, - 7, - 3.75 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 10.5, - 4.75, - 14, - 3.75 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 0, - 4.75, - 3.5, - 3.75 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 7, - 0, - 10.5, - 3.5 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 7, - 4.75, - 10.5, - 3.75 - ] - } + "__comment": "Box1", + "faces": { + "east": { + "texture": "#texture", + "uv": [ + 3.5, + 4.75, + 7, + 3.75 + ] }, - "from": [ - 1, - 10, - 1 - ], - "to": [ - 15, - 14, - 15 - ] + "north": { + "texture": "#texture", + "uv": [ + 10.5, + 4.75, + 14, + 3.75 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 0, + 4.75, + 3.5, + 3.75 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 7, + 0, + 10.5, + 3.5 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 7, + 4.75, + 10.5, + 3.75 + ] + } + }, + "from": [ + 1, + 10, + 1 + ], + "to": [ + 15, + 14, + 15 + ] }, { - "__comment": "Box1", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 0.25, - 0, - 0.75, - 0.25 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 0, - 1.25, - 0.25, - 0.25 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 0.5, - 1.25, - 1, - 0.25 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 0.75, - 0, - 1.25, - 0.25 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 0, - 1.25, - 0.25, - 0.25 - ] - } + "__comment": "Box1", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 0.25, + 0, + 0.75, + 0.25 + ] }, - "from": [ - 7, - 7, - 0 - ], - "to": [ - 9, - 11, - 1 - ] + "east": { + "texture": "#texture", + "uv": [ + 0, + 1.25, + 0.25, + 0.25 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 0.5, + 1.25, + 1, + 0.25 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 0.75, + 0, + 1.25, + 0.25 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 0, + 1.25, + 0.25, + 0.25 + ] + } + }, + "from": [ + 7, + 7, + 0 + ], + "to": [ + 9, + 11, + 1 + ] } ] } diff --git a/src/main/resources/assets/bclib/models/block/ladder.json b/src/main/resources/assets/bclib/models/block/ladder.json index 65ea537b..710f39cd 100644 --- a/src/main/resources/assets/bclib/models/block/ladder.json +++ b/src/main/resources/assets/bclib/models/block/ladder.json @@ -2,436 +2,436 @@ "__comment": "Designed by Paulevs with Cubik Studio - https://cubik.studio", "elements": [ { - "__comment": "Box1", - "faces": { - "down": { - "cullface": "down", - "rotation": 180, - "texture": "#texture", - "uv": [ - 2, - 15, - 4, - 16 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 2, - 0, - 3, - 16 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 16 - ] - }, - "south": { - "cullface": "north", - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 16 - ] - }, - "up": { - "cullface": "up", - "rotation": 180, - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 1 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 3, - 0, - 4, - 16 - ] - } + "__comment": "Box1", + "faces": { + "down": { + "cullface": "down", + "rotation": 180, + "texture": "#texture", + "uv": [ + 2, + 15, + 4, + 16 + ] }, - "from": [ - 12, - 0, - 15 - ], - "to": [ - 14, - 16, - 16 - ] + "east": { + "texture": "#texture", + "uv": [ + 2, + 0, + 3, + 16 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 16 + ] + }, + "south": { + "cullface": "north", + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 16 + ] + }, + "up": { + "cullface": "up", + "rotation": 180, + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 1 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 3, + 0, + 4, + 16 + ] + } + }, + "from": [ + 12, + 0, + 15 + ], + "to": [ + 14, + 16, + 16 + ] }, { - "__comment": "Box1", - "faces": { - "down": { - "cullface": "down", - "rotation": 180, - "texture": "#texture", - "uv": [ - 12, - 15, - 14, - 16 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 2, - 0, - 3, - 16 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 16 - ] - }, - "south": { - "cullface": "north", - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 16 - ] - }, - "up": { - "cullface": "up", - "rotation": 180, - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 1 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 3, - 0, - 4, - 16 - ] - } + "__comment": "Box1", + "faces": { + "down": { + "cullface": "down", + "rotation": 180, + "texture": "#texture", + "uv": [ + 12, + 15, + 14, + 16 + ] }, - "from": [ - 2, - 0, - 15 - ], - "to": [ - 4, - 16, - 16 - ] + "east": { + "texture": "#texture", + "uv": [ + 2, + 0, + 3, + 16 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 16 + ] + }, + "south": { + "cullface": "north", + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 16 + ] + }, + "up": { + "cullface": "up", + "rotation": 180, + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 1 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 3, + 0, + 4, + 16 + ] + } + }, + "from": [ + 2, + 0, + 15 + ], + "to": [ + 4, + 16, + 16 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 14, - 15, - 15 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 13, - 2, - 15 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 15 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 15 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 14 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 13, - 15, - 15 - ] - } + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 14, + 15, + 15 + ] }, - "from": [ - 1, - 1, - 14.5 - ], - "to": [ - 15, - 3, - 15.5 - ] + "east": { + "texture": "#texture", + "uv": [ + 1, + 13, + 2, + 15 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 15 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 15 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 14 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 13, + 15, + 15 + ] + } + }, + "from": [ + 1, + 1, + 14.5 + ], + "to": [ + 15, + 3, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 10, - 15, - 11 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 9, - 2, - 11 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 11 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 11 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 10 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 9, - 15, - 11 - ] - } + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 10, + 15, + 11 + ] }, - "from": [ - 1, - 5, - 14.5 - ], - "to": [ - 15, - 7, - 15.5 - ] + "east": { + "texture": "#texture", + "uv": [ + 1, + 9, + 2, + 11 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 11 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 11 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 10 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 9, + 15, + 11 + ] + } + }, + "from": [ + 1, + 5, + 14.5 + ], + "to": [ + 15, + 7, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 6, - 15, - 7 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 5, - 2, - 7 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 7 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 7 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 6 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 5, - 15, - 7 - ] - } + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 6, + 15, + 7 + ] }, - "from": [ - 1, - 9, - 14.5 - ], - "to": [ - 15, - 11, - 15.5 - ] + "east": { + "texture": "#texture", + "uv": [ + 1, + 5, + 2, + 7 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 7 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 7 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 6 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 5, + 15, + 7 + ] + } + }, + "from": [ + 1, + 9, + 14.5 + ], + "to": [ + 15, + 11, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 2, - 15, - 3 - ] - }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 1, - 2, - 3 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 3 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 3 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 2 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 1, - 15, - 3 - ] - } + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 2, + 15, + 3 + ] }, - "from": [ - 1, - 13, - 14.5 - ], - "to": [ - 15, - 15, - 15.5 - ] + "east": { + "texture": "#texture", + "uv": [ + 1, + 1, + 2, + 3 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 3 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 3 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 2 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 1, + 15, + 3 + ] + } + }, + "from": [ + 1, + 13, + 14.5 + ], + "to": [ + 15, + 15, + 15.5 + ] } ], "parent": "block/ladder", diff --git a/src/main/resources/assets/bclib/models/block/path.json b/src/main/resources/assets/bclib/models/block/path.json index 04fed330..696ef5f5 100644 --- a/src/main/resources/assets/bclib/models/block/path.json +++ b/src/main/resources/assets/bclib/models/block/path.json @@ -1,18 +1,81 @@ -{ "parent": "block/block", - "textures": { - "particle": "#bottom" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 16, 15, 16 ], - "faces": { - "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#bottom", "cullface": "down" }, - "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#top" }, - "north": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "south" }, - "west": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "west" }, - "east": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "east" } - } - } - ] +{ + "parent": "block/block", + "textures": { + "particle": "#bottom" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 15, + 16 + ], + "faces": { + "down": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#bottom", + "cullface": "down" + }, + "up": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#top" + }, + "north": { + "uv": [ + 0, + 1, + 16, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 0, + 1, + 16, + 16 + ], + "texture": "#side", + "cullface": "south" + }, + "west": { + "uv": [ + 0, + 1, + 16, + 16 + ], + "texture": "#side", + "cullface": "west" + }, + "east": { + "uv": [ + 0, + 1, + 16, + 16 + ], + "texture": "#side", + "cullface": "east" + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_bottom.json b/src/main/resources/assets/bclib/models/block/sided_door_bottom.json index 6fddf595..debe45de 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_bottom.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_bottom.json @@ -1,18 +1,71 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 3, 16, 16 ], - "faces": { - "down": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "down" }, - "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, - "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade", "cullface": "west" }, - "east": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade" } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 3, + 16, + 16 + ], + "faces": { + "down": { + "uv": [ + 13, + 0, + 16, + 16 + ], + "texture": "#side", + "cullface": "down" + }, + "north": { + "uv": [ + 3, + 0, + 0, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 0, + 0, + 3, + 16 + ], + "texture": "#side", + "cullface": "south" + }, + "west": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#facade", + "cullface": "west" + }, + "east": { + "uv": [ + 16, + 0, + 0, + 16 + ], + "texture": "#facade" + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json b/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json index e6294d19..112dcc5b 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json @@ -1,18 +1,71 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 3, 16, 16 ], - "faces": { - "down": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "down" }, - "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, - "west": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade", "cullface": "west" }, - "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade" } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 3, + 16, + 16 + ], + "faces": { + "down": { + "uv": [ + 13, + 0, + 16, + 16 + ], + "texture": "#side", + "cullface": "down" + }, + "north": { + "uv": [ + 3, + 0, + 0, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 0, + 0, + 3, + 16 + ], + "texture": "#side", + "cullface": "south" + }, + "west": { + "uv": [ + 16, + 0, + 0, + 16 + ], + "texture": "#facade", + "cullface": "west" + }, + "east": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#facade" + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_top.json b/src/main/resources/assets/bclib/models/block/sided_door_top.json index 4a646108..df8005ff 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_top.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_top.json @@ -1,18 +1,71 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 3, 16, 16 ], - "faces": { - "up": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "up" }, - "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, - "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade", "cullface": "west" }, - "east": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade" } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 3, + 16, + 16 + ], + "faces": { + "up": { + "uv": [ + 13, + 0, + 16, + 16 + ], + "texture": "#side", + "cullface": "up" + }, + "north": { + "uv": [ + 3, + 0, + 0, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 0, + 0, + 3, + 16 + ], + "texture": "#side", + "cullface": "south" + }, + "west": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#facade", + "cullface": "west" + }, + "east": { + "uv": [ + 16, + 0, + 0, + 16 + ], + "texture": "#facade" + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json b/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json index c706fe16..6e564e02 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json @@ -1,18 +1,71 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 3, 16, 16 ], - "faces": { - "up": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "up" }, - "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, - "west": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade", "cullface": "west" }, - "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade" } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 3, + 16, + 16 + ], + "faces": { + "up": { + "uv": [ + 13, + 0, + 16, + 16 + ], + "texture": "#side", + "cullface": "up" + }, + "north": { + "uv": [ + 3, + 0, + 0, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 0, + 0, + 3, + 16 + ], + "texture": "#side", + "cullface": "south" + }, + "west": { + "uv": [ + 16, + 0, + 0, + 16 + ], + "texture": "#facade", + "cullface": "west" + }, + "east": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#facade" + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_trapdoor.json b/src/main/resources/assets/bclib/models/block/sided_trapdoor.json index 9f776427..c6b99a46 100644 --- a/src/main/resources/assets/bclib/models/block/sided_trapdoor.json +++ b/src/main/resources/assets/bclib/models/block/sided_trapdoor.json @@ -1,18 +1,85 @@ -{ "parent": "block/thin_block", - "textures": { - "particle": "#texture" - }, - "elements": [ - { "from": [ 0, 0, 0 ], - "to": [ 16, 3, 16 ], - "faces": { - "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "down" }, - "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture" }, - "north": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "north", "rotation": 90 }, - "south": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "south", "rotation": 90 }, - "west": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "west", "rotation": 90 }, - "east": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "east", "rotation": 90 } - } - } - ] +{ + "parent": "block/thin_block", + "textures": { + "particle": "#texture" + }, + "elements": [ + { + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 3, + 16 + ], + "faces": { + "down": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "down" + }, + "up": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture" + }, + "north": { + "uv": [ + 16, + 0, + 13, + 16 + ], + "texture": "#side", + "cullface": "north", + "rotation": 90 + }, + "south": { + "uv": [ + 16, + 0, + 13, + 16 + ], + "texture": "#side", + "cullface": "south", + "rotation": 90 + }, + "west": { + "uv": [ + 16, + 0, + 13, + 16 + ], + "texture": "#side", + "cullface": "west", + "rotation": 90 + }, + "east": { + "uv": [ + 16, + 0, + 13, + 16 + ], + "texture": "#side", + "cullface": "east", + "rotation": 90 + } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/tint_cube.json b/src/main/resources/assets/bclib/models/block/tint_cube.json index f65b5c05..a99494bf 100644 --- a/src/main/resources/assets/bclib/models/block/tint_cube.json +++ b/src/main/resources/assets/bclib/models/block/tint_cube.json @@ -3,18 +3,86 @@ "textures": { "particle": "#texture" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ 0, 0, 0 ], - "to": [ 16, 16, 16 ], + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 16, + 16 + ], "faces": { - "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "down", "tintindex": 0 }, - "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "up", "tintindex": 0 }, - "north": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "north", "tintindex": 0 }, - "south": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "south", "tintindex": 0 }, - "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "west", "tintindex": 0 }, - "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "east", "tintindex": 0 } + "down": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "down", + "tintindex": 0 + }, + "up": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "up", + "tintindex": 0 + }, + "north": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "north", + "tintindex": 0 + }, + "south": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "south", + "tintindex": 0 + }, + "west": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "west", + "tintindex": 0 + }, + "east": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#texture", + "cullface": "east", + "tintindex": 0 + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/anvil.json b/src/main/resources/assets/bclib/patterns/block/anvil.json index 7710c9a1..94bc7a6c 100644 --- a/src/main/resources/assets/bclib/patterns/block/anvil.json +++ b/src/main/resources/assets/bclib/patterns/block/anvil.json @@ -8,61 +8,270 @@ "panel": "%modid%:block/%anvil%_panel", "bottom": "%modid%:block/%anvil%_bottom" }, - "elements": [ + "elements": [ { "__comment": "Bottom", - "from": [ 2, 0, 2 ], - "to": [ 14, 4, 14 ], + "from": [ + 2, + 0, + 2 + ], + "to": [ + 14, + 4, + 14 + ], "faces": { - "down": { "uv": [ 2, 2, 14, 14 ], "texture": "#bottom", "cullface": "down" }, - "up": { "uv": [ 2, 2, 14, 14 ], "texture": "#panel" }, - "north": { "uv": [ 2, 12, 14, 16 ], "texture": "#back" }, - "south": { "uv": [ 2, 12, 14, 16 ], "texture": "#back" }, - "west": { "uv": [ 2, 12, 14, 16 ], "texture": "#front" }, - "east": { "uv": [ 2, 12, 14, 16 ], "texture": "#front" } + "down": { + "uv": [ + 2, + 2, + 14, + 14 + ], + "texture": "#bottom", + "cullface": "down" + }, + "up": { + "uv": [ + 2, + 2, + 14, + 14 + ], + "texture": "#panel" + }, + "north": { + "uv": [ + 2, + 12, + 14, + 16 + ], + "texture": "#back" + }, + "south": { + "uv": [ + 2, + 12, + 14, + 16 + ], + "texture": "#back" + }, + "west": { + "uv": [ + 2, + 12, + 14, + 16 + ], + "texture": "#front" + }, + "east": { + "uv": [ + 2, + 12, + 14, + 16 + ], + "texture": "#front" + } } }, { "__comment": "Plate", - "from": [ 4, 4, 3 ], - "to": [ 12, 5, 13 ], + "from": [ + 4, + 4, + 3 + ], + "to": [ + 12, + 5, + 13 + ], "faces": { - "up": { "uv": [ 4, 3, 12, 13 ], "texture": "#panel" }, - "north": { "uv": [ 4, 11, 12, 12 ], "texture": "#back" }, - "south": { "uv": [ 4, 11, 12, 12 ], "texture": "#back" }, - "west": { "uv": [ 3, 11, 13, 12 ], "texture": "#front" }, - "east": { "uv": [ 3, 11, 13, 12 ], "texture": "#front" } + "up": { + "uv": [ + 4, + 3, + 12, + 13 + ], + "texture": "#panel" + }, + "north": { + "uv": [ + 4, + 11, + 12, + 12 + ], + "texture": "#back" + }, + "south": { + "uv": [ + 4, + 11, + 12, + 12 + ], + "texture": "#back" + }, + "west": { + "uv": [ + 3, + 11, + 13, + 12 + ], + "texture": "#front" + }, + "east": { + "uv": [ + 3, + 11, + 13, + 12 + ], + "texture": "#front" + } } }, { "__comment": "Support", - "from": [ 6, 5, 4 ], - "to": [ 10, 10, 12 ], + "from": [ + 6, + 5, + 4 + ], + "to": [ + 10, + 10, + 12 + ], "faces": { - "north": { "uv": [ 6, 6, 10, 11 ], "texture": "#back" }, - "south": { "uv": [ 6, 6, 10, 11 ], "texture": "#back" }, - "west": { "uv": [ 4, 6, 12, 11 ], "texture": "#front" }, - "east": { "uv": [ 4, 6, 12, 11 ], "texture": "#front" } + "north": { + "uv": [ + 6, + 6, + 10, + 11 + ], + "texture": "#back" + }, + "south": { + "uv": [ + 6, + 6, + 10, + 11 + ], + "texture": "#back" + }, + "west": { + "uv": [ + 4, + 6, + 12, + 11 + ], + "texture": "#front" + }, + "east": { + "uv": [ + 4, + 6, + 12, + 11 + ], + "texture": "#front" + } } }, { "__comment": "Top", - "from": [ 3, 10, 0 ], - "to": [ 13, 16, 16 ], + "from": [ + 3, + 10, + 0 + ], + "to": [ + 13, + 16, + 16 + ], "faces": { - "down": { "uv": [ 3, 0, 13, 16 ], "texture": "#top" }, - "up": { "uv": [ 3, 0, 13, 16 ], "texture": "#top" }, - "north": { "uv": [ 3, 0, 13, 6 ], "texture": "#back" }, - "south": { "uv": [ 3, 0, 13, 6 ], "texture": "#back" }, - "west": { "uv": [ 0, 0, 16, 6 ], "texture": "#front" }, - "east": { "uv": [ 0, 0, 16, 6 ], "texture": "#front" } + "down": { + "uv": [ + 3, + 0, + 13, + 16 + ], + "texture": "#top" + }, + "up": { + "uv": [ + 3, + 0, + 13, + 16 + ], + "texture": "#top" + }, + "north": { + "uv": [ + 3, + 0, + 13, + 6 + ], + "texture": "#back" + }, + "south": { + "uv": [ + 3, + 0, + 13, + 6 + ], + "texture": "#back" + }, + "west": { + "uv": [ + 0, + 0, + 16, + 6 + ], + "texture": "#front" + }, + "east": { + "uv": [ + 0, + 0, + 16, + 6 + ], + "texture": "#front" + } } } ], "display": { "fixed": { - "rotation": [ 0, 90, 0 ], - "scale": [ 0.5, 0.5, 0.5 ] + "rotation": [ + 0, + 90, + 0 + ], + "scale": [ + 0.5, + 0.5, + 0.5 + ] } } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/bars_post.json b/src/main/resources/assets/bclib/patterns/block/bars_post.json index 0dee124c..8ef444bc 100644 --- a/src/main/resources/assets/bclib/patterns/block/bars_post.json +++ b/src/main/resources/assets/bclib/patterns/block/bars_post.json @@ -4,18 +4,76 @@ "top": "%modid%:block/%texture%_top", "particle": "#top" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ 7, 0, 7 ], - "to": [ 9, 16, 9 ], + "from": [ + 7, + 0, + 7 + ], + "to": [ + 9, + 16, + 9 + ], "faces": { - "down": { "uv": [ 7, 7, 9, 9 ], "texture": "#top", "cullface": "down" }, - "up": { "uv": [ 7, 7, 9, 9 ], "texture": "#top", "cullface": "up" }, - "north": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, - "south": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, - "west": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, - "east": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" } + "down": { + "uv": [ + 7, + 7, + 9, + 9 + ], + "texture": "#top", + "cullface": "down" + }, + "up": { + "uv": [ + 7, + 7, + 9, + 9 + ], + "texture": "#top", + "cullface": "up" + }, + "north": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#top" + }, + "south": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#top" + }, + "west": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#top" + }, + "east": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#top" + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/bars_side.json b/src/main/resources/assets/bclib/patterns/block/bars_side.json index 44794f8e..c22a18fa 100644 --- a/src/main/resources/assets/bclib/patterns/block/bars_side.json +++ b/src/main/resources/assets/bclib/patterns/block/bars_side.json @@ -5,18 +5,77 @@ "top": "%modid%:block/%texture%_top", "particle": "#side" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ 7, 0, 0 ], - "to": [ 9, 16, 9 ], + "from": [ + 7, + 0, + 0 + ], + "to": [ + 9, + 16, + 9 + ], "faces": { - "down": { "uv": [ 7, 7, 9, 16 ], "texture": "#top", "cullface": "down" }, - "up": { "uv": [ 7, 0, 9, 9 ], "texture": "#top", "cullface": "up" }, - "north": { "uv": [ 7, 0, 9, 16 ], "texture": "#side", "cullface": "north" }, - "south": { "uv": [ 7, 0, 9, 16 ], "texture": "#side" }, - "west": { "uv": [ 0, 0, 9, 16 ], "texture": "#side" }, - "east": { "uv": [ 7, 0, 16, 16 ], "texture": "#side" } + "down": { + "uv": [ + 7, + 7, + 9, + 16 + ], + "texture": "#top", + "cullface": "down" + }, + "up": { + "uv": [ + 7, + 0, + 9, + 9 + ], + "texture": "#top", + "cullface": "up" + }, + "north": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#side", + "cullface": "north" + }, + "south": { + "uv": [ + 7, + 0, + 9, + 16 + ], + "texture": "#side" + }, + "west": { + "uv": [ + 0, + 0, + 9, + 16 + ], + "texture": "#side" + }, + "east": { + "uv": [ + 7, + 0, + 16, + 16 + ], + "texture": "#side" + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/block.json b/src/main/resources/assets/bclib/patterns/block/block.json index 431bc5cf..b827a128 100644 --- a/src/main/resources/assets/bclib/patterns/block/block.json +++ b/src/main/resources/assets/bclib/patterns/block/block.json @@ -1,6 +1,6 @@ { - "parent": "block/cube_all", - "textures": { - "all": "%modid%:block/%texture%" - } + "parent": "block/cube_all", + "textures": { + "all": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/button.json b/src/main/resources/assets/bclib/patterns/block/button.json index e09625cd..14a6c8f2 100644 --- a/src/main/resources/assets/bclib/patterns/block/button.json +++ b/src/main/resources/assets/bclib/patterns/block/button.json @@ -1,6 +1,6 @@ { - "parent": "block/button", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/button_pressed.json b/src/main/resources/assets/bclib/patterns/block/button_pressed.json index dfe04d40..23c89dd8 100644 --- a/src/main/resources/assets/bclib/patterns/block/button_pressed.json +++ b/src/main/resources/assets/bclib/patterns/block/button_pressed.json @@ -1,6 +1,6 @@ { - "parent": "block/button_pressed", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button_pressed", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/composter.json b/src/main/resources/assets/bclib/patterns/block/composter.json index cddf7792..82fb4e2a 100644 --- a/src/main/resources/assets/bclib/patterns/block/composter.json +++ b/src/main/resources/assets/bclib/patterns/block/composter.json @@ -9,51 +9,145 @@ }, "elements": [ { - "from": [ 0, 0, 0 ], - "to": [ 16, 2, 16 ], + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 2, + 16 + ], "faces": { - "up": { "texture": "#inside", "cullface": "up" }, - "down": { "texture": "#bottom", "cullface": "down" } + "up": { + "texture": "#inside", + "cullface": "up" + }, + "down": { + "texture": "#bottom", + "cullface": "down" + } } }, { - "from": [ 0, 0, 0 ], - "to": [ 2, 16, 16 ], + "from": [ + 0, + 0, + 0 + ], + "to": [ + 2, + 16, + 16 + ], "faces": { - "up": { "texture": "#top", "cullface": "up" }, - "north": { "texture": "#side", "cullface": "north" }, - "south": { "texture": "#side", "cullface": "south" }, - "west": { "texture": "#side", "cullface": "west" }, - "east": { "texture": "#side", "cullface": "up" } + "up": { + "texture": "#top", + "cullface": "up" + }, + "north": { + "texture": "#side", + "cullface": "north" + }, + "south": { + "texture": "#side", + "cullface": "south" + }, + "west": { + "texture": "#side", + "cullface": "west" + }, + "east": { + "texture": "#side", + "cullface": "up" + } } }, { - "from": [ 14, 0, 0 ], - "to": [ 16, 16, 16 ], + "from": [ + 14, + 0, + 0 + ], + "to": [ + 16, + 16, + 16 + ], "faces": { - "up": { "texture": "#top", "cullface": "up" }, - "north": { "texture": "#side", "cullface": "north" }, - "south": { "texture": "#side", "cullface": "south" }, - "west": { "texture": "#side", "cullface": "up" }, - "east": { "texture": "#side", "cullface": "east" } + "up": { + "texture": "#top", + "cullface": "up" + }, + "north": { + "texture": "#side", + "cullface": "north" + }, + "south": { + "texture": "#side", + "cullface": "south" + }, + "west": { + "texture": "#side", + "cullface": "up" + }, + "east": { + "texture": "#side", + "cullface": "east" + } } }, { - "from": [ 2, 0, 0 ], - "to": [ 14, 16, 2 ], + "from": [ + 2, + 0, + 0 + ], + "to": [ + 14, + 16, + 2 + ], "faces": { - "up": { "texture": "#top", "cullface": "up" }, - "north": { "texture": "#side", "cullface": "north" }, - "south": { "texture": "#side", "cullface": "up" } + "up": { + "texture": "#top", + "cullface": "up" + }, + "north": { + "texture": "#side", + "cullface": "north" + }, + "south": { + "texture": "#side", + "cullface": "up" + } } }, { - "from": [ 2, 0, 14 ], - "to": [ 14, 16, 16 ], + "from": [ + 2, + 0, + 14 + ], + "to": [ + 14, + 16, + 16 + ], "faces": { - "up": { "texture": "#top", "cullface": "up" }, - "north": { "texture": "#side", "cullface": "up" }, - "south": { "texture": "#side", "cullface": "south" } + "up": { + "texture": "#top", + "cullface": "up" + }, + "north": { + "texture": "#side", + "cullface": "up" + }, + "south": { + "texture": "#side", + "cullface": "south" + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/cross_shaded.json b/src/main/resources/assets/bclib/patterns/block/cross_shaded.json index 1db00d86..421f42bd 100644 --- a/src/main/resources/assets/bclib/patterns/block/cross_shaded.json +++ b/src/main/resources/assets/bclib/patterns/block/cross_shaded.json @@ -5,20 +5,88 @@ "particle": "#cross" }, "elements": [ - { "from": [ 0.8, 0, 8 ], - "to": [ 15.2, 16, 8 ], - "rotation": { "origin": [ 8, 8, 8 ], "axis": "y", "angle": 45, "rescale": true }, + { + "from": [ + 0.8, + 0, + 8 + ], + "to": [ + 15.2, + 16, + 8 + ], + "rotation": { + "origin": [ + 8, + 8, + 8 + ], + "axis": "y", + "angle": 45, + "rescale": true + }, "faces": { - "north": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" }, - "south": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" } + "north": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#cross" + }, + "south": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#cross" + } } }, - { "from": [ 8, 0, 0.8 ], - "to": [ 8, 16, 15.2 ], - "rotation": { "origin": [ 8, 8, 8 ], "axis": "y", "angle": 45, "rescale": true }, + { + "from": [ + 8, + 0, + 0.8 + ], + "to": [ + 8, + 16, + 15.2 + ], + "rotation": { + "origin": [ + 8, + 8, + 8 + ], + "axis": "y", + "angle": 45, + "rescale": true + }, "faces": { - "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" }, - "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" } + "west": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#cross" + }, + "east": { + "uv": [ + 0, + 0, + 16, + 16 + ], + "texture": "#cross" + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/furnace_glow.json b/src/main/resources/assets/bclib/patterns/block/furnace_glow.json index caa5ffdc..12b059a5 100644 --- a/src/main/resources/assets/bclib/patterns/block/furnace_glow.json +++ b/src/main/resources/assets/bclib/patterns/block/furnace_glow.json @@ -8,30 +8,79 @@ }, "display": { "firstperson_righthand": { - "rotation": [ 0, 135, 0 ], - "translation": [ 0, 0, 0 ], - "scale": [ 0.40, 0.40, 0.40 ] + "rotation": [ + 0, + 135, + 0 + ], + "translation": [ + 0, + 0, + 0 + ], + "scale": [ + 0.40, + 0.40, + 0.40 + ] } }, "elements": [ { - "from": [ 0, 0, 0 ], - "to": [ 16, 16, 16 ], + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 16, + 16 + ], "faces": { - "down": { "texture": "#top", "cullface": "down" }, - "up": { "texture": "#top", "cullface": "up" }, - "north": { "texture": "#front", "cullface": "north" }, - "south": { "texture": "#side", "cullface": "south" }, - "west": { "texture": "#side", "cullface": "west" }, - "east": { "texture": "#side", "cullface": "east" } + "down": { + "texture": "#top", + "cullface": "down" + }, + "up": { + "texture": "#top", + "cullface": "up" + }, + "north": { + "texture": "#front", + "cullface": "north" + }, + "south": { + "texture": "#side", + "cullface": "south" + }, + "west": { + "texture": "#side", + "cullface": "west" + }, + "east": { + "texture": "#side", + "cullface": "east" + } } }, { - "from": [ 0, 0, 0 ], - "to": [ 16, 16, 16 ], + "from": [ + 0, + 0, + 0 + ], + "to": [ + 16, + 16, + 16 + ], "shade": false, "faces": { - "north": { "texture": "#glow", "cullface": "north" } + "north": { + "texture": "#glow", + "cullface": "north" + } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/path.json b/src/main/resources/assets/bclib/patterns/block/path.json index 347121bb..d73787a0 100644 --- a/src/main/resources/assets/bclib/patterns/block/path.json +++ b/src/main/resources/assets/bclib/patterns/block/path.json @@ -1,7 +1,8 @@ -{ "parent": "bclib:block/path", - "textures": { - "top": "%modid%:block/%top%", - "side": "%modid%:block/%side%", - "bottom": "%bottom%" - } +{ + "parent": "bclib:block/path", + "textures": { + "top": "%modid%:block/%top%", + "side": "%modid%:block/%side%", + "bottom": "%bottom%" + } } diff --git a/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json b/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json index 60147e84..7de574bb 100644 --- a/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json +++ b/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json @@ -1,6 +1,6 @@ { - "parent": "block/pressure_plate_down", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/pressure_plate_down", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json b/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json index 66c028a3..274d36ba 100644 --- a/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json +++ b/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json @@ -1,6 +1,6 @@ { - "parent": "block/pressure_plate_up", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/pressure_plate_up", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/slab.json b/src/main/resources/assets/bclib/patterns/block/slab.json index 7012e909..02fb5d29 100644 --- a/src/main/resources/assets/bclib/patterns/block/slab.json +++ b/src/main/resources/assets/bclib/patterns/block/slab.json @@ -1,8 +1,8 @@ { - "parent": "block/slab", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/slab", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs.json b/src/main/resources/assets/bclib/patterns/block/stairs.json index af694555..6db6d51b 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs.json @@ -1,8 +1,8 @@ { - "parent": "block/stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs_inner.json b/src/main/resources/assets/bclib/patterns/block/stairs_inner.json index 30b7d9bf..4f9f2f9d 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs_inner.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs_inner.json @@ -1,8 +1,8 @@ { - "parent": "block/inner_stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/inner_stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs_outer.json b/src/main/resources/assets/bclib/patterns/block/stairs_outer.json index 3544d10f..fa54a797 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs_outer.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs_outer.json @@ -1,8 +1,8 @@ { - "parent": "block/outer_stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/outer_stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_inventory.json b/src/main/resources/assets/bclib/patterns/block/wall_inventory.json index 85d64810..c6c852ad 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_inventory.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_inventory.json @@ -1,6 +1,6 @@ { - "parent": "block/wall_inventory", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/wall_inventory", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_post.json b/src/main/resources/assets/bclib/patterns/block/wall_post.json index 466b91eb..a4f1819d 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_post.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_post.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_post", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_post", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_side.json b/src/main/resources/assets/bclib/patterns/block/wall_side.json index e93fd118..e44d462a 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_side.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_side.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_side", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_side", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json b/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json index 86451081..69e4647d 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_side_tall", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_side_tall", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_button.json b/src/main/resources/assets/bclib/patterns/item/pattern_button.json index 7cc6b6e0..ceacffba 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_button.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_button.json @@ -1,6 +1,6 @@ { - "parent": "block/button_inventory", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button_inventory", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json b/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json index 765225c9..debcb565 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json @@ -1,3 +1,3 @@ { - "parent": "item/template_spawn_egg" + "parent": "item/template_spawn_egg" } diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_wall.json b/src/main/resources/assets/bclib/patterns/item/pattern_wall.json index 85d64810..c6c852ad 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_wall.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_wall.json @@ -1,6 +1,6 @@ { - "parent": "block/wall_inventory", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/wall_inventory", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index 689cb36b..267fb2fb 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -7,7 +7,7 @@ "EnchantingTableBlockMixin", "BackgroundRendererMixin", "TextureAtlasMixin", - "ModelBakeryMixin", + "ModelBakeryMixin", "MinecraftMixin" ], "injectors": { diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 6d8a5cb6..01ea9f48 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -2,7 +2,6 @@ "schemaVersion": 1, "id": "bclib", "version": "${version}", - "name": "BCLib", "description": "A library for BetterX team mods", "authors": [ @@ -14,10 +13,8 @@ "issues": "https://github.com/paulevsGitch/bclib/issues", "sources": "https://github.com/paulevsGitch/bclib" }, - "license": "MIT", "icon": "assets/bclib/icon.png", - "environment": "*", "entrypoints": { "main": [ @@ -34,7 +31,6 @@ "bclib.mixins.common.json", "bclib.mixins.client.json" ], - "depends": { "fabricloader": ">=0.11.6", "fabric": ">=0.36.0", From 5e2961c91d523ded244f011c9e51649196dae04f Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 23:11:26 +0200 Subject: [PATCH 0060/1033] renamed default config dir --- src/main/java/ru/bclib/config/SessionConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/config/SessionConfig.java b/src/main/java/ru/bclib/config/SessionConfig.java index 3c311417..8ceff397 100644 --- a/src/main/java/ru/bclib/config/SessionConfig.java +++ b/src/main/java/ru/bclib/config/SessionConfig.java @@ -18,8 +18,8 @@ public class SessionConfig extends PathConfig { public final File levelFolder; public SessionConfig(String modID, String group, LevelStorageSource.LevelStorageAccess session, ServerLevel world) { - super(modID, group, new File(getWorldFolder(session, world), BCLib.MOD_ID)); + super(modID, group, new File(getWorldFolder(session, world), BCLib.MOD_ID+"-config")); - this.levelFolder = new File(getWorldFolder(session, world), BCLib.MOD_ID); + this.levelFolder = new File(getWorldFolder(session, world), BCLib.MOD_ID+"-config"); } } From db8dc41c8f4fcf30c22facbd32c9230f23b18534 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 00:16:42 +0300 Subject: [PATCH 0061/1033] Getters interfaces to Providers rename --- .../java/ru/bclib/blocks/BaseAnvilBlock.java | 7 +++---- .../java/ru/bclib/blocks/BaseBarrelBlock.java | 4 ++-- src/main/java/ru/bclib/blocks/BaseBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseButtonBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseChainBlock.java | 6 +++--- .../java/ru/bclib/blocks/BaseChestBlock.java | 4 ++-- .../ru/bclib/blocks/BaseComposterBlock.java | 4 ++-- .../bclib/blocks/BaseCraftingTableBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseDoorBlock.java | 6 +++--- .../ru/bclib/blocks/BaseDoublePlantBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseFenceBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseFurnaceBlock.java | 6 +++--- .../java/ru/bclib/blocks/BaseGateBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseLadderBlock.java | 6 +++--- .../java/ru/bclib/blocks/BaseLeavesBlock.java | 6 +++--- .../ru/bclib/blocks/BaseMetalBarsBlock.java | 6 +++--- .../java/ru/bclib/blocks/BaseOreBlock.java | 4 ++-- .../java/ru/bclib/blocks/BasePlantBlock.java | 4 ++-- .../bclib/blocks/BasePressurePlateBlock.java | 4 ++-- .../bclib/blocks/BaseRotatedPillarBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseSignBlock.java | 7 +++---- .../java/ru/bclib/blocks/BaseSlabBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseStairsBlock.java | 4 ++-- .../ru/bclib/blocks/BaseTrapdoorBlock.java | 6 +++--- .../java/ru/bclib/blocks/BaseVineBlock.java | 4 ++-- .../java/ru/bclib/blocks/BaseWallBlock.java | 4 ++-- .../bclib/blocks/BaseWeightedPlateBlock.java | 4 ++-- .../ru/bclib/blocks/FeatureSaplingBlock.java | 6 +++--- .../ru/bclib/blocks/SimpleLeavesBlock.java | 4 ++-- .../java/ru/bclib/blocks/StalactiteBlock.java | 4 ++-- .../ru/bclib/blocks/UnderwaterPlantBlock.java | 4 ++-- .../java/ru/bclib/blocks/UpDownPlantBlock.java | 4 ++-- src/main/java/ru/bclib/client/BCLibClient.java | 6 +++--- ...odelGetter.java => BlockModelProvider.java} | 2 +- ...derGetter.java => CustomColorProvider.java} | 2 +- ...ItemGetter.java => CustomItemProvider.java} | 2 +- ...ModelGetter.java => ItemModelProvider.java} | 2 +- ...yerGetter.java => RenderLayerProvider.java} | 2 +- .../java/ru/bclib/items/BaseAnvilItem.java | 6 +++--- .../java/ru/bclib/items/BaseArmorItem.java | 4 ++-- .../java/ru/bclib/items/BaseBucketItem.java | 4 ++-- src/main/java/ru/bclib/items/BaseDiscItem.java | 4 ++-- .../java/ru/bclib/items/BaseSpawnEggItem.java | 4 ++-- .../java/ru/bclib/items/ModelProviderItem.java | 4 ++-- .../java/ru/bclib/items/tool/BaseAxeItem.java | 4 ++-- .../java/ru/bclib/items/tool/BaseHoeItem.java | 4 ++-- .../ru/bclib/items/tool/BasePickaxeItem.java | 4 ++-- .../ru/bclib/items/tool/BaseShovelItem.java | 4 ++-- .../ru/bclib/items/tool/BaseSwordItem.java | 4 ++-- .../ru/bclib/mixin/client/MinecraftMixin.java | 6 +++--- .../bclib/mixin/client/ModelBakeryMixin.java | 18 +++++++++--------- .../java/ru/bclib/registry/BlocksRegistry.java | 6 +++--- 52 files changed, 120 insertions(+), 122 deletions(-) rename src/main/java/ru/bclib/interfaces/{BlockModelGetter.java => BlockModelProvider.java} (96%) rename src/main/java/ru/bclib/interfaces/{ColorProviderGetter.java => CustomColorProvider.java} (83%) rename src/main/java/ru/bclib/interfaces/{CustomItemGetter.java => CustomItemProvider.java} (91%) rename src/main/java/ru/bclib/interfaces/{ItemModelGetter.java => ItemModelProvider.java} (91%) rename src/main/java/ru/bclib/interfaces/{RenderLayerGetter.java => RenderLayerProvider.java} (74%) diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 69283002..1f138e12 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -24,16 +24,15 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.CustomItemGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.CustomItemProvider; import ru.bclib.items.BaseAnvilItem; -import ru.bclib.registry.BlocksRegistry; import java.util.List; import java.util.Map; import java.util.Optional; -public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelGetter, CustomItemGetter { +public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider, CustomItemProvider { public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; public BaseAnvilBlock(MaterialColor color) { diff --git a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java index baca4bdb..c5d8dd8b 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java @@ -30,7 +30,7 @@ import ru.bclib.blockentities.BaseBarrelBlockEntity; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.registry.BaseBlockEntities; import java.util.List; @@ -38,7 +38,7 @@ import java.util.Map; import java.util.Optional; import java.util.Random; -public class BaseBarrelBlock extends BarrelBlock implements BlockModelGetter { +public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { public BaseBarrelBlock(Block source) { super(FabricBlockSettings.copyOf(source).noOcclusion()); } diff --git a/src/main/java/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index da796ab1..7dd51813 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -8,7 +8,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; @@ -23,7 +23,7 @@ import java.util.function.Consumer; *
  • Automatically create an Item-Model from the Block-Model
  • * */ -public class BaseBlock extends Block implements BlockModelGetter { +public class BaseBlock extends Block implements BlockModelProvider { /** * Creates a new Block with the passed properties * diff --git a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java index 5afd08e1..289eef21 100644 --- a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java @@ -17,14 +17,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelGetter { +public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { private final Block parent; diff --git a/src/main/java/ru/bclib/blocks/BaseChainBlock.java b/src/main/java/ru/bclib/blocks/BaseChainBlock.java index 97257e9a..9abdb58e 100644 --- a/src/main/java/ru/bclib/blocks/BaseChainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChainBlock.java @@ -18,15 +18,15 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseChainBlock extends ChainBlock implements BlockModelGetter, RenderLayerGetter { +public class BaseChainBlock extends ChainBlock implements BlockModelProvider, RenderLayerProvider { public BaseChainBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); } diff --git a/src/main/java/ru/bclib/blocks/BaseChestBlock.java b/src/main/java/ru/bclib/blocks/BaseChestBlock.java index 94f7c722..6ebc000d 100644 --- a/src/main/java/ru/bclib/blocks/BaseChestBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChestBlock.java @@ -17,13 +17,13 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.Optional; -public class BaseChestBlock extends ChestBlock implements BlockModelGetter { +public class BaseChestBlock extends ChestBlock implements BlockModelProvider { private final Block parent; public BaseChestBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java index 44ee2ddd..8a977e30 100644 --- a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java @@ -16,14 +16,14 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseComposterBlock extends ComposterBlock implements BlockModelGetter { +public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { public BaseComposterBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } diff --git a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java index 5addddc0..6be8cbb9 100644 --- a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java @@ -14,14 +14,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; -public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelGetter { +public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { public BaseCraftingTableBlock(Block source) { super(FabricBlockSettings.copyOf(source)); } diff --git a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java index 540a5638..2e8f8d8b 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java @@ -21,15 +21,15 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseDoorBlock extends DoorBlock implements RenderLayerGetter, BlockModelGetter { +public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, BlockModelProvider { public BaseDoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion()); } diff --git a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index 837fcee2..ad065758 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -31,14 +31,14 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.BlocksHelper; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { +public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); public static final IntegerProperty ROTATION = BlockProperties.ROTATION; public static final BooleanProperty TOP = BooleanProperty.create("top"); diff --git a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java index fecd6ecb..8308330e 100644 --- a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java @@ -18,14 +18,14 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseFenceBlock extends FenceBlock implements BlockModelGetter { +public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { private final Block parent; public BaseFenceBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index 062f7ee5..09958ec8 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -29,15 +29,15 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelGetter, RenderLayerGetter { +public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, RenderLayerProvider { public BaseFurnaceBlock(Block source) { super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0)); } diff --git a/src/main/java/ru/bclib/blocks/BaseGateBlock.java b/src/main/java/ru/bclib/blocks/BaseGateBlock.java index c2e6a1c1..b49e5b51 100644 --- a/src/main/java/ru/bclib/blocks/BaseGateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseGateBlock.java @@ -16,14 +16,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseGateBlock extends FenceGateBlock implements BlockModelGetter { +public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { private final Block parent; public BaseGateBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index 404e6e28..a5a5fa5b 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -31,15 +31,15 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.BlocksHelper; import java.util.Map; import java.util.Optional; @SuppressWarnings("deprecation") -public class BaseLadderBlock extends BaseBlockNotFull implements RenderLayerGetter, BlockModelGetter { +public class BaseLadderBlock extends BaseBlockNotFull implements RenderLayerProvider, BlockModelProvider { public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; protected static final VoxelShape EAST_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index d89887b5..4c6861bf 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -16,15 +16,15 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.MHelper; import java.util.Collections; import java.util.List; import java.util.function.Consumer; -public class BaseLeavesBlock extends LeavesBlock implements BlockModelGetter, RenderLayerGetter { +public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider { private final Block sapling; private static FabricBlockSettings makeLeaves(MaterialColor color) { diff --git a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java index 5ed2ecec..5c64bf7f 100644 --- a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java @@ -19,15 +19,15 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelGetter, RenderLayerGetter { +public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, RenderLayerProvider { public BaseMetalBarsBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion()); } diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index e5c17f15..168c5bce 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -16,13 +16,13 @@ import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.util.MHelper; import java.util.Collections; import java.util.List; -public class BaseOreBlock extends OreBlock implements BlockModelGetter { +public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final Item dropItem; private final int minCount; private final int maxCount; diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index a9fe59fa..ae004374 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -27,13 +27,13 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { +public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public BasePlantBlock() { diff --git a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java index a7f834c4..77d2cacb 100644 --- a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java @@ -16,14 +16,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelGetter { +public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { private final Block parent; public BasePressurePlateBlock(Sensitivity rule, Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java index 9eac0d81..dc1560fa 100644 --- a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java @@ -14,14 +14,14 @@ import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelGetter { +public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { public BaseRotatedPillarBlock(Properties settings) { super(settings); } diff --git a/src/main/java/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index 05ec9de3..655dff5a 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -42,16 +42,15 @@ import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseSignBlockEntity; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.CustomItemGetter; -import ru.bclib.registry.BlocksRegistry; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.CustomItemProvider; import ru.bclib.util.BlocksHelper; import java.util.Collections; import java.util.List; @SuppressWarnings("deprecation") -public class BaseSignBlock extends SignBlock implements BlockModelGetter, CustomItemGetter { +public class BaseSignBlock extends SignBlock implements BlockModelProvider, CustomItemProvider { public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] { diff --git a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java index dfdb1894..80550b77 100644 --- a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java @@ -18,14 +18,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseSlabBlock extends SlabBlock implements BlockModelGetter { +public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { private final Block parent; public BaseSlabBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java index 2f444a1e..7e9de0a0 100644 --- a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java @@ -19,14 +19,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseStairsBlock extends StairBlock implements BlockModelGetter { +public class BaseStairsBlock extends StairBlock implements BlockModelProvider { private final Block parent; diff --git a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java index 84a3b1b1..7e4c0ba7 100644 --- a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java @@ -18,8 +18,8 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Collections; import java.util.HashMap; @@ -27,7 +27,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerGetter, BlockModelGetter { +public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerProvider, BlockModelProvider { public BaseTrapdoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion()); } diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 7b473eb2..67688cba 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -30,14 +30,14 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.util.BlocksHelper; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock { +public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; private static final VoxelShape VOXEL_SHAPE = Block.box(2, 0, 2, 14, 16, 14); diff --git a/src/main/java/ru/bclib/blocks/BaseWallBlock.java b/src/main/java/ru/bclib/blocks/BaseWallBlock.java index 349f1e3e..3f0eea73 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallBlock.java @@ -18,14 +18,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseWallBlock extends WallBlock implements BlockModelGetter { +public class BaseWallBlock extends WallBlock implements BlockModelProvider { private final Block parent; diff --git a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java index 6b396c71..4e4b9d99 100644 --- a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java @@ -16,14 +16,14 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelGetter; +import ru.bclib.interfaces.BlockModelProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelGetter { +public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { private final Block parent; public BaseWeightedPlateBlock(Block source) { diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index c5492614..40ea6e02 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -28,8 +28,8 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Collections; import java.util.List; @@ -37,7 +37,7 @@ import java.util.Optional; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class FeatureSaplingBlock extends SaplingBlock implements RenderLayerGetter, BlockModelGetter { +public abstract class FeatureSaplingBlock extends SaplingBlock implements RenderLayerProvider, BlockModelProvider { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public FeatureSaplingBlock() { diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 4c17edd0..47195b4f 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -5,9 +5,9 @@ import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; -public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerGetter { +public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerProvider { public SimpleLeavesBlock(MaterialColor color) { super(FabricBlockSettings.of(Material.LEAVES) .strength(0.2F) diff --git a/src/main/java/ru/bclib/blocks/StalactiteBlock.java b/src/main/java/ru/bclib/blocks/StalactiteBlock.java index 04dd00b9..be53dd4f 100644 --- a/src/main/java/ru/bclib/blocks/StalactiteBlock.java +++ b/src/main/java/ru/bclib/blocks/StalactiteBlock.java @@ -37,13 +37,13 @@ import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.Map; import java.util.Optional; @SuppressWarnings("deprecation") -public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, RenderLayerGetter { +public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, RenderLayerProvider { public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; public static final IntegerProperty SIZE = BlockProperties.SIZE; diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index 86c21d86..957ee59d 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -31,13 +31,13 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.List; import java.util.Random; @SuppressWarnings("deprecation") -public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerGetter, BonemealableBlock, LiquidBlockContainer { +public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public UnderwaterPlantBlock() { diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index 593edcab..758f06e5 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -24,12 +24,12 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.List; @SuppressWarnings("deprecation") -public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerGetter { +public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerProvider { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); public UpDownPlantBlock() { diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 56a82c37..7b85b66c 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -7,7 +7,7 @@ import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.PostInitable; -import ru.bclib.interfaces.RenderLayerGetter; +import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @@ -27,8 +27,8 @@ public class BCLibClient implements ClientModInitializer { RenderType cutout = RenderType.cutout(); RenderType translucent = RenderType.translucent(); Registry.BLOCK.forEach(block -> { - if (block instanceof RenderLayerGetter) { - BCLRenderLayer layer = ((RenderLayerGetter) block).getRenderLayer(); + if (block instanceof RenderLayerProvider) { + BCLRenderLayer layer = ((RenderLayerProvider) block).getRenderLayer(); if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); } diff --git a/src/main/java/ru/bclib/interfaces/BlockModelGetter.java b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java similarity index 96% rename from src/main/java/ru/bclib/interfaces/BlockModelGetter.java rename to src/main/java/ru/bclib/interfaces/BlockModelProvider.java index 00f371fa..26ba723c 100644 --- a/src/main/java/ru/bclib/interfaces/BlockModelGetter.java +++ b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java @@ -16,7 +16,7 @@ import java.util.Optional; import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION; -public interface BlockModelGetter extends ItemModelGetter { +public interface BlockModelProvider extends ItemModelProvider { @Environment(EnvType.CLIENT) default @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { Optional pattern = PatternsHelper.createBlockSimple(resourceLocation); diff --git a/src/main/java/ru/bclib/interfaces/ColorProviderGetter.java b/src/main/java/ru/bclib/interfaces/CustomColorProvider.java similarity index 83% rename from src/main/java/ru/bclib/interfaces/ColorProviderGetter.java rename to src/main/java/ru/bclib/interfaces/CustomColorProvider.java index 7433981e..608df477 100644 --- a/src/main/java/ru/bclib/interfaces/ColorProviderGetter.java +++ b/src/main/java/ru/bclib/interfaces/CustomColorProvider.java @@ -3,7 +3,7 @@ package ru.bclib.interfaces; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.item.ItemColor; -public interface ColorProviderGetter { +public interface CustomColorProvider { BlockColor getProvider(); ItemColor getItemProvider(); diff --git a/src/main/java/ru/bclib/interfaces/CustomItemGetter.java b/src/main/java/ru/bclib/interfaces/CustomItemProvider.java similarity index 91% rename from src/main/java/ru/bclib/interfaces/CustomItemGetter.java rename to src/main/java/ru/bclib/interfaces/CustomItemProvider.java index 0964f996..c82b1e17 100644 --- a/src/main/java/ru/bclib/interfaces/CustomItemGetter.java +++ b/src/main/java/ru/bclib/interfaces/CustomItemProvider.java @@ -5,7 +5,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import ru.bclib.registry.BlocksRegistry; -public interface CustomItemGetter { +public interface CustomItemProvider { /** * Used to replace default Block Item when block is registered. * diff --git a/src/main/java/ru/bclib/interfaces/ItemModelGetter.java b/src/main/java/ru/bclib/interfaces/ItemModelProvider.java similarity index 91% rename from src/main/java/ru/bclib/interfaces/ItemModelGetter.java rename to src/main/java/ru/bclib/interfaces/ItemModelProvider.java index 162959ca..5ef7873f 100644 --- a/src/main/java/ru/bclib/interfaces/ItemModelGetter.java +++ b/src/main/java/ru/bclib/interfaces/ItemModelProvider.java @@ -6,7 +6,7 @@ import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import ru.bclib.client.models.ModelsHelper; -public interface ItemModelGetter { +public interface ItemModelProvider { @Environment(EnvType.CLIENT) default BlockModel getItemModel(ResourceLocation resourceLocation) { return ModelsHelper.createItemModel(resourceLocation); diff --git a/src/main/java/ru/bclib/interfaces/RenderLayerGetter.java b/src/main/java/ru/bclib/interfaces/RenderLayerProvider.java similarity index 74% rename from src/main/java/ru/bclib/interfaces/RenderLayerGetter.java rename to src/main/java/ru/bclib/interfaces/RenderLayerProvider.java index 2d4e94dc..2da7485a 100644 --- a/src/main/java/ru/bclib/interfaces/RenderLayerGetter.java +++ b/src/main/java/ru/bclib/interfaces/RenderLayerProvider.java @@ -2,6 +2,6 @@ package ru.bclib.interfaces; import ru.bclib.client.render.BCLRenderLayer; -public interface RenderLayerGetter { +public interface RenderLayerProvider { BCLRenderLayer getRenderLayer(); } diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index e3c3b075..c55c5191 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -16,11 +16,11 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; import java.util.List; -public class BaseAnvilItem extends BlockItem implements ItemModelGetter { +public class BaseAnvilItem extends BlockItem implements ItemModelProvider { public final static String DESTRUCTION = "destruction"; @@ -54,6 +54,6 @@ public class BaseAnvilItem extends BlockItem implements ItemModelGetter { public BlockModel getItemModel(ResourceLocation resourceLocation) { Block anvilBlock = getBlock(); ResourceLocation blockId = Registry.BLOCK.getKey(anvilBlock); - return ((ItemModelGetter) anvilBlock).getItemModel(blockId); + return ((ItemModelProvider) anvilBlock).getItemModel(blockId); } } diff --git a/src/main/java/ru/bclib/items/BaseArmorItem.java b/src/main/java/ru/bclib/items/BaseArmorItem.java index ea99dd98..8523d30f 100644 --- a/src/main/java/ru/bclib/items/BaseArmorItem.java +++ b/src/main/java/ru/bclib/items/BaseArmorItem.java @@ -8,11 +8,11 @@ import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ArmorMaterial; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; import java.util.UUID; -public class BaseArmorItem extends ArmorItem implements ItemModelGetter { +public class BaseArmorItem extends ArmorItem implements ItemModelProvider { protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[] { UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), diff --git a/src/main/java/ru/bclib/items/BaseBucketItem.java b/src/main/java/ru/bclib/items/BaseBucketItem.java index 9d98f969..9a4e8789 100644 --- a/src/main/java/ru/bclib/items/BaseBucketItem.java +++ b/src/main/java/ru/bclib/items/BaseBucketItem.java @@ -5,9 +5,9 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.MobBucketItem; import net.minecraft.world.level.material.Fluids; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseBucketItem extends MobBucketItem implements ItemModelGetter { +public class BaseBucketItem extends MobBucketItem implements ItemModelProvider { public BaseBucketItem(EntityType type, FabricItemSettings settings) { super(type, Fluids.WATER, SoundEvents.BUCKET_EMPTY_FISH, settings.stacksTo(1)); } diff --git a/src/main/java/ru/bclib/items/BaseDiscItem.java b/src/main/java/ru/bclib/items/BaseDiscItem.java index 5c39b6e4..17157487 100644 --- a/src/main/java/ru/bclib/items/BaseDiscItem.java +++ b/src/main/java/ru/bclib/items/BaseDiscItem.java @@ -2,9 +2,9 @@ package ru.bclib.items; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.RecordItem; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseDiscItem extends RecordItem implements ItemModelGetter { +public class BaseDiscItem extends RecordItem implements ItemModelProvider { public BaseDiscItem(int comparatorOutput, SoundEvent sound, Properties settings) { super(comparatorOutput, sound, settings); } diff --git a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java index e3b078f5..b06834e8 100644 --- a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java +++ b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java @@ -10,11 +10,11 @@ import net.minecraft.world.item.SpawnEggItem; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; import java.util.Optional; -public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelGetter { +public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { super(type, primaryColor, secondaryColor, settings); } diff --git a/src/main/java/ru/bclib/items/ModelProviderItem.java b/src/main/java/ru/bclib/items/ModelProviderItem.java index 1562651c..03b3d1ce 100644 --- a/src/main/java/ru/bclib/items/ModelProviderItem.java +++ b/src/main/java/ru/bclib/items/ModelProviderItem.java @@ -6,9 +6,9 @@ import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class ModelProviderItem extends Item implements ItemModelGetter { +public class ModelProviderItem extends Item implements ItemModelProvider { public ModelProviderItem(Properties settings) { super(settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java index caaf5df8..f0543c0f 100644 --- a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java @@ -14,9 +14,9 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelGetter { +public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelProvider { public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java index 8ad78f00..786ed794 100644 --- a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java @@ -7,9 +7,9 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.HoeItem; import net.minecraft.world.item.Tier; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseHoeItem extends HoeItem implements ItemModelGetter { +public class BaseHoeItem extends HoeItem implements ItemModelProvider { public BaseHoeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java index 7be7301a..53be6e2d 100644 --- a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java @@ -16,9 +16,9 @@ import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelGetter { +public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelProvider { public BasePickaxeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java index d91aa55e..a987b68b 100644 --- a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java @@ -16,9 +16,9 @@ import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelGetter { +public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelProvider { public BaseShovelItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java index 56615a1f..c32addac 100644 --- a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java @@ -8,9 +8,9 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.SwordItem; import net.minecraft.world.item.Tier; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.ItemModelProvider; -public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelGetter { +public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelProvider { public BaseSwordItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 6f9e45c2..4633efbe 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -11,7 +11,7 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import ru.bclib.interfaces.ColorProviderGetter; +import ru.bclib.interfaces.CustomColorProvider; @Mixin(Minecraft.class) public class MinecraftMixin { @@ -26,8 +26,8 @@ public class MinecraftMixin { @Inject(method = "*", at = @At("TAIL")) private void bclib_onMCInit(GameConfig args, CallbackInfo info) { Registry.BLOCK.forEach(block -> { - if (block instanceof ColorProviderGetter) { - ColorProviderGetter provider = (ColorProviderGetter) block; + if (block instanceof CustomColorProvider) { + CustomColorProvider provider = (CustomColorProvider) block; blockColors.register(provider.getProvider(), block); itemColors.register(provider.getItemProvider(), block.asItem()); } diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index 33719f1f..065c2b0c 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -20,8 +20,8 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.BCLib; -import ru.bclib.interfaces.BlockModelGetter; -import ru.bclib.interfaces.ItemModelGetter; +import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.ItemModelProvider; import java.util.List; import java.util.Map; @@ -51,14 +51,14 @@ public abstract class ModelBakeryMixin { ResourceLocation itemModelLoc = new ResourceLocation(modId, "models/" + itemLoc.getPath() + ".json"); if (!resourceManager.hasResource(itemModelLoc)) { Item item = Registry.ITEM.get(clearLoc); - ItemModelGetter modelProvider = null; - if (item instanceof ItemModelGetter) { - modelProvider = (ItemModelGetter) item; + ItemModelProvider modelProvider = null; + if (item instanceof ItemModelProvider) { + modelProvider = (ItemModelProvider) item; } else if (item instanceof BlockItem) { Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof ItemModelGetter) { - modelProvider = (ItemModelGetter) block; + if (block instanceof ItemModelProvider) { + modelProvider = (ItemModelProvider) block; } } if (modelProvider != null) { @@ -79,7 +79,7 @@ public abstract class ModelBakeryMixin { ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); if (!resourceManager.hasResource(stateLoc)) { Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof BlockModelGetter) { + if (block instanceof BlockModelProvider) { List possibleStates = block.getStateDefinition().getPossibleStates(); Optional possibleState = possibleStates.stream() .filter(state -> modelId.equals( @@ -89,7 +89,7 @@ public abstract class ModelBakeryMixin { ))) .findFirst(); if (possibleState.isPresent()) { - UnbakedModel modelVariant = ((BlockModelGetter) block).getModelVariant( + UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant( modelId, possibleState.get(), unbakedCache diff --git a/src/main/java/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlocksRegistry.java index d6d4cee2..4af14c9c 100644 --- a/src/main/java/ru/bclib/registry/BlocksRegistry.java +++ b/src/main/java/ru/bclib/registry/BlocksRegistry.java @@ -7,7 +7,7 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; -import ru.bclib.interfaces.CustomItemGetter; +import ru.bclib.interfaces.CustomItemProvider; public abstract class BlocksRegistry extends BaseRegistry { @@ -18,8 +18,8 @@ public abstract class BlocksRegistry extends BaseRegistry { @Override public Block register(ResourceLocation id, Block block) { BlockItem item = null; - if (block instanceof CustomItemGetter) { - item = ((CustomItemGetter) block).getCustomItem(id, makeItemSettings()); + if (block instanceof CustomItemProvider) { + item = ((CustomItemProvider) block).getCustomItem(id, makeItemSettings()); } else { item = new BlockItem(block, makeItemSettings()); From adadee7ef7c93a3fdc2f32a80c4ab95940c6fa8b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 00:19:45 +0300 Subject: [PATCH 0062/1033] Version change --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index dccb9055..058f9b87 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ yarn_mappings= 6 loader_version= 0.11.6 # Mod Properties -mod_version = 0.2.5 +mod_version = 0.3.0 maven_group = ru.bclib archives_base_name = bclib From fa1c58b832b8fff61dfdd6c43983c3d1be2a6fb4 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 19 Jul 2021 23:20:08 +0200 Subject: [PATCH 0063/1033] Refactor --- src/main/java/ru/bclib/api/DataFixerAPI2.java | 379 ------------------ .../ru/bclib/api/datafixer/DataFixerAPI.java | 159 ++++++++ .../bclib/api/datafixer/MigrationProfile.java | 81 ++++ .../java/ru/bclib/api/datafixer/Patch.java | 147 +++++++ .../bclib/mixin/common/ServerLevelMixin.java | 4 +- 5 files changed, 389 insertions(+), 381 deletions(-) delete mode 100644 src/main/java/ru/bclib/api/DataFixerAPI2.java create mode 100644 src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java create mode 100644 src/main/java/ru/bclib/api/datafixer/MigrationProfile.java create mode 100644 src/main/java/ru/bclib/api/datafixer/Patch.java diff --git a/src/main/java/ru/bclib/api/DataFixerAPI2.java b/src/main/java/ru/bclib/api/DataFixerAPI2.java deleted file mode 100644 index 4f68809d..00000000 --- a/src/main/java/ru/bclib/api/DataFixerAPI2.java +++ /dev/null @@ -1,379 +0,0 @@ -package ru.bclib.api; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.storage.RegionFile; -import org.jetbrains.annotations.NotNull; -import ru.bclib.config.Configs; -import ru.bclib.config.PathConfig; -import ru.bclib.config.SessionConfig; -import ru.bclib.util.Logger; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -public class DataFixerAPI2 { - private static final Logger LOGGER = new Logger("DataFixerAPI"); - - public static void fixData(SessionConfig config) { - if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { - LOGGER.info("World Patches are disabled"); - return; - } - - final File dir = config.levelFolder; - Patch.MigrationData data = Patch.createMigrationData(config); - if (!data.hasAnyFixes()) { - LOGGER.info("Everything up to date"); - return; - } - - List regions = getAllRegions(dir, null); - regions.parallelStream() - .forEach((file) -> { - try { - LOGGER.info("Inspecting " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), true); - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos)) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - // } - input.close(); - - ListTag tileEntities = root.getCompound("Level") - .getList("TileEntities", 10); - fixItemArrayWithID(tileEntities, changed, data, true); - - ListTag sections = root.getCompound("Level") - .getList("Sections", 10); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", 10); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); - }); - }); - if (changed[0]) { - LOGGER.warning("Writing '{}': {}/{}", file, x, z); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - }); - - data.markApplied(); - } - - private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, Patch.MigrationData data, boolean recursive) { - items.forEach(inTag -> { - final CompoundTag tag = (CompoundTag) inTag; - - changed[0] |= data.replaceStringFromIDs(tag, "id"); - - if (recursive && tag.contains("Items")) { - changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); - } - }); - - return changed[0]; - } - - private static List getAllRegions(File dir, List list) { - if (list == null) { - list = new ArrayList<>(); - } - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - getAllRegions(file, list); - } - else if (file.isFile() && file.getName() - .endsWith(".mca")) { - list.add(file); - } - } - return list; - } - - /** - * Get mod version from string. String should be in format: %d.%d.%d - * - * @param version - {@link String} mod version. - * @return int mod version. - */ - public static int getModVersion(String version) { - if (version.isEmpty()) { - return 0; - } - try { - int res = 0; - final String semanticVersionPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\D*"; - final Matcher matcher = Pattern.compile(semanticVersionPattern) - .matcher(version); - if (matcher.find()) { - if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 20; - if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 12; - if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0xFFF; - } - - return res; - } - catch (Exception e) { - return 0; - } - } - - /** - * Get mod version from integer. String will be in format %d.%d.%d - * - * @param version - mod version in integer form. - * @return {@link String} mod version. - */ - public static String getModVersion(int version) { - int a = (version >> 20) & 0xFF; - int b = (version >> 12) & 0xFF; - int c = version & 0xFFF; - return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); - } - - public abstract static class Patch { - private static List ALL = new ArrayList<>(10); - private final int level; - private final String version; - @NotNull - private final String modID; - - static List getALL() { - return ALL; - } - - /** - * register a new Patch - * - * @param patch A #Supplier that will instantiate the new Patch Object - */ - public static void registerPatch(Supplier patch) { - ALL.add(patch.get()); - } - - /** - * Returns the highest Patch-Version that is available for the given mod. If no patches were - * registerd for the mod, this will return 0.0.0 - * - * @param modID The ID of the mod you want to query - * @return The highest Patch-Version that was found - */ - public static String maxPatchVersion(@NotNull String modID) { - return ALL.stream() - .filter(p -> p.getModID() - .equals(modID)) - .map(p -> p.version) - .reduce((p, c) -> c) - .orElse("0.0.0"); - } - - /** - * Returns the highest patch-level that is available for the given mod. If no patches were - * registerd for the mod, this will return 0 - * - * @param modID The ID of the mod you want to query - * @return The highest Patch-Level that was found - */ - public static int maxPatchLevel(@NotNull String modID) { - return ALL.stream() - .filter(p -> p.getModID() - .equals(modID)) - .mapToInt(p -> p.level) - .max() - .orElse(0); - } - - /** - * Called by inheriting classes. - *

    - * Performs some sanity checks on the values and might throw a #RuntimeException if any - * inconsistencies are found. - * - * @param modID The ID of the Mod you want to register a patch for. This should be your - * ModID only. The ModID can not be {@code null} or an empty String. - * @param version The mod-version that introduces the patch. This needs Semantic-Version String - * like x.x.x. Developers are responsible for registering their patches in the correct - * order (with increasing versions). You are not allowed to register a new - * Patch with a version lower or equal than - * {@link Patch#maxPatchVersion(String)} - */ - protected Patch(@NotNull String modID, String version) { - //Patchlevels need to be unique and registered in ascending order - if (modID == null || "".equals(modID)) { - throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); - } - - if (version == null || "".equals(version)) { - throw new RuntimeException("Invalid Mod-Version"); - } - - this.version = version; - this.level = getModVersion(version); - if (!ALL.stream() - .filter(p -> p.getModID() - .equals(modID) - ) - .noneMatch(p -> p.getLevel() >= this.level) || this.level <= 0) { - throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); - } - - this.modID = modID; - } - - @Override - public String toString() { - return "Patch{" + getModID() + ':' + getVersion() + ':' + getLevel() + '}'; - } - - final public int getLevel() { - return level; - } - - final public String getVersion() { - return version; - } - - /** - * The Mod-ID that registered this Patch - * - * @return The ID - */ - final public String getModID() { - return modID; - } - - - /** - * Return block data fixes. Fixes will be applied on world load if current patch-level for - * the linked mod is lower than the {@link #level}. - *

    - * The default implementation of this method returns an empty map. - * - * @return The returned Map should contain the replacements. All occurences of the - * {@code KeySet} are replaced with the associated value. - */ - public Map getIDReplacements() { - return new HashMap(); - } - - /** - * Generates ready to use data for all currently registered patches. The list of - * patches is selected by the current patch-level of the world. - *

    - * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the - * world is less - * - * @return a new {@link MigrationData} Object. - */ - static MigrationData createMigrationData(PathConfig config) { - return new MigrationData(config); - } - - static class MigrationData { - final Set mods; - final Map idReplacements; - private final PathConfig config; - - private MigrationData(PathConfig config) { - this.config = config; - - this.mods = Collections.unmodifiableSet(Patch.getALL() - .stream() - .map(p -> p.modID) - .collect(Collectors.toSet())); - - HashMap replacements = new HashMap(); - for (String modID : mods) { - Patch.getALL() - .stream() - .filter(p -> p.modID.equals(modID)) - .forEach(patch -> { - if (currentPatchLevel(modID) < patch.level) { - replacements.putAll(patch.getIDReplacements()); - LOGGER.info("Applying " + patch); - } - else { - LOGGER.info("Ignoring " + patch); - } - }); - } - - this.idReplacements = Collections.unmodifiableMap(replacements); - } - - final public void markApplied() { - for (String modID : mods) { - LOGGER.info( - "Updating Patch-Level for '{}' from {} to {}", - modID, - currentPatchLevel(modID), - Patch.maxPatchLevel(modID) - ); - config.setString(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchVersion(modID)); - } - - config.saveChanges(); - } - - public String currentPatchVersion(@NotNull String modID) { - return config.getString(Configs.MAIN_PATCH_CATEGORY, modID, "0.0.0"); - } - - public int currentPatchLevel(@NotNull String modID) { - return getModVersion(currentPatchVersion(modID)); - } - - public boolean hasAnyFixes() { - return idReplacements.size() > 0; - } - - public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key) { - if (!tag.contains(key)) return false; - - final String val = tag.getString(key); - final String replace = idReplacements.get(val); - - if (replace != null) { - LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); - tag.putString(key, replace); - return true; - } - - return false; - } - } - } -} diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java new file mode 100644 index 00000000..da2ef884 --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -0,0 +1,159 @@ +package ru.bclib.api.datafixer; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.RegionFile; +import ru.bclib.config.Configs; +import ru.bclib.config.SessionConfig; +import ru.bclib.util.Logger; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class DataFixerAPI { + static final Logger LOGGER = new Logger("DataFixerAPI"); + + public static void fixData(SessionConfig config) { + if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { + LOGGER.info("World Patches are disabled"); + return; + } + + final File dir = config.levelFolder; + MigrationProfile data = Patch.createMigrationData(config); + if (!data.hasAnyFixes()) { + LOGGER.info("Everything up to date"); + return; + } + + List regions = getAllRegions(dir, null); + regions.parallelStream() + .forEach((file) -> { + try { + LOGGER.info("Inspecting " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + ChunkPos pos = new ChunkPos(x, z); + changed[0] = false; + if (region.hasChunk(pos)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + // } + input.close(); + + ListTag tileEntities = root.getCompound("Level") + .getList("TileEntities", 10); + fixItemArrayWithID(tileEntities, changed, data, true); + + ListTag sections = root.getCompound("Level") + .getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); + }); + }); + if (changed[0]) { + LOGGER.warning("Writing '{}': {}/{}", file, x, z); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + } + } + } + } + region.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + }); + + data.markApplied(); + } + + private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, MigrationProfile data, boolean recursive) { + items.forEach(inTag -> { + final CompoundTag tag = (CompoundTag) inTag; + + changed[0] |= data.replaceStringFromIDs(tag, "id"); + + if (recursive && tag.contains("Items")) { + changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); + } + }); + + return changed[0]; + } + + private static List getAllRegions(File dir, List list) { + if (list == null) { + list = new ArrayList<>(); + } + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + getAllRegions(file, list); + } + else if (file.isFile() && file.getName() + .endsWith(".mca")) { + list.add(file); + } + } + return list; + } + + /** + * Get mod version from string. String should be in format: %d.%d.%d + * + * @param version - {@link String} mod version. + * @return int mod version. + */ + public static int getModVersion(String version) { + if (version.isEmpty()) { + return 0; + } + try { + int res = 0; + final String semanticVersionPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\D*"; + final Matcher matcher = Pattern.compile(semanticVersionPattern) + .matcher(version); + if (matcher.find()) { + if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 20; + if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 12; + if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0xFFF; + } + + return res; + } + catch (Exception e) { + return 0; + } + } + + /** + * Get mod version from integer. String will be in format %d.%d.%d + * + * @param version - mod version in integer form. + * @return {@link String} mod version. + */ + public static String getModVersion(int version) { + int a = (version >> 20) & 0xFF; + int b = (version >> 12) & 0xFF; + int c = version & 0xFFF; + return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); + } + +} diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java new file mode 100644 index 00000000..7adef854 --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -0,0 +1,81 @@ +package ru.bclib.api.datafixer; + +import net.minecraft.nbt.CompoundTag; +import org.jetbrains.annotations.NotNull; +import ru.bclib.config.Configs; +import ru.bclib.config.PathConfig; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +class MigrationProfile { + final Set mods; + final Map idReplacements; + private final PathConfig config; + + MigrationProfile(PathConfig config) { + this.config = config; + + this.mods = Collections.unmodifiableSet(Patch.getALL() + .stream() + .map(p -> p.modID) + .collect(Collectors.toSet())); + + HashMap replacements = new HashMap(); + for (String modID : mods) { + Patch.getALL() + .stream() + .filter(p -> p.modID.equals(modID)) + .forEach(patch -> { + if (currentPatchLevel(modID) < patch.level) { + replacements.putAll(patch.getIDReplacements()); + DataFixerAPI.LOGGER.info("Applying " + patch); + } + else { + DataFixerAPI.LOGGER.info("Ignoring " + patch); + } + }); + } + + this.idReplacements = Collections.unmodifiableMap(replacements); + } + + final public void markApplied() { + for (String modID : mods) { + DataFixerAPI.LOGGER.info("Updating Patch-Level for '{}' from {} to {}", modID, currentPatchLevel(modID), Patch.maxPatchLevel(modID)); + config.setString(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchVersion(modID)); + } + + config.saveChanges(); + } + + public String currentPatchVersion(@NotNull String modID) { + return config.getString(Configs.MAIN_PATCH_CATEGORY, modID, "0.0.0"); + } + + public int currentPatchLevel(@NotNull String modID) { + return DataFixerAPI.getModVersion(currentPatchVersion(modID)); + } + + public boolean hasAnyFixes() { + return idReplacements.size() > 0; + } + + public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key) { + if (!tag.contains(key)) return false; + + final String val = tag.getString(key); + final String replace = idReplacements.get(val); + + if (replace != null) { + DataFixerAPI.LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); + tag.putString(key, replace); + return true; + } + + return false; + } +} diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java new file mode 100644 index 00000000..5bb95aa3 --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -0,0 +1,147 @@ +package ru.bclib.api.datafixer; + +import org.jetbrains.annotations.NotNull; +import ru.bclib.config.PathConfig; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +public abstract class Patch { + private static List ALL = new ArrayList<>(10); + + /** + * The Patch-Level derived from {@link #version} + */ + public final int level; + + /** + * The Patch-Version string + */ + public final String version; + + /** + * The Mod-ID that registered this Patch + * + * @return The ID + */ + + @NotNull + public final String modID; + + static List getALL() { + return ALL; + } + + /** + * register a new Patch + * + * @param patch A #Supplier that will instantiate the new Patch Object + */ + public static void registerPatch(Supplier patch) { + ALL.add(patch.get()); + } + + /** + * Returns the highest Patch-Version that is available for the given mod. If no patches were + * registerd for the mod, this will return 0.0.0 + * + * @param modID The ID of the mod you want to query + * @return The highest Patch-Version that was found + */ + public static String maxPatchVersion(@NotNull String modID) { + return ALL.stream() + .filter(p -> p.modID + .equals(modID)) + .map(p -> p.version) + .reduce((p, c) -> c) + .orElse("0.0.0"); + } + + /** + * Returns the highest patch-level that is available for the given mod. If no patches were + * registerd for the mod, this will return 0 + * + * @param modID The ID of the mod you want to query + * @return The highest Patch-Level that was found + */ + public static int maxPatchLevel(@NotNull String modID) { + return ALL.stream() + .filter(p -> p.modID + .equals(modID)) + .mapToInt(p -> p.level) + .max() + .orElse(0); + } + + /** + * Called by inheriting classes. + *

    + * Performs some sanity checks on the values and might throw a #RuntimeException if any + * inconsistencies are found. + * + * @param modID The ID of the Mod you want to register a patch for. This should be your + * ModID only. The ModID can not be {@code null} or an empty String. + * @param version The mod-version that introduces the patch. This needs Semantic-Version String + * like x.x.x. Developers are responsible for registering their patches in the correct + * order (with increasing versions). You are not allowed to register a new + * Patch with a version lower or equal than + * {@link Patch#maxPatchVersion(String)} + */ + protected Patch(@NotNull String modID, String version) { + //Patchlevels need to be unique and registered in ascending order + if (modID == null || "".equals(modID)) { + throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); + } + + if (version == null || "".equals(version)) { + throw new RuntimeException("Invalid Mod-Version"); + } + + this.version = version; + this.level = DataFixerAPI.getModVersion(version); + if (!ALL.stream() + .filter(p -> p.modID + .equals(modID)) + .noneMatch(p -> p.level >= this.level) || this.level <= 0) { + throw new RuntimeException("[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); + } + + this.modID = modID; + } + + @Override + public String toString() { + return "Patch{" + modID + ':' +version + ':' + level + '}'; + } + + + /** + * Return block data fixes. Fixes will be applied on world load if current patch-level for + * the linked mod is lower than the {@link #level}. + *

    + * The default implementation of this method returns an empty map. + * + * @return The returned Map should contain the replacements. All occurences of the + * {@code KeySet} are replaced with the associated value. + */ + public Map getIDReplacements() { + return new HashMap(); + } + + /** + * Generates ready to use data for all currently registered patches. The list of + * patches is selected by the current patch-level of the world. + *

    + * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the + * world is less + * + * @return a new {@link MigrationProfile} Object. + */ + static MigrationProfile createMigrationData(PathConfig config) { + return new MigrationProfile(config); + } + +} diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index eaf365c0..c89822d4 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -18,7 +18,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.BCLib; import ru.bclib.api.BiomeAPI; -import ru.bclib.api.DataFixerAPI2; +import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.api.WorldDataAPI; import ru.bclib.config.SessionConfig; @@ -52,7 +52,7 @@ public abstract class ServerLevelMixin extends Level { } //DataFixerAPI.fixData(dir); - DataFixerAPI2.fixData(new SessionConfig(BCLib.MOD_ID, "patches", session, world)); + DataFixerAPI.fixData(new SessionConfig(BCLib.MOD_ID, "patches", session, world)); WorldDataAPI.load(new File(dir, "data")); } } From e50ad6b6aa2594efe1222e5ecebe13a47f972c21 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 00:41:25 +0300 Subject: [PATCH 0064/1033] Imports optimised --- src/main/java/ru/bclib/interfaces/CustomItemProvider.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/ru/bclib/interfaces/CustomItemProvider.java b/src/main/java/ru/bclib/interfaces/CustomItemProvider.java index c82b1e17..eb1154c3 100644 --- a/src/main/java/ru/bclib/interfaces/CustomItemProvider.java +++ b/src/main/java/ru/bclib/interfaces/CustomItemProvider.java @@ -3,7 +3,6 @@ package ru.bclib.interfaces; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; -import ru.bclib.registry.BlocksRegistry; public interface CustomItemProvider { /** From cba8637122372ef0d397058d2fc8903ddc737a2b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 01:03:43 +0300 Subject: [PATCH 0065/1033] Anvil model fixes --- src/main/java/ru/bclib/blocks/BaseAnvilBlock.java | 3 --- src/main/java/ru/bclib/items/BaseAnvilItem.java | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 1f138e12..5baf37fb 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -62,9 +62,6 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro return blockId.getPath() + "_top_" + last; } - @Override - public abstract Item asItem(); - @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation blockId) { diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index c55c5191..5cd60bc8 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -16,12 +16,12 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; +import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.ItemModelProvider; import java.util.List; public class BaseAnvilItem extends BlockItem implements ItemModelProvider { - public final static String DESTRUCTION = "destruction"; public BaseAnvilItem(Block block, Properties properties) { @@ -54,6 +54,6 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { public BlockModel getItemModel(ResourceLocation resourceLocation) { Block anvilBlock = getBlock(); ResourceLocation blockId = Registry.BLOCK.getKey(anvilBlock); - return ((ItemModelProvider) anvilBlock).getItemModel(blockId); + return ((BlockModelProvider) anvilBlock).getBlockModel(blockId, anvilBlock.defaultBlockState()); } } From f595cdbbede2e802effee0f22dee9e133ee09c02 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 20 Jul 2021 00:22:45 +0200 Subject: [PATCH 0066/1033] Register BCLib in the `WorldDataAPI` --- src/main/java/ru/bclib/BCLib.java | 2 ++ src/main/java/ru/bclib/api/WorldDataAPI.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index e0936be0..d3174cae 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -5,6 +5,7 @@ import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resources.ResourceLocation; import ru.bclib.api.TagAPI; +import ru.bclib.api.WorldDataAPI; import ru.bclib.config.Configs; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; @@ -23,6 +24,7 @@ public class BCLib implements ModInitializer { BCLSurfaceBuilders.register(); TagAPI.init(); CraftingRecipes.init(); + WorldDataAPI.registerModCache(MOD_ID); Configs.save(); } diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index 842699c5..ff328660 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -38,7 +38,7 @@ public class WorldDataAPI { if (optional.isPresent()) { ModContainer modContainer = optional.get(); if (BCLib.isDevEnvironment()) { - root.putString("version", "63.63.63"); + root.putString("version", "255.255.9999"); } else { root.putString("version", modContainer.getMetadata().getVersion().toString()); From 4ad3ff8277e1f9c63d7d2f38682ddbf9f39e1138 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 20 Jul 2021 00:23:49 +0200 Subject: [PATCH 0067/1033] Using `WorldDataAPI` to keep track of pacth-level --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 45 ++++++++++++++----- .../bclib/api/datafixer/MigrationProfile.java | 13 +++--- .../java/ru/bclib/api/datafixer/Patch.java | 18 ++------ 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index da2ef884..dfdf2f8e 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -5,8 +5,9 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtIo; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.RegionFile; +import ru.bclib.BCLib; +import ru.bclib.api.WorldDataAPI; import ru.bclib.config.Configs; -import ru.bclib.config.SessionConfig; import ru.bclib.util.Logger; import java.io.DataInputStream; @@ -15,26 +16,27 @@ import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DataFixerAPI { static final Logger LOGGER = new Logger("DataFixerAPI"); - public static void fixData(SessionConfig config) { + public static void fixData(File dir) { if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { LOGGER.info("World Patches are disabled"); return; } - final File dir = config.levelFolder; - MigrationProfile data = Patch.createMigrationData(config); + MigrationProfile data = Patch.createMigrationData(WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY)); if (!data.hasAnyFixes()) { LOGGER.info("Everything up to date"); return; } List regions = getAllRegions(dir, null); + boolean[] allOk = {true}; regions.parallelStream() .forEach((file) -> { try { @@ -78,11 +80,23 @@ public class DataFixerAPI { region.close(); } catch (Exception e) { + allOk[0] = false; e.printStackTrace(); } }); - data.markApplied(); + if (allOk[0]) { + data.markApplied(); + WorldDataAPI.saveFile(BCLib.MOD_ID); + } + } + + static CompoundTag patchConfTag = null; + static CompoundTag getPatchData(){ + if (patchConfTag==null) { + patchConfTag = WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); + } + return patchConfTag; } private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, MigrationProfile data, boolean recursive) { @@ -115,6 +129,15 @@ public class DataFixerAPI { return list; } + /** + * register a new Patch + * + * @param patch A #Supplier that will instantiate the new Patch Object + */ + public static void registerPatch(Supplier patch) { + Patch.getALL().add(patch.get()); + } + /** * Get mod version from string. String should be in format: %d.%d.%d * @@ -131,9 +154,9 @@ public class DataFixerAPI { final Matcher matcher = Pattern.compile(semanticVersionPattern) .matcher(version); if (matcher.find()) { - if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 20; - if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 12; - if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0xFFF; + if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 22; + if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 14; + if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0x3FFF; } return res; @@ -150,9 +173,9 @@ public class DataFixerAPI { * @return {@link String} mod version. */ public static String getModVersion(int version) { - int a = (version >> 20) & 0xFF; - int b = (version >> 12) & 0xFF; - int c = version & 0xFFF; + int a = (version >> 22) & 0xFF; + int b = (version >> 14) & 0xFF; + int c = version & 0x3FFF; return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); } diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 7adef854..644b9d6c 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -2,8 +2,6 @@ package ru.bclib.api.datafixer; import net.minecraft.nbt.CompoundTag; import org.jetbrains.annotations.NotNull; -import ru.bclib.config.Configs; -import ru.bclib.config.PathConfig; import java.util.Collections; import java.util.HashMap; @@ -14,9 +12,9 @@ import java.util.stream.Collectors; class MigrationProfile { final Set mods; final Map idReplacements; - private final PathConfig config; + private final CompoundTag config; - MigrationProfile(PathConfig config) { + MigrationProfile(CompoundTag config) { this.config = config; this.mods = Collections.unmodifiableSet(Patch.getALL() @@ -46,14 +44,13 @@ class MigrationProfile { final public void markApplied() { for (String modID : mods) { DataFixerAPI.LOGGER.info("Updating Patch-Level for '{}' from {} to {}", modID, currentPatchLevel(modID), Patch.maxPatchLevel(modID)); - config.setString(Configs.MAIN_PATCH_CATEGORY, modID, Patch.maxPatchVersion(modID)); + config.putString(modID, Patch.maxPatchVersion(modID)); } - - config.saveChanges(); } public String currentPatchVersion(@NotNull String modID) { - return config.getString(Configs.MAIN_PATCH_CATEGORY, modID, "0.0.0"); + if (!config.contains(modID)) return "0.0.0"; + return config.getString(modID); } public int currentPatchLevel(@NotNull String modID) { diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java index 5bb95aa3..1be18145 100644 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -1,13 +1,12 @@ package ru.bclib.api.datafixer; +import net.minecraft.nbt.CompoundTag; import org.jetbrains.annotations.NotNull; -import ru.bclib.config.PathConfig; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Supplier; public abstract class Patch { private static List ALL = new ArrayList<>(10); @@ -24,8 +23,6 @@ public abstract class Patch { /** * The Mod-ID that registered this Patch - * - * @return The ID */ @NotNull @@ -35,15 +32,6 @@ public abstract class Patch { return ALL; } - /** - * register a new Patch - * - * @param patch A #Supplier that will instantiate the new Patch Object - */ - public static void registerPatch(Supplier patch) { - ALL.add(patch.get()); - } - /** * Returns the highest Patch-Version that is available for the given mod. If no patches were * registerd for the mod, this will return 0.0.0 @@ -137,10 +125,10 @@ public abstract class Patch { *

    * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the * world is less - * + * @param config The current patch-level configuration * @return a new {@link MigrationProfile} Object. */ - static MigrationProfile createMigrationData(PathConfig config) { + static MigrationProfile createMigrationData(CompoundTag config) { return new MigrationProfile(config); } From 66851baf0f6aaf6ccd4486f25f699b971dc4c737 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 20 Jul 2021 00:36:59 +0200 Subject: [PATCH 0068/1033] fixed bug where "WorldDataAPI" would always restore an empty Tag. --- src/main/java/ru/bclib/api/WorldDataAPI.java | 3 ++- src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java | 7 ++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index ff328660..fda603d7 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -24,7 +24,6 @@ public class WorldDataAPI { MODS.stream().parallel().forEach(modID -> { File file = new File(dataDir, modID + ".nbt"); CompoundTag root = new CompoundTag(); - TAGS.put(modID, root); if (file.exists()) { try { root = NbtIo.readCompressed(file); @@ -46,6 +45,8 @@ public class WorldDataAPI { saveFile(modID); } } + + TAGS.put(modID, root); }); } diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index c89822d4..58aec99b 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -16,11 +16,9 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import ru.bclib.BCLib; import ru.bclib.api.BiomeAPI; -import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.api.WorldDataAPI; -import ru.bclib.config.SessionConfig; +import ru.bclib.api.datafixer.DataFixerAPI; import java.io.File; import java.util.List; @@ -51,8 +49,7 @@ public abstract class ServerLevelMixin extends Level { dir = dir.getParentFile(); } - //DataFixerAPI.fixData(dir); - DataFixerAPI.fixData(new SessionConfig(BCLib.MOD_ID, "patches", session, world)); WorldDataAPI.load(new File(dir, "data")); + DataFixerAPI.fixData(dir); } } From dcb66ee5e08a854613e1ab7ba3d28ad2231fa5ff Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 20 Jul 2021 00:37:16 +0200 Subject: [PATCH 0069/1033] Better Debug order --- src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index dfdf2f8e..74eae701 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -29,7 +29,8 @@ public class DataFixerAPI { return; } - MigrationProfile data = Patch.createMigrationData(WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY)); + final CompoundTag patchConfig = WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); + MigrationProfile data = Patch.createMigrationData(patchConfig); if (!data.hasAnyFixes()) { LOGGER.info("Everything up to date"); return; From cfa240892f4223805ea054652df7081e9e2d114b Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Tue, 20 Jul 2021 00:42:01 +0200 Subject: [PATCH 0070/1033] Removed original `DataFixerAPI` --- src/main/java/ru/bclib/api/DataFixerAPI.java | 152 ------------------- src/main/java/ru/bclib/api/WorldDataAPI.java | 1 + 2 files changed, 1 insertion(+), 152 deletions(-) delete mode 100644 src/main/java/ru/bclib/api/DataFixerAPI.java diff --git a/src/main/java/ru/bclib/api/DataFixerAPI.java b/src/main/java/ru/bclib/api/DataFixerAPI.java deleted file mode 100644 index e2eaff5b..00000000 --- a/src/main/java/ru/bclib/api/DataFixerAPI.java +++ /dev/null @@ -1,152 +0,0 @@ -package ru.bclib.api; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.storage.RegionFile; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -public class DataFixerAPI { - private static final Map REPLACEMENT = Maps.newHashMap(); - private static final Map FIX_VERSIONS = Maps.newHashMap(); - - public static void fixData(File dir) { - REPLACEMENT.clear(); // API is not finished yet! - if (REPLACEMENT.isEmpty()) { - return; - } - - boolean shoudFix = false; - Collection mods = FabricLoader.getInstance().getAllMods(); - for (ModContainer mod : mods) { - String name = mod.getMetadata().getId(); - int preVersion = WorldDataAPI.getIntModVersion(name); - int version = getModVersion(mod.getMetadata().getVersion().toString()); - if (version > preVersion) { - int fixVersion = FIX_VERSIONS.getOrDefault(name, version); - shoudFix |= fixVersion < version && fixVersion >= preVersion; - } - } - ; - if (!shoudFix) { - return; - } - - List regions = getAllRegions(dir, null); - regions.parallelStream().forEach((file) -> { - try { - System.out.println("Fixing " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), true); - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos)) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - input.close(); - ListTag sections = root.getCompound("Level").getList("Sections", 10); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", 10); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - String name = blockTagCompound.getString("Name"); - String replace = REPLACEMENT.get(name); - if (replace != null) { - blockTagCompound.putString("Name", replace); - changed[0] = true; - } - }); - }); - if (changed[0]) { - System.out.println("Write!"); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - }); - } - - /** - * Register block data fix. Fix will be applied on world load if current mod version will be newer than specified one. - * - * @param modID - {@link String} mod id; - * @param modVersion - {@link String} mod version, should be in format: %d.%d.%d - * @param result - {@link String} new block name; - * @param names - array of {@link String}, old block names to convert. - */ - protected static void addFix(String modID, String modVersion, String result, String... names) { - FIX_VERSIONS.put(modID, getModVersion(modVersion)); - for (String name : names) { - REPLACEMENT.put(name, result); - } - } - - private static List getAllRegions(File dir, List list) { - if (list == null) { - list = Lists.newArrayList(); - } - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - getAllRegions(file, list); - } - else if (file.isFile() && file.getName().endsWith(".mca")) { - list.add(file); - } - } - return list; - } - - /** - * Get mod version from string. String should be in format: %d.%d.%d - * - * @param version - {@link String} mod version. - * @return int mod version. - */ - public static int getModVersion(String version) { - if (version.isEmpty()) { - return 0; - } - try { - String[] values = version.split("\\."); - return Integer.parseInt(values[0]) << 12 | Integer.parseInt(values[1]) << 6 | Integer.parseInt(values[2]); - } - catch (Exception e) { - return 0; - } - } - - /** - * Get mod version from integer. String will be in format %d.%d.%d - * - * @param version - mod version in integer form. - * @return {@link String} mod version. - */ - public static String getModVersion(int version) { - int a = (version >> 12) & 63; - int b = (version >> 6) & 63; - int c = version & 63; - return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); - } -} diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index fda603d7..1ce22f35 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -7,6 +7,7 @@ import net.fabricmc.loader.api.ModContainer; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import ru.bclib.BCLib; +import ru.bclib.api.datafixer.DataFixerAPI; import java.io.File; import java.io.IOException; From 1a4a9ef0a19c28c9ade9543c891d9983fe5efd6c Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 02:57:43 +0300 Subject: [PATCH 0071/1033] Anvil fixes --- .../java/ru/bclib/blocks/BaseAnvilBlock.java | 62 ++++++++++---- .../java/ru/bclib/blocks/BlockProperties.java | 1 + .../java/ru/bclib/items/BaseAnvilItem.java | 24 ++++-- .../bclib/mixin/common/AnvilBlockMixin.java | 20 +++++ .../ru/bclib/mixin/common/AnvilMenuMixin.java | 81 +++++++++++++++++++ src/main/resources/bclib.mixins.common.json | 2 + 6 files changed, 168 insertions(+), 22 deletions(-) create mode 100644 src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java create mode 100644 src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 5baf37fb..e4211688 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -8,6 +8,7 @@ import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; +import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; @@ -27,13 +28,16 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.CustomItemProvider; import ru.bclib.items.BaseAnvilItem; +import ru.bclib.util.MHelper; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Random; public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider, CustomItemProvider { public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; + public IntegerProperty durability; public BaseAnvilBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color)); @@ -42,24 +46,13 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(DESTRUCTION); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack dropStack = new ItemStack(this); - int destruction = state.getValue(DESTRUCTION); - dropStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, destruction); - return Lists.newArrayList(dropStack); - } - - protected String getTop(ResourceLocation blockId, String block) { - if (block.contains("item")) { - return blockId.getPath() + "_top_0"; + if (getMaxDurability() != 3) { + durability = IntegerProperty.create("durability", 0, getMaxDurability()); } - char last = block.charAt(block.length() - 1); - return blockId.getPath() + "_top_" + last; + else { + durability = BlockProperties.DEFAULT_ANVIL_DURABILITY; + } + builder.add(DESTRUCTION, durability); } @Override @@ -96,4 +89,39 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro public BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings) { return new BaseAnvilItem(this, settings); } + + @Override + @SuppressWarnings("deprecation") + public List getDrops(BlockState state, LootContext.Builder builder) { + int destruction = state.getValue(DESTRUCTION); + int durability = state.getValue(getDurabilityProp()); + int value = destruction * getMaxDurability() + durability; + List drops = super.getDrops(state, builder); + ItemStack itemStack = drops.get(0); + itemStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, value); + return drops; + } + + public IntegerProperty getDurabilityProp() { + return durability; + } + + public int getMaxDurability() { + return 3; + } + + public BlockState damageAnvilUse(BlockState state, Random random) { + IntegerProperty durability = getDurabilityProp(); + int value = state.getValue(durability); + if (value < getMaxDurability() && random.nextInt(8) == 0) { + return state.setValue(durability, value + 1); + } + value = state.getValue(DESTRUCTION); + return value < 2 ? state.setValue(DESTRUCTION, value + 1).setValue(durability, 0) : null; + } + + public BlockState damageAnvilFall(BlockState state) { + int destruction = state.getValue(DESTRUCTION); + return destruction < 2 ? state.setValue(DESTRUCTION, destruction + 1) : null; + } } diff --git a/src/main/java/ru/bclib/blocks/BlockProperties.java b/src/main/java/ru/bclib/blocks/BlockProperties.java index b6a71150..15a16c0f 100644 --- a/src/main/java/ru/bclib/blocks/BlockProperties.java +++ b/src/main/java/ru/bclib/blocks/BlockProperties.java @@ -16,6 +16,7 @@ public class BlockProperties { public static final BooleanProperty ACTIVE = BooleanProperty.create("active"); public static final BooleanProperty SMALL = BooleanProperty.create("small"); + public static final IntegerProperty DEFAULT_ANVIL_DURABILITY = IntegerProperty.create("durability", 0, 3); public static final IntegerProperty DESTRUCTION = IntegerProperty.create("destruction", 0, 2); public static final IntegerProperty ROTATION = IntegerProperty.create("rotation", 0, 3); public static final IntegerProperty FULLNESS = IntegerProperty.create("fullness", 0, 3); diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index 5cd60bc8..75865894 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -14,12 +14,14 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.IntegerProperty; import org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.ItemModelProvider; import java.util.List; +import java.util.Locale; public class BaseAnvilItem extends BlockItem implements ItemModelProvider { public final static String DESTRUCTION = "destruction"; @@ -34,7 +36,16 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { ItemStack stack = blockPlaceContext.getItemInHand(); int destruction = stack.getOrCreateTag().getInt(DESTRUCTION); if (blockState != null) { - blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); + BaseAnvilBlock block = (BaseAnvilBlock) blockState.getBlock(); + IntegerProperty durabilityProp = block.getDurabilityProp(); + if (destruction == 0) { + blockState = blockState.setValue(durabilityProp, 0).setValue(BaseAnvilBlock.DESTRUCTION, 0); + } + else { + int destructionValue = destruction / block.getMaxDurability(); + int durabilityValue = destruction - destructionValue * block.getMaxDurability(); + blockState = blockState.setValue(durabilityProp, durabilityValue).setValue(BaseAnvilBlock.DESTRUCTION, destructionValue); + } } return blockState; } @@ -42,10 +53,13 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { @Override @Environment(EnvType.CLIENT) public void appendHoverText(ItemStack itemStack, @Nullable Level level, List list, TooltipFlag tooltipFlag) { - super.appendHoverText(itemStack, level, list, tooltipFlag); - int l = itemStack.getOrCreateTag().getInt(DESTRUCTION); - if (l > 0) { - list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + l)); + int destruction = itemStack.getOrCreateTag().getInt(DESTRUCTION); + if (destruction > 0) { + BaseAnvilBlock block = (BaseAnvilBlock) ((BaseAnvilItem) itemStack.getItem()).getBlock(); + int maxValue = block.getMaxDurability() * 3; + float damage = maxValue - destruction; + String percents = String.format(Locale.ROOT, "%.0F%%", damage); + list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + percents)); } } diff --git a/src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java new file mode 100644 index 00000000..0c296df3 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java @@ -0,0 +1,20 @@ +package ru.bclib.mixin.common; + +import net.minecraft.world.level.block.AnvilBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import ru.bclib.blocks.BaseAnvilBlock; + +@Mixin(AnvilBlock.class) +public class AnvilBlockMixin { + @Inject(method = "damage", at = @At("HEAD"), cancellable = true) + private static void bclib_anvilDamage(BlockState state, CallbackInfoReturnable info) { + if (state.getBlock() instanceof BaseAnvilBlock) { + BaseAnvilBlock anvil = (BaseAnvilBlock) state.getBlock(); + info.setReturnValue(anvil.damageAnvilFall(state)); + } + } +} diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java new file mode 100644 index 00000000..345b62ab --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -0,0 +1,81 @@ +package ru.bclib.mixin.common; + +import net.minecraft.tags.BlockTags; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.inventory.ContainerLevelAccess; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.inventory.ItemCombinerMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.AnvilBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import ru.bclib.blocks.BaseAnvilBlock; + +@Mixin(AnvilMenu.class) +public abstract class AnvilMenuMixin extends ItemCombinerMenu { + @Shadow + private int repairItemCountCost; + + @Final + @Shadow + private DataSlot cost; + + public AnvilMenuMixin(@Nullable MenuType menuType, int i, Inventory inventory, ContainerLevelAccess containerLevelAccess) { + super(menuType, i, inventory, containerLevelAccess); + } + + @Inject(method = "onTake", at = @At("HEAD"), cancellable = true) + protected void bclib_onTakeAnvilOutput(Player player, ItemStack stack, CallbackInfo info) { + this.access.execute((level, blockPos) -> { + BlockState blockState = level.getBlockState(blockPos); + if (blockState.getBlock() instanceof BaseAnvilBlock) { + if (!player.getAbilities().instabuild) { + player.giveExperienceLevels(-this.cost.get()); + } + + this.inputSlots.setItem(0, ItemStack.EMPTY); + if (this.repairItemCountCost > 0) { + ItemStack itemStack2 = this.inputSlots.getItem(1); + if (!itemStack2.isEmpty() && itemStack2.getCount() > this.repairItemCountCost) { + itemStack2.shrink(this.repairItemCountCost); + this.inputSlots.setItem(1, itemStack2); + } + else { + this.inputSlots.setItem(1, ItemStack.EMPTY); + } + } + else { + this.inputSlots.setItem(1, ItemStack.EMPTY); + } + + this.cost.set(0); + + if (!player.getAbilities().instabuild && blockState.is(BlockTags.ANVIL) && player.getRandom() + .nextFloat() < 0.12F) { + BlockState blockState2 = AnvilBlock.damage(blockState); + if (blockState2 == null) { + level.removeBlock(blockPos, false); + level.levelEvent(1029, blockPos, 0); + } + else { + level.setBlock(blockPos, blockState2, 2); + level.levelEvent(1030, blockPos, 0); + } + } + else { + level.levelEvent(1030, blockPos, 0); + } + } + info.cancel(); + }); + } +} diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index a357113d..01d3e36b 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -12,6 +12,8 @@ "RecipeManagerMixin", "BoneMealItemMixin", "ServerLevelMixin", + "AnvilBlockMixin", + "AnvilMenuMixin", "TagLoaderMixin" ], "injectors": { From 450b7d420565e525dbbbdac9eda6fd820d53e196 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 03:23:17 +0300 Subject: [PATCH 0072/1033] Small drop fix --- .../java/ru/bclib/blocks/BaseAnvilBlock.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index e4211688..9aca2c1d 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -8,11 +8,10 @@ import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -21,6 +20,7 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; @@ -28,8 +28,8 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.CustomItemProvider; import ru.bclib.items.BaseAnvilItem; -import ru.bclib.util.MHelper; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -96,10 +96,13 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro int destruction = state.getValue(DESTRUCTION); int durability = state.getValue(getDurabilityProp()); int value = destruction * getMaxDurability() + durability; - List drops = super.getDrops(state, builder); - ItemStack itemStack = drops.get(0); - itemStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, value); - return drops; + ItemStack tool = builder.getParameter(LootContextParams.TOOL); + if (tool != null && tool.getItem() instanceof PickaxeItem) { + ItemStack itemStack = new ItemStack(this); + itemStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, value); + return Lists.newArrayList(itemStack); + } + return Collections.emptyList(); } public IntegerProperty getDurabilityProp() { From 1dc2fea7e2bedf14763f52f8e5d0250027958a1a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 03:33:52 +0300 Subject: [PATCH 0073/1033] Translations --- src/main/java/ru/bclib/items/BaseAnvilItem.java | 2 +- src/main/resources/assets/bclib/lang/en_us.json | 3 +++ src/main/resources/assets/bclib/lang/ru_ru.json | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 src/main/resources/assets/bclib/lang/en_us.json create mode 100644 src/main/resources/assets/bclib/lang/ru_ru.json diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index 75865894..465b82ad 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -58,7 +58,7 @@ public class BaseAnvilItem extends BlockItem implements ItemModelProvider { BaseAnvilBlock block = (BaseAnvilBlock) ((BaseAnvilItem) itemStack.getItem()).getBlock(); int maxValue = block.getMaxDurability() * 3; float damage = maxValue - destruction; - String percents = String.format(Locale.ROOT, "%.0F%%", damage); + String percents = String.format(Locale.ROOT, "%.0f%%", damage); list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + percents)); } } diff --git a/src/main/resources/assets/bclib/lang/en_us.json b/src/main/resources/assets/bclib/lang/en_us.json new file mode 100644 index 00000000..b89551db --- /dev/null +++ b/src/main/resources/assets/bclib/lang/en_us.json @@ -0,0 +1,3 @@ +{ + "message.bclib.anvil_damage": "§cDamage" +} \ No newline at end of file diff --git a/src/main/resources/assets/bclib/lang/ru_ru.json b/src/main/resources/assets/bclib/lang/ru_ru.json new file mode 100644 index 00000000..092f7299 --- /dev/null +++ b/src/main/resources/assets/bclib/lang/ru_ru.json @@ -0,0 +1,3 @@ +{ + "message.bclib.anvil_damage": "§cПовреждение" +} \ No newline at end of file From 5455034da3cd4a2e37b1c47d8dd0d353f2a9f79b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 03:39:58 +0300 Subject: [PATCH 0074/1033] Small changes --- .../java/ru/bclib/mixin/common/AnvilMenuMixin.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java index 345b62ab..9417f9b0 100644 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -38,6 +38,7 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu { this.access.execute((level, blockPos) -> { BlockState blockState = level.getBlockState(blockPos); if (blockState.getBlock() instanceof BaseAnvilBlock) { + info.cancel(); if (!player.getAbilities().instabuild) { player.giveExperienceLevels(-this.cost.get()); } @@ -59,15 +60,15 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu { this.cost.set(0); - if (!player.getAbilities().instabuild && blockState.is(BlockTags.ANVIL) && player.getRandom() - .nextFloat() < 0.12F) { - BlockState blockState2 = AnvilBlock.damage(blockState); - if (blockState2 == null) { + if (!player.getAbilities().instabuild && blockState.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { + BaseAnvilBlock anvil = (BaseAnvilBlock) blockState.getBlock(); + BlockState damaged = anvil.damageAnvilUse(blockState, player.getRandom()); + if (damaged == null) { level.removeBlock(blockPos, false); level.levelEvent(1029, blockPos, 0); } else { - level.setBlock(blockPos, blockState2, 2); + level.setBlock(blockPos, damaged, 2); level.levelEvent(1030, blockPos, 0); } } @@ -75,7 +76,6 @@ public abstract class AnvilMenuMixin extends ItemCombinerMenu { level.levelEvent(1030, blockPos, 0); } } - info.cancel(); }); } } From e5e948ef4f084d668bb020af428a799e9f05c335 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 04:54:41 +0300 Subject: [PATCH 0075/1033] Moved TagHelper inside TagAPI --- src/main/java/ru/bclib/api/TagAPI.java | 151 ++++++++++++++++-- .../ru/bclib/mixin/common/AnvilMenuMixin.java | 1 - .../ru/bclib/mixin/common/TagLoaderMixin.java | 4 +- .../java/ru/bclib/registry/ItemsRegistry.java | 12 +- src/main/java/ru/bclib/util/TagHelper.java | 138 ---------------- 5 files changed, 146 insertions(+), 160 deletions(-) delete mode 100644 src/main/java/ru/bclib/util/TagHelper.java diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 6ca55627..622c4834 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,7 +1,11 @@ package ru.bclib.api; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; import net.fabricmc.fabric.api.tag.TagRegistry; +import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; @@ -9,14 +13,19 @@ import net.minecraft.tags.Tag.Named; import net.minecraft.tags.TagCollection; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; +import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; -import ru.bclib.util.TagHelper; +import java.util.Map; +import java.util.Set; import java.util.function.Supplier; public class TagAPI { + private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); + private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); + // Block Tags public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); public static final Tag.Named GEN_TERRAIN = makeBlockTag(BCLib.MOD_ID, "gen_terrain"); @@ -114,8 +123,8 @@ public class TagAPI { * @param block - {@link Block}. */ public static void addNetherGround(Block block) { - TagHelper.addTag(NETHER_GROUND, block); - TagHelper.addTag(GEN_TERRAIN, block); + addTag(NETHER_GROUND, block); + addTag(GEN_TERRAIN, block); } /** @@ -124,21 +133,137 @@ public class TagAPI { * @param block - {@link Block}. */ public static void addEndGround(Block block) { - TagHelper.addTag(GEN_TERRAIN, block); - TagHelper.addTag(END_GROUND, block); + addTag(GEN_TERRAIN, block); + addTag(END_GROUND, block); } /** * Initializes basic tags. Should be called only in BCLib main class. */ public static void init() { - TagHelper.addTag(BOOKSHELVES, Blocks.BOOKSHELF); - TagHelper.addTag(GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - TagHelper.addTag(NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - TagHelper.addTag(END_GROUND, Blocks.END_STONE); - TagHelper.addTag(BLOCK_CHEST, Blocks.CHEST); - TagHelper.addTag(ITEM_CHEST, Items.CHEST); - TagHelper.addTag(IRON_INGOTS, Items.IRON_INGOT); - TagHelper.addTag(FURNACES, Blocks.FURNACE); + addTag(BOOKSHELVES, Blocks.BOOKSHELF); + addTag(GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + addTag(NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + addTag(END_GROUND, Blocks.END_STONE); + addTag(BLOCK_CHEST, Blocks.CHEST); + addTag(ITEM_CHEST, Items.CHEST); + addTag(IRON_INGOTS, Items.IRON_INGOT); + addTag(FURNACES, Blocks.FURNACE); + } + + /** + * Adds one Tag to multiple Blocks. + *

    + * Example: + *

    {@code  Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
    +	 * addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);}
    + *

    + * The call will reserve the Tag. The Tag is added to the blocks once + * {@link #apply(String, Map)} was executed. + * + * @param tag The new Tag + * @param blocks One or more blocks that should receive the Tag. + */ + public static void addTag(Tag.Named tag, Block... blocks) { + ResourceLocation tagID = tag.getName(); + Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); + for (Block block : blocks) { + ResourceLocation id = Registry.BLOCK.getKey(block); + if (id != Registry.BLOCK.getDefaultKey()) { + set.add(id); + } + } + } + + /** + * Adds one Tag to multiple Items. + *

    + * Example: + *

    {@code  Tag.Named METALS = makeBlockTag("mymod", "metals");
    +	 * addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);}
    + *

    + * The call will reserve the Tag. The Tag is added to the items once + * {@link #apply(String, Map)} was executed. + * + * @param tag The new Tag + * @param items One or more item that should receive the Tag. + */ + public static void addTag(Tag.Named tag, ItemLike... items) { + ResourceLocation tagID = tag.getName(); + Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); + for (ItemLike item : items) { + ResourceLocation id = Registry.ITEM.getKey(item.asItem()); + if (id != Registry.ITEM.getDefaultKey()) { + set.add(id); + } + } + } + + /** + * Adds multiple Tags to one Item. + *

    + * The call will reserve the Tags. The Tags are added to the Item once + * * {@link #apply(String, Map)} was executed. + * + * @param item The Item that will receive all Tags + * @param tags One or more Tags + */ + @SafeVarargs + public static void addTags(ItemLike item, Tag.Named... tags) { + for (Tag.Named tag : tags) { + addTag(tag, item); + } + } + + /** + * Adds multiple Tags to one Block. + *

    + * The call will reserve the Tags. The Tags are added to the Block once + * * {@link #apply(String, Map)} was executed. + * + * @param block The Block that will receive all Tags + * @param tags One or more Tags + */ + @SafeVarargs + public static void addTags(Block block, Tag.Named... tags) { + for (Tag.Named tag : tags) { + addTag(tag, block); + } + } + + /** + * Adds all {@code ids} to the {@code builder}. + * + * @param builder + * @param ids + * @return The Builder passed as {@code builder}. + */ + public static Tag.Builder apply(Tag.Builder builder, Set ids) { + ids.forEach(value -> builder.addElement(value, "Better End Code")); + return builder; + } + + /** + * Automatically called in {@link net.minecraft.tags.TagLoader#loadAndBuild(ResourceManager)}. + *

    + * In most cases there is no need to call this Method manually. + * + * @param directory The name of the Tag-directory. Should be either "tags/blocks" or + * "tags/items". + * @param tagsMap The map that will hold the registered Tags + * @return The {@code tagsMap} Parameter. + */ + public static Map apply(String directory, Map tagsMap) { + Map> endTags = null; + if ("tags/blocks".equals(directory)) { + endTags = TAGS_BLOCK; + } + else if ("tags/items".equals(directory)) { + endTags = TAGS_ITEM; + } + if (endTags != null) { + endTags.forEach((id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids)); + } + return tagsMap; } } diff --git a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java index 9417f9b0..a8391228 100644 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java @@ -9,7 +9,6 @@ import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.inventory.ItemCombinerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index 0fa5be52..4d89c067 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -7,7 +7,7 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; -import ru.bclib.util.TagHelper; +import ru.bclib.api.TagAPI; import java.util.Map; @@ -18,6 +18,6 @@ public class TagLoaderMixin { @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) public Map be_modifyTags(Map tagsMap) { - return TagHelper.apply(directory, tagsMap); + return TagAPI.apply(directory, tagsMap); } } diff --git a/src/main/java/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemsRegistry.java index 2f491b49..dde6333b 100644 --- a/src/main/java/ru/bclib/registry/ItemsRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemsRegistry.java @@ -27,7 +27,7 @@ import ru.bclib.items.ModelProviderItem; import ru.bclib.items.tool.BaseAxeItem; import ru.bclib.items.tool.BaseHoeItem; import ru.bclib.items.tool.BasePickaxeItem; -import ru.bclib.util.TagHelper; +import ru.bclib.api.TagAPI; public abstract class ItemsRegistry extends BaseRegistry { @@ -54,19 +54,19 @@ public abstract class ItemsRegistry extends BaseRegistry { registerItem(id, item, BaseRegistry.getModItems(id.getNamespace())); if (item instanceof ShovelItem) { - TagHelper.addTag((Tag.Named) FabricToolTags.SHOVELS, item); + TagAPI.addTag((Tag.Named) FabricToolTags.SHOVELS, item); } else if (item instanceof SwordItem) { - TagHelper.addTag((Tag.Named) FabricToolTags.SWORDS, item); + TagAPI.addTag((Tag.Named) FabricToolTags.SWORDS, item); } else if (item instanceof BasePickaxeItem) { - TagHelper.addTag((Tag.Named) FabricToolTags.PICKAXES, item); + TagAPI.addTag((Tag.Named) FabricToolTags.PICKAXES, item); } else if (item instanceof BaseAxeItem) { - TagHelper.addTag((Tag.Named) FabricToolTags.AXES, item); + TagAPI.addTag((Tag.Named) FabricToolTags.AXES, item); } else if (item instanceof BaseHoeItem) { - TagHelper.addTag((Tag.Named) FabricToolTags.HOES, item); + TagAPI.addTag((Tag.Named) FabricToolTags.HOES, item); } return item; diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java deleted file mode 100644 index d21df3ff..00000000 --- a/src/main/java/ru/bclib/util/TagHelper.java +++ /dev/null @@ -1,138 +0,0 @@ -package ru.bclib.util; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.tags.Tag; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; - -import java.util.Map; -import java.util.Set; - -/** - * Utility functions to manage Minecraft Tags - */ -public class TagHelper { - private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); - private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); - - /** - * Adds one Tag to multiple Blocks. - *

    - * Example: - *

    {@code  Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
    -	 * TagHelper.addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);}
    - *

    - * The call will reserve the Tag. The Tag is added to the blocks once - * {@link #apply(String, Map)} was executed. - * - * @param tag The new Tag - * @param blocks One or more blocks that should receive the Tag. - */ - public static void addTag(Tag.Named tag, Block... blocks) { - ResourceLocation tagID = tag.getName(); - Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (Block block : blocks) { - ResourceLocation id = Registry.BLOCK.getKey(block); - if (id != Registry.BLOCK.getDefaultKey()) { - set.add(id); - } - } - } - - /** - * Adds one Tag to multiple Items. - *

    - * Example: - *

    {@code  Tag.Named METALS = makeBlockTag("mymod", "metals");
    -	 * TagHelper.addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);}
    - *

    - * The call will reserve the Tag. The Tag is added to the items once - * {@link #apply(String, Map)} was executed. - * - * @param tag The new Tag - * @param items One or more item that should receive the Tag. - */ - public static void addTag(Tag.Named tag, ItemLike... items) { - ResourceLocation tagID = tag.getName(); - Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (ItemLike item : items) { - ResourceLocation id = Registry.ITEM.getKey(item.asItem()); - if (id != Registry.ITEM.getDefaultKey()) { - set.add(id); - } - } - } - - /** - * Adds multiple Tags to one Item. - *

    - * The call will reserve the Tags. The Tags are added to the Item once - * * {@link #apply(String, Map)} was executed. - * - * @param item The Item that will receive all Tags - * @param tags One or more Tags - */ - @SafeVarargs - public static void addTags(ItemLike item, Tag.Named... tags) { - for (Tag.Named tag : tags) { - addTag(tag, item); - } - } - - /** - * Adds multiple Tags to one Block. - *

    - * The call will reserve the Tags. The Tags are added to the Block once - * * {@link #apply(String, Map)} was executed. - * - * @param block The Block that will receive all Tags - * @param tags One or more Tags - */ - @SafeVarargs - public static void addTags(Block block, Tag.Named... tags) { - for (Tag.Named tag : tags) { - addTag(tag, block); - } - } - - /** - * Adds all {@code ids} to the {@code builder}. - * - * @param builder - * @param ids - * @return The Builder passed as {@code builder}. - */ - public static Tag.Builder apply(Tag.Builder builder, Set ids) { - ids.forEach(value -> builder.addElement(value, "Better End Code")); - return builder; - } - - /** - * Automatically called in {@link net.minecraft.tags.TagLoader#loadAndBuild(ResourceManager)}. - *

    - * In most cases there is no need to call this Method manually. - * - * @param directory The name of the Tag-directory. Should be either "tags/blocks" or - * "tags/items". - * @param tagsMap The map that will hold the registered Tags - * @return The {@code tagsMap} Parameter. - */ - public static Map apply(String directory, Map tagsMap) { - Map> endTags = null; - if ("tags/blocks".equals(directory)) { - endTags = TAGS_BLOCK; - } - else if ("tags/items".equals(directory)) { - endTags = TAGS_ITEM; - } - if (endTags != null) { - endTags.forEach((id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids)); - } - return tagsMap; - } -} From cdc9d85b530b5391c8360002103eaca21bb3714a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Tue, 20 Jul 2021 23:55:40 +0300 Subject: [PATCH 0076/1033] Shader enhancements, disable when Optifine is installed --- .../bclib/mixin/client/TextureAtlasMixin.java | 113 ++++++++++-------- .../shaders/core/rendertype_cutout.fsh | 17 ++- .../shaders/core/rendertype_entity_cutout.fsh | 17 ++- ...endertype_item_entity_translucent_cull.fsh | 17 ++- .../shaders/core/rendertype_solid.fsh | 13 +- 5 files changed, 103 insertions(+), 74 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java index fc6ba619..bdf3204a 100644 --- a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java +++ b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java @@ -2,6 +2,7 @@ package ru.bclib.mixin.client; import com.mojang.blaze3d.platform.NativeImage; import net.fabricmc.fabric.impl.client.texture.FabricSprite; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.resources.ResourceLocation; @@ -18,71 +19,79 @@ import java.io.IOException; @Mixin(TextureAtlas.class) public class TextureAtlasMixin { + private static final int EMISSIVE_ALPHA = 253 << 24; private boolean bclib_modifyAtlas; @Inject(method = "*", at = @At("TAIL")) private void bclib_onAtlasInit(ResourceLocation resourceLocation, CallbackInfo info) { - bclib_modifyAtlas = resourceLocation.toString().equals("minecraft:textures/atlas/blocks.png"); + boolean hasOptifine = FabricLoader.getInstance().isModLoaded("optifabric"); + bclib_modifyAtlas = !hasOptifine && resourceLocation.toString().equals("minecraft:textures/atlas/blocks.png"); } @Inject(method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite$Info;IIIII)Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;", at = @At("HEAD"), cancellable = true) private void bclib_loadSprite(ResourceManager resourceManager, TextureAtlasSprite.Info spriteInfo, int atlasWidth, int atlasHeight, int maxLevel, int posX, int posY, CallbackInfoReturnable info) { + if (!bclib_modifyAtlas) { + return; + } + ResourceLocation location = spriteInfo.name(); - if (bclib_modifyAtlas && location.getPath().startsWith("block")) { - ResourceLocation emissiveLocation = new ResourceLocation( - location.getNamespace(), - "textures/" + location.getPath() + "_e.png" - ); - if (resourceManager.hasResource(emissiveLocation)) { - NativeImage sprite = null; - NativeImage emission = null; - try { - ResourceLocation spriteLocation = new ResourceLocation( - location.getNamespace(), - "textures/" + location.getPath() + ".png" - ); - Resource resource = resourceManager.getResource(spriteLocation); - sprite = NativeImage.read(resource.getInputStream()); - resource.close(); - - resource = resourceManager.getResource(emissiveLocation); - emission = NativeImage.read(resource.getInputStream()); - resource.close(); - } - catch (IOException e) { - BCLib.LOGGER.warning(e.getMessage()); - } - if (sprite != null && emission != null) { - int width = Math.min(sprite.getWidth(), emission.getWidth()); - int height = Math.min(sprite.getHeight(), emission.getHeight()); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - int argb = emission.getPixelRGBA(x, y); - int alpha = (argb >> 24) & 255; - if (alpha > 127) { - int r = (argb >> 16) & 255; - int g = (argb >> 8) & 255; - int b = argb & 255; - if (r > 0 || g > 0 || b > 0) { - argb = (argb & 0x00FFFFFF) | (250 << 24); - sprite.setPixelRGBA(x, y, argb); - } + if (!location.getPath().startsWith("block")) { + return; + } + + ResourceLocation emissiveLocation = new ResourceLocation( + location.getNamespace(), + "textures/" + location.getPath() + "_e.png" + ); + if (resourceManager.hasResource(emissiveLocation)) { + NativeImage sprite = null; + NativeImage emission = null; + try { + ResourceLocation spriteLocation = new ResourceLocation( + location.getNamespace(), + "textures/" + location.getPath() + ".png" + ); + Resource resource = resourceManager.getResource(spriteLocation); + sprite = NativeImage.read(resource.getInputStream()); + resource.close(); + + resource = resourceManager.getResource(emissiveLocation); + emission = NativeImage.read(resource.getInputStream()); + resource.close(); + } + catch (IOException e) { + BCLib.LOGGER.warning(e.getMessage()); + } + if (sprite != null && emission != null) { + int width = Math.min(sprite.getWidth(), emission.getWidth()); + int height = Math.min(sprite.getHeight(), emission.getHeight()); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + int argb = emission.getPixelRGBA(x, y); + int alpha = (argb >> 24) & 255; + if (alpha > 127) { + int r = (argb >> 16) & 255; + int g = (argb >> 8) & 255; + int b = argb & 255; + if (r > 0 || g > 0 || b > 0) { + argb = (argb & 0x00FFFFFF) | EMISSIVE_ALPHA; + sprite.setPixelRGBA(x, y, argb); } } } - TextureAtlas self = (TextureAtlas) (Object) this; - FabricSprite result = new FabricSprite( - self, - spriteInfo, - maxLevel, - atlasWidth, - atlasHeight, - posX, - posY, - sprite - ); - info.setReturnValue(result); } + TextureAtlas self = (TextureAtlas) (Object) this; + FabricSprite result = new FabricSprite( + self, + spriteInfo, + maxLevel, + atlasWidth, + atlasHeight, + posX, + posY, + sprite + ); + info.setReturnValue(result); } } } diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh index 9687414d..46538f7e 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh @@ -24,19 +24,24 @@ vec3 rgbToHSV(vec3 color) { } vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +// Value between 252 and 254 +bool isEmissive(float alpha) { + return 0.9883 < alpha && alpha < 0.9961; } void main() { vec4 tex = texture(Sampler0, texCoord0); if (tex.a < 0.1) { - discard; - } + discard; + } vec4 color = tex * ColorModulator; vec4 vertex = vertexColor; - if (tex.a < 0.99) { + if (isEmissive(tex.a)) { vec3 hsv = rgbToHSV(vertex.rgb); hsv.z = 1.0; vertex.rgb = hsvToRGB(hsv); diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh index f00c54f9..7fe88bc4 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh @@ -26,20 +26,25 @@ vec3 rgbToHSV(vec3 color) { } vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +// Value between 252 and 254 +bool isEmissive(float alpha) { + return 0.9883 < alpha && alpha < 0.9961; } void main() { vec4 tex = texture(Sampler0, texCoord0); if (tex.a < 0.1) { - discard; - } + discard; + } vec4 color = tex * ColorModulator; color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); vec4 vertex = vertexColor * lightMapColor; - if (tex.a < 0.99) { + if (isEmissive(tex.a)) { vec3 hsv = rgbToHSV(vertex.rgb); hsv.z = 1.0; vertex.rgb = hsvToRGB(hsv); diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh index 2293003e..0897b74f 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh @@ -25,20 +25,25 @@ vec3 rgbToHSV(vec3 color) { } vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +// Value between 252 and 254 +bool isEmissive(float alpha) { + return 0.9883 < alpha && alpha < 0.9961; } void main() { vec4 tex = texture(Sampler0, texCoord0); if (tex.a < 0.1) { - discard; - } + discard; + } vec4 color = tex * ColorModulator; color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); vec4 vertex = vertexColor; - if (tex.a < 0.99) { + if (isEmissive(tex.a)) { vec3 hsv = rgbToHSV(vertex.rgb); hsv.z = 1.0; vertex.rgb = hsvToRGB(hsv); diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh index 19222825..cbe64a51 100644 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh +++ b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh @@ -24,16 +24,21 @@ vec3 rgbToHSV(vec3 color) { } vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); + vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); + return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); +} + +// Value between 252 and 254 +bool isEmissive(float alpha) { + return 0.9883 < alpha && alpha < 0.9961; } void main() { vec4 tex = texture(Sampler0, texCoord0); vec4 color = tex * ColorModulator; vec4 vertex = vertexColor; - if (tex.a < 0.99) { + if (isEmissive(tex.a)) { vec3 hsv = rgbToHSV(vertex.rgb); hsv.z = 1.0; vertex.rgb = hsvToRGB(hsv); From 2bfc98540385af2f6958a713fb70b7c8dbd3b8bc Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 02:09:57 +0300 Subject: [PATCH 0077/1033] Description update --- README.md | 99 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 79 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 814d89b5..67b2b426 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,92 @@ [![](https://jitpack.io/v/paulevsGitch/BCLib.svg)](https://jitpack.io/#paulevsGitch/BCLib) # BCLib -BCLib is a library mod for BetterX team mods, developed for Fabric, MC 1.16.5 +BCLib is a library mod for BetterX team mods, developed for Fabric, MC 1.17.1 ## Features: +### Rendering +* Emissive textures (with _e suffix) + * Can be applied to Solid and Transparent blocks; + * Can be changed/added with resourcepacks; + * Incompatible with Sodium and Canvas (just will be not rendered); + * Incompatible with Iris shaders (Iris without shaders works fine). +* Procedural block and item models (from paterns or from code); +* Block render interfaces. + ### API: -* Simple Mod Integration API; -* Structure Features API; -* World Data API; -* Bonemeal API; -* Features API; -* Biome API; -* Tag API. +* Simple Mod Integration API: + * Get mod inner methods, classes and objects on runtime. +* Structure Features API: + * Sructure Features with automatical registration, Helpers and math stuff. +* World Data API: + * World fixers for comfortable migration between mod versions when content was removed; + * Support for Block name changes and Tile Entities (WIP). +* Bonemeal API: + * Add custom spreadable blocks; + * Add custom plants grow with weight, biomes and other checks; + * Custom underwater plants. +* Features API: + * Features with automatical registration, Helpers and math. +* Biome API: + * Biome wrapper around MC biomes; + * Custom biome data storage; + * Custom fog density. +* Tag API: + * Pre-builded set of tags; + * Dynamical tag registration with code; + * Adding blocks and items into tags at runtime. ### Libs: -* Spline library (simple); -* Recipe manager; -* Noise library; -* Math library; -* SDF library. +* Spline library (simple): + * Helper to create simple splines as set of points; + * Some basic operation with splines; + * Converting splines to SDF. +* Recipe manager: + * Register recipes from code with configs and ingredients check. +* Noise library: + * Voronoi noise and Open Simplex Noise. +* Math library: + * Many basic math functions that are missing in MC. +* SDF library: + * Implementation of Signed Distance Functions; + * Different SDF Operations and Primitives; + * Different materials for SDF Primitives; + * Block post-processing; + * Feature generation using SDF. ### Helpers And Utils: -* Custom surface builders; -* Translation helper; -* Weighted list; -* Block helper. +* Custom surface builders. +* Translation helper: + * Generates translation template. +* Weighted list: + * A list of objects by weight; +* Weighted Tree: + * Fast approach for big weight structures; +* Block helper: + * Some useful functions to operate with blocks; -### Rendering: -* Procedural block models (from paterns or from code); -* Block render layer interface. +### Pre-Defined Blocks and Items: +* Most basic blocks from MC; +* Automatic item & block model generation; + +### Configs: +* Custom config system based on Json; +* Hierarchical configs; +* Different entry types; +* Only-changes saves. + +### Interfaces: +* BlockModelProvider: + * Allows block to return custom model and blockstate. +* ItemModelProvider: + * Allows block to return custom item model. +* CustomColorProvider: + * Make available to add block and item color provider. +* RenderLayerProvider: + * Determine block render layer (Transparent and Translucent). +* PostInitable: + * Allows block to init something after all mods are loaded. +* CustomItemProvider: + * Allows block to change its registered item (example - signs, water lilies). ## Importing: * Clone repo From 5fbb2e03b55c2ac52945a9643a4d2f7dbbcd1e16 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 12:27:00 +0300 Subject: [PATCH 0078/1033] Torus SDF --- .../java/ru/bclib/sdf/primitive/SDFTorus.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/ru/bclib/sdf/primitive/SDFTorus.java diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java b/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java new file mode 100644 index 00000000..2dfcb23d --- /dev/null +++ b/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java @@ -0,0 +1,24 @@ +package ru.bclib.sdf.primitive; + +import ru.bclib.util.MHelper; + +public class SDFTorus extends SDFPrimitive { + private float radiusSmall; + private float radiusBig; + + public SDFTorus setBigRadius(float radius) { + this.radiusBig = radiusBig; + return this; + } + + public SDFTorus setSmallRadius(float radius) { + this.radiusSmall = radiusSmall; + return this; + } + + @Override + public float getDistance(float x, float y, float z) { + float nx = MHelper.length(x, z) - radiusBig; + return MHelper.length(nx, y) - radiusSmall; + } +} From 51bff6b2ca1eae56e2bc738f17552c606d54a1e6 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 13:28:27 +0300 Subject: [PATCH 0079/1033] Small fix --- src/main/java/ru/bclib/sdf/primitive/SDFTorus.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java b/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java index 2dfcb23d..e7540c93 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java @@ -7,12 +7,12 @@ public class SDFTorus extends SDFPrimitive { private float radiusBig; public SDFTorus setBigRadius(float radius) { - this.radiusBig = radiusBig; + this.radiusBig = radius; return this; } public SDFTorus setSmallRadius(float radius) { - this.radiusSmall = radiusSmall; + this.radiusSmall = radius; return this; } From a48c350aa24be6f0ba72181298edabfb30a0f6b0 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 13:32:02 +0300 Subject: [PATCH 0080/1033] Tag name changes, workbenches tag --- src/main/java/ru/bclib/api/TagAPI.java | 42 ++++++++++--------- .../client/EnchantingTableBlockMixin.java | 2 +- .../mixin/common/EnchantmentMenuMixin.java | 12 +++--- .../ru/bclib/recipes/CraftingRecipes.java | 22 +++++----- .../java/ru/bclib/util/StructureHelper.java | 6 +-- .../ru/bclib/world/features/BCLFeature.java | 2 +- .../world/features/NBTStructureFeature.java | 6 +-- 7 files changed, 47 insertions(+), 45 deletions(-) diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 622c4834..c3b04638 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -27,16 +27,17 @@ public class TagAPI { private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); // Block Tags - public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); - public static final Tag.Named GEN_TERRAIN = makeBlockTag(BCLib.MOD_ID, "gen_terrain"); - public static final Tag.Named NETHER_GROUND = makeBlockTag(BCLib.MOD_ID, "nether_ground"); - public static final Tag.Named END_GROUND = makeBlockTag(BCLib.MOD_ID, "end_ground"); + public static final Tag.Named BLOCK_BOOKSHELVES = makeCommonBlockTag("bookshelves"); + public static final Tag.Named BLOCK_GEN_TERRAIN = makeBlockTag(BCLib.MOD_ID, "gen_terrain"); + public static final Tag.Named BLOCK_NETHER_GROUND = makeBlockTag(BCLib.MOD_ID, "nether_ground"); + public static final Tag.Named BLOCK_END_GROUND = makeBlockTag(BCLib.MOD_ID, "end_ground"); public static final Tag.Named BLOCK_CHEST = makeCommonBlockTag("chest"); - public static final Tag.Named END_STONES = makeCommonBlockTag("end_stones"); - public static final Tag.Named NETHER_STONES = makeCommonBlockTag("nether_stones"); + public static final Tag.Named BLOCK_END_STONES = makeCommonBlockTag("end_stones"); + public static final Tag.Named BLOCK_NETHER_STONES = makeCommonBlockTag("nether_stones"); + public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbenches"); - public static final Tag.Named DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); + public static final Tag.Named BLOCK_DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); public static final Tag.Named MINEABLE_AXE = getMCBlockTag("mineable/axe"); public static final Tag.Named MINEABLE_PICKAXE = getMCBlockTag("mineable/pickaxe"); @@ -45,9 +46,10 @@ public class TagAPI { // Item Tags public static final Tag.Named ITEM_CHEST = makeCommonItemTag("chest"); - public static final Tag.Named IRON_INGOTS = makeCommonItemTag("iron_ingots"); - public static final Tag.Named FURNACES = makeCommonItemTag("furnaces"); - public final static Tag.Named HAMMERS = makeItemTag("fabric", "hammers"); + public static final Tag.Named ITEM_IRON_INGOTS = makeCommonItemTag("iron_ingots"); + public static final Tag.Named ITEM_FURNACES = makeCommonItemTag("furnaces"); + public static final Tag.Named ITEM_WORKBENCHES = makeCommonItemTag("workbenches"); + public final static Tag.Named ITEM_HAMMERS = makeCommonItemTag("hammers"); /** * Get or create {@link Tag.Named}. @@ -123,8 +125,8 @@ public class TagAPI { * @param block - {@link Block}. */ public static void addNetherGround(Block block) { - addTag(NETHER_GROUND, block); - addTag(GEN_TERRAIN, block); + addTag(BLOCK_NETHER_GROUND, block); + addTag(BLOCK_GEN_TERRAIN, block); } /** @@ -133,22 +135,22 @@ public class TagAPI { * @param block - {@link Block}. */ public static void addEndGround(Block block) { - addTag(GEN_TERRAIN, block); - addTag(END_GROUND, block); + addTag(BLOCK_GEN_TERRAIN, block); + addTag(BLOCK_END_GROUND, block); } /** * Initializes basic tags. Should be called only in BCLib main class. */ public static void init() { - addTag(BOOKSHELVES, Blocks.BOOKSHELF); - addTag(GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - addTag(NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - addTag(END_GROUND, Blocks.END_STONE); + addTag(BLOCK_BOOKSHELVES, Blocks.BOOKSHELF); + addTag(BLOCK_GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + addTag(BLOCK_NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + addTag(BLOCK_END_GROUND, Blocks.END_STONE); addTag(BLOCK_CHEST, Blocks.CHEST); addTag(ITEM_CHEST, Items.CHEST); - addTag(IRON_INGOTS, Items.IRON_INGOT); - addTag(FURNACES, Blocks.FURNACE); + addTag(ITEM_IRON_INGOTS, Items.IRON_INGOT); + addTag(ITEM_FURNACES, Blocks.FURNACE); } /** diff --git a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java index 53ed82db..c6d91a25 100644 --- a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java @@ -30,7 +30,7 @@ public abstract class EnchantingTableBlockMixin extends Block { if (random.nextInt(16) == 0) { for (int py = 0; py <= 1; ++py) { BlockPos blockPos = pos.offset(px, py, pz); - if (world.getBlockState(blockPos).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos).is(TagAPI.BLOCK_BOOKSHELVES)) { if (!world.isEmptyBlock(pos.offset(px / 2, 0, pz / 2))) { break; } diff --git a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java index 3c5c66cf..2f73d643 100644 --- a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java @@ -71,28 +71,28 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { 0, j )) && world.isEmptyBlock(blockPos.offset(k, 1, j))) { - if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } - if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } if (k != 0 && j != 0) { - if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } - if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } - if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } - if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { ++i; } } diff --git a/src/main/java/ru/bclib/recipes/CraftingRecipes.java b/src/main/java/ru/bclib/recipes/CraftingRecipes.java index 1d43873a..539305bf 100644 --- a/src/main/java/ru/bclib/recipes/CraftingRecipes.java +++ b/src/main/java/ru/bclib/recipes/CraftingRecipes.java @@ -12,23 +12,23 @@ public class CraftingRecipes { GridRecipe.make(BCLib.MOD_ID, "tag_smith_table", Blocks.SMITHING_TABLE) .setShape("II", "##", "##") .addMaterial('#', ItemTags.PLANKS) - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_cauldron", Blocks.CAULDRON) .setShape("I I", "I I", "III") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) .setShape("I I", "ICI", " I ") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('C', TagAPI.ITEM_CHEST) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_piston", Blocks.PISTON) .setShape("WWW", "CIC", "CDC") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('D', Items.REDSTONE) .addMaterial('C', Items.COBBLESTONE) .addMaterial('W', ItemTags.PLANKS) @@ -37,42 +37,42 @@ public class CraftingRecipes { GridRecipe.make(BCLib.MOD_ID, "tag_rail", Blocks.RAIL) .setOutputCount(16) .setShape("I I", "ISI", "I I") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('S', Items.STICK) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_stonecutter", Blocks.STONECUTTER) .setShape(" I ", "SSS") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('S', Items.STONE) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_bucket", Items.BUCKET) .setShape("I I", " I ") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_compass", Items.COMPASS) .setShape(" I ", "IDI", " I ") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('D', Items.REDSTONE) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART) .setShape("I I", "III") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD) .setShape("WIW", "WWW", " W ") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('W', ItemTags.PLANKS) .checkConfig(Configs.RECIPE_CONFIG) .build(); GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) .setShape("I I", "ICI", " I ") - .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) .addMaterial('C', TagAPI.ITEM_CHEST) .checkConfig(Configs.RECIPE_CONFIG) .build(); diff --git a/src/main/java/ru/bclib/util/StructureHelper.java b/src/main/java/ru/bclib/util/StructureHelper.java index 536a25ec..28494f48 100644 --- a/src/main/java/ru/bclib/util/StructureHelper.java +++ b/src/main/java/ru/bclib/util/StructureHelper.java @@ -286,7 +286,7 @@ public class StructureHelper { private static boolean isTerrainNear(WorldGenLevel world, BlockPos pos) { for (Direction dir : BlocksHelper.DIRECTIONS) { - if (world.getBlockState(pos.relative(dir)).is(TagAPI.GEN_TERRAIN)) { + if (world.getBlockState(pos.relative(dir)).is(TagAPI.BLOCK_GEN_TERRAIN)) { return true; } } @@ -365,7 +365,7 @@ public class StructureHelper { private static boolean ignore(BlockState state, WorldGenLevel world, BlockPos pos) { return state.getMaterial().isReplaceable() || !state.getFluidState() - .isEmpty() || state.is(TagAPI.END_GROUND) || state.is( + .isEmpty() || state.is(TagAPI.BLOCK_END_GROUND) || state.is( BlockTags.LOGS) || state.is(BlockTags.LEAVES) || state.getMaterial() .equals(Material.PLANT) || state.getMaterial() .equals(Material.LEAVES) || BlocksHelper @@ -382,7 +382,7 @@ public class StructureHelper { for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); - if (state.is(TagAPI.END_GROUND) && !world.getBlockState(mut.above()) + if (state.is(TagAPI.BLOCK_END_GROUND) && !world.getBlockState(mut.above()) .getMaterial() .isSolidBlocking()) { BlocksHelper.setWithoutUpdate(world, mut, top); diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index 1c3f9f0c..2cc3f41d 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -21,7 +21,7 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; import ru.bclib.api.TagAPI; public class BCLFeature { - private static final RuleTest ANY_TERRAIN = new TagMatchTest(TagAPI.GEN_TERRAIN); + private static final RuleTest ANY_TERRAIN = new TagMatchTest(TagAPI.BLOCK_GEN_TERRAIN); private ConfiguredFeature featureConfigured; private GenerationStep.Decoration featureStep; private Feature feature; diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index 5d5201c5..37aa0050 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -136,11 +136,11 @@ public abstract class NBTStructureFeature extends DefaultFeature { mut.setZ(z); mut.setY(surfMax); BlockState state = world.getBlockState(mut); - if (!state.is(TagAPI.GEN_TERRAIN) && state.isFaceSturdy(world, mut, Direction.DOWN)) { + if (!state.is(TagAPI.BLOCK_GEN_TERRAIN) && state.isFaceSturdy(world, mut, Direction.DOWN)) { for (int i = 0; i < 10; i++) { mut.setY(mut.getY() - 1); BlockState stateSt = world.getBlockState(mut); - if (!stateSt.is(TagAPI.GEN_TERRAIN)) { + if (!stateSt.is(TagAPI.BLOCK_GEN_TERRAIN)) { if (merge == TerrainMerge.SURFACE) { SurfaceBuilderConfiguration config = world.getBiome(mut) .getGenerationSettings() @@ -154,7 +154,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { } } else { - if (stateSt.is(TagAPI.END_GROUND) && state.getMaterial().isSolidBlocking()) { + if (stateSt.is(TagAPI.BLOCK_END_GROUND) && state.getMaterial().isSolidBlocking()) { if (merge == TerrainMerge.SURFACE) { SurfaceBuilderConfiguration config = world.getBiome(mut) .getGenerationSettings() From f981527200e1bb9cdf09fdec60b911b41d184e12 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 17:31:24 +0300 Subject: [PATCH 0081/1033] Feature randomization (fix MC bug) --- .../ru/bclib/mixin/common/BiomeMixin.java | 28 +++++++++++ .../ru/bclib/world/features/BCLFeature.java | 50 ++++++++++--------- src/main/resources/bclib.mixins.common.json | 3 +- 3 files changed, 56 insertions(+), 25 deletions(-) create mode 100644 src/main/java/ru/bclib/mixin/common/BiomeMixin.java diff --git a/src/main/java/ru/bclib/mixin/common/BiomeMixin.java b/src/main/java/ru/bclib/mixin/common/BiomeMixin.java new file mode 100644 index 00000000..cd8bebf8 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/BiomeMixin.java @@ -0,0 +1,28 @@ +package ru.bclib.mixin.common; + +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.WorldGenRegion; +import net.minecraft.world.level.StructureFeatureManager; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.WorldgenRandom; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Biome.class) +public class BiomeMixin { + private int bclib_featureIteratorSeed; + + @ModifyArg(method = "generate", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/WorldgenRandom;setFeatureSeed(JII)J")) + private long bclib_updateFeatureSeed(long seed) { + return Long.rotateRight(seed, bclib_featureIteratorSeed); + } + + @Inject(method = "generate", at = @At("HEAD")) + private void bclib_obBiomeGenerate(StructureFeatureManager structureFeatureManager, ChunkGenerator chunkGenerator, WorldGenRegion worldGenRegion, long l, WorldgenRandom worldgenRandom, BlockPos blockPos, CallbackInfo info) { + bclib_featureIteratorSeed = 0; + } +} diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index 2cc3f41d..b7b898d0 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -39,23 +39,25 @@ public class BCLFeature { } public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(BCLDecorators.HEIGHTMAP_SQUARE) - .countRandom(density); + ConfiguredFeature configured = feature + .configured(FeatureConfiguration.NONE) + .decorated(BCLDecorators.HEIGHTMAP_SQUARE) + .countRandom(density); return new BCLFeature(id, feature, GenerationStep.Decoration.VEGETAL_DECORATION, configured); } public static BCLFeature makeRawGenFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration( - chance))); + ConfiguredFeature configured = feature + .configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } + @Deprecated public static BCLFeature makeLakeFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration( - chance))); + ConfiguredFeature configured = feature + .configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.LAKES, configured); } @@ -66,13 +68,14 @@ public class BCLFeature { veinSize ); OreConfiguration config = new OreConfiguration(ANY_TERRAIN, blockOre.defaultBlockState(), 33); - ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig) - .rangeUniform( - VerticalAnchor.absolute(minY), - VerticalAnchor.absolute(maxY) - ) - .squared() - .count(veins); + ConfiguredFeature oreFeature = Feature.ORE + .configured(featureConfig) + .rangeUniform( + VerticalAnchor.absolute(minY), + VerticalAnchor.absolute(maxY) + ) + .squared() + .count(veins); return new BCLFeature( Feature.ORE, Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), @@ -81,23 +84,22 @@ public class BCLFeature { } public static BCLFeature makeChunkFeature(ResourceLocation id, Feature feature) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration( - 1))); + ConfiguredFeature configured = feature + .configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(1))); return new BCLFeature(id, feature, GenerationStep.Decoration.LOCAL_MODIFICATIONS, configured); } public static BCLFeature makeChansedFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration( - chance))); + ConfiguredFeature configured = feature + .configured(FeatureConfiguration.NONE) + .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.SURFACE_STRUCTURES, configured); } public static BCLFeature makeCountRawFeature(ResourceLocation id, Feature feature, int chance) { ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration( - chance))); + .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 01d3e36b..5ea05c8b 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -14,7 +14,8 @@ "ServerLevelMixin", "AnvilBlockMixin", "AnvilMenuMixin", - "TagLoaderMixin" + "TagLoaderMixin", + "BiomeMixin" ], "injectors": { "defaultRequire": 1 From 9878854f6b11d64c39e99e87c6b83fb8e83f829e Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 17:38:45 +0300 Subject: [PATCH 0082/1033] Small fix for fix --- src/main/java/ru/bclib/mixin/common/BiomeMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/mixin/common/BiomeMixin.java b/src/main/java/ru/bclib/mixin/common/BiomeMixin.java index cd8bebf8..26f16bcb 100644 --- a/src/main/java/ru/bclib/mixin/common/BiomeMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BiomeMixin.java @@ -18,7 +18,7 @@ public class BiomeMixin { @ModifyArg(method = "generate", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/WorldgenRandom;setFeatureSeed(JII)J")) private long bclib_updateFeatureSeed(long seed) { - return Long.rotateRight(seed, bclib_featureIteratorSeed); + return Long.rotateRight(seed, bclib_featureIteratorSeed++); } @Inject(method = "generate", at = @At("HEAD")) From a6419d96e28cf9ae9e056d138da30d0e8a104834 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Wed, 21 Jul 2021 18:40:46 +0300 Subject: [PATCH 0083/1033] Less fast fog density transition, render code in separate class --- .../render/CustomBackgroundRenderer.java | 111 ++++++++++++++++++ .../mixin/client/BackgroundRendererMixin.java | 82 +------------ 2 files changed, 113 insertions(+), 80 deletions(-) create mode 100644 src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java diff --git a/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java new file mode 100644 index 00000000..f8b75a5a --- /dev/null +++ b/src/main/java/ru/bclib/client/render/CustomBackgroundRenderer.java @@ -0,0 +1,111 @@ +package ru.bclib.client.render; + +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.FogRenderer; +import net.minecraft.core.BlockPos.MutableBlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.material.FogType; +import ru.bclib.api.BiomeAPI; +import ru.bclib.util.BackgroundInfo; +import ru.bclib.util.MHelper; +import ru.bclib.world.biomes.BCLBiome; + +public class CustomBackgroundRenderer { + private static final MutableBlockPos LAST_POS = new MutableBlockPos(0, -100, 0); + private static final MutableBlockPos MUT_POS = new MutableBlockPos(); + private static final float[] FOG_DENSITY = new float[8]; + private static final int GRID_SIZE = 32; + + public static boolean applyFogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog) { + Entity entity = camera.getEntity(); + FogType fogType = camera.getFluidInCamera(); + if (fogType != FogType.WATER) { + if (shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { + return false; + } + float fog = getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); + BackgroundInfo.fogDensity = fog; + float start = viewDistance * 0.75F / fog; + float end = viewDistance / fog; + + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + MobEffectInstance effect = livingEntity.getEffect(MobEffects.BLINDNESS); + if (effect != null) { + int duration = effect.getDuration(); + if (duration > 20) { + start = 0; + end *= 0.03F; + BackgroundInfo.blindness = 1; + } + else { + float delta = (float) duration / 20F; + BackgroundInfo.blindness = delta; + start = Mth.lerp(delta, start, 0); + end = Mth.lerp(delta, end, end * 0.03F); + } + } + else { + BackgroundInfo.blindness = 0; + } + } + + RenderSystem.setShaderFogStart(start); + RenderSystem.setShaderFogEnd(end); + return true; + } + return false; + } + + private static boolean shouldIgnore(Level level, int x, int y, int z) { + Biome biome = level.getBiome(MUT_POS.set(x, y, z)); + return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; + } + + private static float getFogDensityI(Level level, int x, int y, int z) { + Biome biome = level.getBiome(MUT_POS.set(x, y, z)); + BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); + return renderBiome.getFogDensity(); + } + + private static float getFogDensity(Level level, double x, double y, double z) { + int x1 = MHelper.floor(x / GRID_SIZE) * GRID_SIZE; + int y1 = MHelper.floor(y / GRID_SIZE) * GRID_SIZE; + int z1 = MHelper.floor(z / GRID_SIZE) * GRID_SIZE; + float dx = (float) (x - x1) / GRID_SIZE; + float dy = (float) (y - y1) / GRID_SIZE; + float dz = (float) (z - z1) / GRID_SIZE; + + if (LAST_POS.getX() != x1 || LAST_POS.getY() != y1 || LAST_POS.getZ() != z1) { + int x2 = x1 + GRID_SIZE; + int y2 = y1 + GRID_SIZE; + int z2 = z1 + GRID_SIZE; + LAST_POS.set(x1, y1, z1); + FOG_DENSITY[0] = getFogDensityI(level, x1, y1, z1); + FOG_DENSITY[1] = getFogDensityI(level, x2, y1, z1); + FOG_DENSITY[2] = getFogDensityI(level, x1, y2, z1); + FOG_DENSITY[3] = getFogDensityI(level, x2, y2, z1); + FOG_DENSITY[4] = getFogDensityI(level, x1, y1, z2); + FOG_DENSITY[5] = getFogDensityI(level, x2, y1, z2); + FOG_DENSITY[6] = getFogDensityI(level, x1, y2, z2); + FOG_DENSITY[7] = getFogDensityI(level, x2, y2, z2); + } + + float a = Mth.lerp(dx, FOG_DENSITY[0], FOG_DENSITY[1]); + float b = Mth.lerp(dx, FOG_DENSITY[2], FOG_DENSITY[3]); + float c = Mth.lerp(dx, FOG_DENSITY[4], FOG_DENSITY[5]); + float d = Mth.lerp(dx, FOG_DENSITY[6], FOG_DENSITY[7]); + + a = Mth.lerp(dy, a, b); + b = Mth.lerp(dy, c, d); + + return Mth.lerp(dz, a, b); + } +} diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index 2fc492bd..f8576f4d 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -19,6 +19,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.BiomeAPI; +import ru.bclib.client.render.CustomBackgroundRenderer; import ru.bclib.util.BackgroundInfo; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; @@ -60,87 +61,8 @@ public class BackgroundRendererMixin { @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) private static void bclib_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { - Entity entity = camera.getEntity(); - FogType fogType = camera.getFluidInCamera(); - if (fogType != FogType.WATER) { - if (bclib_shouldIgnore(entity.level, (int) entity.getX(), (int) entity.getEyeY(), (int) entity.getZ())) { - return; - } - float fog = bclib_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); - BackgroundInfo.fogDensity = fog; - float start = viewDistance * 0.75F / fog; - float end = viewDistance / fog; - - if (entity instanceof LivingEntity) { - LivingEntity le = (LivingEntity) entity; - MobEffectInstance effect = le.getEffect(MobEffects.BLINDNESS); - if (effect != null) { - int duration = effect.getDuration(); - if (duration > 20) { - start = 0; - end *= 0.03F; - BackgroundInfo.blindness = 1; - } - else { - float delta = (float) duration / 20F; - BackgroundInfo.blindness = delta; - start = Mth.lerp(delta, start, 0); - end = Mth.lerp(delta, end, end * 0.03F); - } - } - else { - BackgroundInfo.blindness = 0; - } - } - - RenderSystem.setShaderFogStart(start); - RenderSystem.setShaderFogEnd(end); + if (CustomBackgroundRenderer.applyFogDensity(camera, fogMode, viewDistance, thickFog)) { info.cancel(); } } - - private static boolean bclib_shouldIgnore(Level level, int x, int y, int z) { - Biome biome = level.getBiome(BCLIB_MUT_POS.set(x, y, z)); - return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; - } - - private static float bclib_getFogDensityI(Level level, int x, int y, int z) { - Biome biome = level.getBiome(BCLIB_MUT_POS.set(x, y, z)); - BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); - return renderBiome.getFogDensity(); - } - - private static float bclib_getFogDensity(Level level, double x, double y, double z) { - int x1 = (MHelper.floor(x) >> 3) << 3; - int y1 = (MHelper.floor(y) >> 3) << 3; - int z1 = (MHelper.floor(z) >> 3) << 3; - float dx = (float) (x - x1) / 8F; - float dy = (float) (y - y1) / 8F; - float dz = (float) (z - z1) / 8F; - - if (BCLIB_LAST_POS.getX() != x1 || BCLIB_LAST_POS.getY() != y1 || BCLIB_LAST_POS.getZ() != z1) { - int x2 = x1 + 8; - int y2 = y1 + 8; - int z2 = z1 + 8; - BCLIB_LAST_POS.set(x1, y1, z1); - BCLIB_FOG_DENSITY[0] = bclib_getFogDensityI(level, x1, y1, z1); - BCLIB_FOG_DENSITY[1] = bclib_getFogDensityI(level, x2, y1, z1); - BCLIB_FOG_DENSITY[2] = bclib_getFogDensityI(level, x1, y2, z1); - BCLIB_FOG_DENSITY[3] = bclib_getFogDensityI(level, x2, y2, z1); - BCLIB_FOG_DENSITY[4] = bclib_getFogDensityI(level, x1, y1, z2); - BCLIB_FOG_DENSITY[5] = bclib_getFogDensityI(level, x2, y1, z2); - BCLIB_FOG_DENSITY[6] = bclib_getFogDensityI(level, x1, y2, z2); - BCLIB_FOG_DENSITY[7] = bclib_getFogDensityI(level, x2, y2, z2); - } - - float a = Mth.lerp(dx, BCLIB_FOG_DENSITY[0], BCLIB_FOG_DENSITY[1]); - float b = Mth.lerp(dx, BCLIB_FOG_DENSITY[2], BCLIB_FOG_DENSITY[3]); - float c = Mth.lerp(dx, BCLIB_FOG_DENSITY[4], BCLIB_FOG_DENSITY[5]); - float d = Mth.lerp(dx, BCLIB_FOG_DENSITY[6], BCLIB_FOG_DENSITY[7]); - - a = Mth.lerp(dy, a, b); - b = Mth.lerp(dy, c, d); - - return Mth.lerp(dz, a, b); - } } From 37b85b4ceecf9bc0fa67911a589e60fc1eda6113 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 07:20:09 +0300 Subject: [PATCH 0084/1033] Base plant edit --- .../java/ru/bclib/blocks/BasePlantBlock.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index ae004374..23114bfb 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -1,10 +1,14 @@ package ru.bclib.blocks; import com.google.common.collect.Lists; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; +import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; @@ -26,10 +30,15 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.Nullable; +import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.ModelsHelper; +import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; import java.util.List; +import java.util.Optional; import java.util.Random; @SuppressWarnings("deprecation") @@ -134,4 +143,18 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderL ); world.addFreshEntity(item); } + + @Override + @Environment(EnvType.CLIENT) + public BlockModel getItemModel(ResourceLocation resourceLocation) { + return ModelsHelper.createBlockItem(resourceLocation); + } + + @Override + @Nullable + @Environment(EnvType.CLIENT) + public BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { + Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); + return ModelsHelper.fromPattern(pattern); + } } From d179bd2ba895afaaf8393f7567395d67240ec1e7 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 22 Jul 2021 08:52:46 +0200 Subject: [PATCH 0085/1033] Support fir BCLib as subproject to BN/BE --- bclib-composit.gradle | 8 ++ bclib.gradle | 169 ++++++++++++++++++++++++++++++++++++++++++ build.gradle | 164 +--------------------------------------- gradle.properties | 11 +-- 4 files changed, 185 insertions(+), 167 deletions(-) create mode 100644 bclib-composit.gradle create mode 100644 bclib.gradle diff --git a/bclib-composit.gradle b/bclib-composit.gradle new file mode 100644 index 00000000..3d9f10e6 --- /dev/null +++ b/bclib-composit.gradle @@ -0,0 +1,8 @@ +plugins { + id 'idea' + id 'eclipse' + id 'fabric-loom' + id 'maven-publish' +} + +apply from: "bclib.gradle" \ No newline at end of file diff --git a/bclib.gradle b/bclib.gradle new file mode 100644 index 00000000..0ba6ce46 --- /dev/null +++ b/bclib.gradle @@ -0,0 +1,169 @@ +buildscript { + dependencies { + classpath 'org.kohsuke:github-api:1.114' + } + + repositories { + gradlePluginPortal() + } +} +sourceCompatibility = JavaVersion.VERSION_16 +targetCompatibility = JavaVersion.VERSION_16 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group + +repositories { + maven { url "https://maven.dblsaiko.net/" } + maven { url "https://server.bbkr.space:8081/artifactory/libs-release/" } + maven { url "https://maven.fabricmc.net/" } + maven { url "https://maven.shedaniel.me/" } + maven { url 'https://maven.blamejared.com' } + maven { url 'https://jitpack.io' } +} + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings minecraft.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + //useApi "vazkii.patchouli:Patchouli:1.16.4-${project.patchouli_version}" +} + +def useOptional(String dep) { + dependencies.modRuntime (dep) { + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' + if (!dep.contains("me.shedaniel")) { + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' + } + } + dependencies.modCompileOnly (dep) { + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' + if (!dep.contains("me.shedaniel")) { + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' + } + } +} + +def useApi(String dep) { + dependencies.modApi (dep) { + exclude group: 'net.fabricmc.fabric-api' + exclude group: 'net.fabricmc' + if (!dep.contains("me.shedaniel")) { + exclude group: 'me.shedaniel.cloth' + exclude group: 'me.shedaniel' + } + } +} + +processResources { + println "Version: ${project.mod_version}" + inputs.property "version", project.mod_version + // duplicatesStrategy = 'WARN' + + // from(sourceSets.main.resources.srcDirs) { + // include "fabric.mod.json" + // expand "version": version + // } + + // from(sourceSets.main.resources.srcDirs) { + // exclude "fabric.mod.json" + // } + filesMatching("fabric.mod.json") { + expand "version": project.mod_version + } +} + +// ensure that the encoding is set to UTF-8, no matter what the system default is +// this fixes some edge cases with special characters not displaying correctly +// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" + it.options.release = 16 +} + +javadoc { + options.tags = [ "reason" ] + options.stylesheetFile = new File(projectDir, "javadoc.css"); +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task +// if it is present. +// If you remove this task, sources will not be generated. +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource +} + +jar { + from "LICENSE" +} + +artifacts { + archives sourcesJar + archives javadocJar +} + +def env = System.getenv() + +import org.kohsuke.github.GHReleaseBuilder +import org.kohsuke.github.GitHub + +task release(dependsOn: [remapJar, sourcesJar, javadocJar]) { + onlyIf { + env.GITHUB_TOKEN + } + + doLast { + def github = GitHub.connectUsingOAuth(env.GITHUB_TOKEN as String) + def repository = github.getRepository("paulevsGitch/BCLib") + + def releaseBuilder = new GHReleaseBuilder(repository, version as String) + releaseBuilder.name("${archivesBaseName}-${version}") + releaseBuilder.body("A changelog can be found at https://github.com/paulevsGitch/BCLib/commits") + releaseBuilder.commitish("main") + + def ghRelease = releaseBuilder.create() + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}.jar"), "application/java-archive"); + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-sources.jar"), "application/java-archive"); + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-javadoc.jar"), "application/java-archive"); + } +} + +// configure the maven publication +publishing { + publications { + gpr(MavenPublication) { + artifactId archivesBaseName + artifact(remapJar) { + builtBy remapJar + } + artifact(sourcesJar) { + builtBy remapSourcesJar + } + } + } + + // select the repositories you want to publish to + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/paulevsgitch/bclib") + credentials { + username = env.GITHUB_USER + password = env.GITHUB_TOKEN + } + } + } +} diff --git a/build.gradle b/build.gradle index ed0bc1c0..e1d0a7ff 100644 --- a/build.gradle +++ b/build.gradle @@ -1,168 +1,8 @@ -buildscript { - dependencies { - classpath 'org.kohsuke:github-api:1.114' - } -} - plugins { id 'idea' id 'eclipse' - id 'fabric-loom' version '0.8-SNAPSHOT' + id 'fabric-loom' version "${loom_version}" id 'maven-publish' } -sourceCompatibility = JavaVersion.VERSION_16 -targetCompatibility = JavaVersion.VERSION_16 - -archivesBaseName = project.archives_base_name -version = project.mod_version -group = project.maven_group - -repositories { - maven { url "https://maven.dblsaiko.net/" } - maven { url "https://server.bbkr.space:8081/artifactory/libs-release/" } - maven { url "https://maven.fabricmc.net/" } - maven { url 'https://maven.blamejared.com' } - maven { url "https://maven.shedaniel.me/" } - maven { url 'https://jitpack.io' } -} - -dependencies { - minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings minecraft.officialMojangMappings() - modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - - //useApi "vazkii.patchouli:Patchouli:1.16.4-${project.patchouli_version}" -} - -def useOptional(String dep) { - dependencies.modRuntime (dep) { - exclude group: 'net.fabricmc.fabric-api' - exclude group: 'net.fabricmc' - if (!dep.contains("me.shedaniel")) { - exclude group: 'me.shedaniel.cloth' - exclude group: 'me.shedaniel' - } - } - dependencies.modCompileOnly (dep) { - exclude group: 'net.fabricmc.fabric-api' - exclude group: 'net.fabricmc' - if (!dep.contains("me.shedaniel")) { - exclude group: 'me.shedaniel.cloth' - exclude group: 'me.shedaniel' - } - } -} - -def useApi(String dep) { - dependencies.modApi (dep) { - exclude group: 'net.fabricmc.fabric-api' - exclude group: 'net.fabricmc' - if (!dep.contains("me.shedaniel")) { - exclude group: 'me.shedaniel.cloth' - exclude group: 'me.shedaniel' - } - } -} - -processResources { - inputs.property "version", project.version - duplicatesStrategy = 'WARN' - - from(sourceSets.main.resources.srcDirs) { - include "fabric.mod.json" - expand "version": project.version - } - - from(sourceSets.main.resources.srcDirs) { - exclude "fabric.mod.json" - } -} - -// ensure that the encoding is set to UTF-8, no matter what the system default is -// this fixes some edge cases with special characters not displaying correctly -// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html -tasks.withType(JavaCompile) { - options.encoding = "UTF-8" -} - -javadoc { - options.tags = [ "reason" ] - options.stylesheetFile = new File(projectDir, "javadoc.css"); -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task -// if it is present. -// If you remove this task, sources will not be generated. -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -jar { - from "LICENSE" -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -def env = System.getenv() - -import org.kohsuke.github.GHReleaseBuilder -import org.kohsuke.github.GitHub - -task release(dependsOn: [remapJar, sourcesJar, javadocJar]) { - onlyIf { - env.GITHUB_TOKEN - } - - doLast { - def github = GitHub.connectUsingOAuth(env.GITHUB_TOKEN as String) - def repository = github.getRepository("paulevsGitch/BCLib") - - def releaseBuilder = new GHReleaseBuilder(repository, version as String) - releaseBuilder.name("${archivesBaseName}-${version}") - releaseBuilder.body("A changelog can be found at https://github.com/paulevsGitch/BCLib/commits") - releaseBuilder.commitish("main") - - def ghRelease = releaseBuilder.create() - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}.jar"), "application/java-archive"); - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-sources.jar"), "application/java-archive"); - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-javadoc.jar"), "application/java-archive"); - } -} - -// configure the maven publication -publishing { - publications { - gpr(MavenPublication) { - artifactId archivesBaseName - artifact(remapJar) { - builtBy remapJar - } - artifact(sourcesJar) { - builtBy remapSourcesJar - } - } - } - - // select the repositories you want to publish to - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/paulevsgitch/bclib") - credentials { - username = env.GITHUB_USER - password = env.GITHUB_TOKEN - } - } - } -} +apply from: "bclib.gradle" \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 058f9b87..67528fc4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,11 +1,14 @@ # Done to increase the memory available to gradle. org.gradle.jvmargs=-Xmx2G +#Loom +loom_version=0.8-SNAPSHOT + # Fabric Properties -# check these on https://fabricmc.net/use +# check these on https://fabricmc.net/versions.html minecraft_version= 1.17.1 -yarn_mappings= 6 loader_version= 0.11.6 +fabric_version = 0.36.1+1.17 # Mod Properties mod_version = 0.3.0 @@ -13,6 +16,4 @@ maven_group = ru.bclib archives_base_name = bclib # Dependencies -# currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api -patchouli_version = 50-FABRIC -fabric_version = 0.36.1+1.17 +patchouli_version = 50-FABRIC \ No newline at end of file From c64c6eca7b3f890855718de7ccc64a8ab7c9c63c Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 11:47:48 +0200 Subject: [PATCH 0086/1033] Fixing Entity Inventory --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 117 ++++++++++-------- 1 file changed, 65 insertions(+), 52 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 74eae701..0d8a8ccb 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -35,63 +35,75 @@ public class DataFixerAPI { LOGGER.info("Everything up to date"); return; } + + boolean[] allOk = {true}; List regions = getAllRegions(dir, null); - boolean[] allOk = {true}; - regions.parallelStream() - .forEach((file) -> { - try { - LOGGER.info("Inspecting " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), true); - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos)) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - // if ((root.toString().contains("betternether") || root.toString().contains("bclib")) && root.toString().contains("chest")) { - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - // } - input.close(); - - ListTag tileEntities = root.getCompound("Level") - .getList("TileEntities", 10); - fixItemArrayWithID(tileEntities, changed, data, true); - - ListTag sections = root.getCompound("Level") - .getList("Sections", 10); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", 10); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - changed[0] = data.replaceStringFromIDs(blockTagCompound, "Name"); - }); - }); - if (changed[0]) { - LOGGER.warning("Writing '{}': {}/{}", file, x, z); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } - catch (Exception e) { - allOk[0] = false; - e.printStackTrace(); - } - }); + regions.parallelStream().forEach((file) -> fixRegion(data, allOk, file)); if (allOk[0]) { data.markApplied(); WorldDataAPI.saveFile(BCLib.MOD_ID); } } - + + private static void fixRegion(MigrationProfile data, boolean[] allOk, File file) { + try { + LOGGER.info("Inspecting " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { + for (int z = 0; z < 32; z++) { + ChunkPos pos = new ChunkPos(x, z); + changed[0] = false; + if (region.hasChunk(pos)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + if ((root.toString().contains("betternether:chest") || root.toString().contains("bclib:chest"))) { + NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + } + input.close(); + + //Checking TileEntities + ListTag tileEntities = root.getCompound("Level") + .getList("TileEntities", 10); + fixItemArrayWithID(tileEntities, changed, data, true); + + //Checking Entities + ListTag entities = root.getList("Entities", 10); + fixItemArrayWithID(entities, changed, data, true); + + + //Checking Block Palette + ListTag sections = root.getCompound("Level") + .getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + changed[0] |= data.replaceStringFromIDs(blockTagCompound, "Name"); + }); + }); + + if (changed[0]) { + LOGGER.warning("Writing '{}': {}/{}", file, x, z); + NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + "-changed.nbt")); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + + } + } + } + } + region.close(); + } + catch (Exception e) { + allOk[0] = false; + e.printStackTrace(); + } + } + static CompoundTag patchConfTag = null; static CompoundTag getPatchData(){ if (patchConfTag==null) { @@ -109,6 +121,9 @@ public class DataFixerAPI { if (recursive && tag.contains("Items")) { changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); } + if (recursive && tag.contains("Inventory")) { + changed[0] |= fixItemArrayWithID(tag.getList("Inventory", 10), changed, data, true); + } }); return changed[0]; @@ -121,9 +136,7 @@ public class DataFixerAPI { for (File file : dir.listFiles()) { if (file.isDirectory()) { getAllRegions(file, list); - } - else if (file.isFile() && file.getName() - .endsWith(".mca")) { + } else if (file.isFile() && file.getName().endsWith(".mca")) { list.add(file); } } From 9e42fe72944a294a6708117137641fb5970d457e Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 13:17:10 +0200 Subject: [PATCH 0087/1033] Handle Player and Level data in Fixer --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 128 +++++++++++++++--- 1 file changed, 109 insertions(+), 19 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 0d8a8ccb..ff7add7d 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -40,12 +40,69 @@ public class DataFixerAPI { List regions = getAllRegions(dir, null); regions.parallelStream().forEach((file) -> fixRegion(data, allOk, file)); + + List players = getAllPlayers(dir); + players.parallelStream().forEach((file) -> fixPlayer(data, allOk, file)); + + fixLevel(data, allOk, new File(dir, "level.dat")); if (allOk[0]) { data.markApplied(); WorldDataAPI.saveFile(BCLib.MOD_ID); } } + private static void fixLevel(MigrationProfile data, boolean[] allOk, File file) { + try { + LOGGER.info("Inspecting " + file); + CompoundTag level = NbtIo.readCompressed(file); + boolean[] changed = { false }; + + if (level.contains("Data")) { + CompoundTag dataTag = (CompoundTag)level.get("Data"); + if (dataTag.contains("Player")) { + CompoundTag player = (CompoundTag)dataTag.get("Player"); + fixPlayerNbt(player, changed, data); + } + } + + if (changed[0]) { + LOGGER.warning("Writing '{}'", file); + NbtIo.writeCompressed(level, file); + } + } + catch (Exception e) { + allOk[0] = false; + e.printStackTrace(); + } + } + + private static void fixPlayer(MigrationProfile data, boolean[] allOk, File file) { + try { + LOGGER.info("Inspecting " + file); + CompoundTag player = NbtIo.readCompressed(file); + boolean[] changed = { false }; + fixPlayerNbt(player, changed, data); + + if (changed[0]) { + LOGGER.warning("Writing '{}'", file); + NbtIo.writeCompressed(player, file); + } + } + catch (Exception e) { + allOk[0] = false; + e.printStackTrace(); + } + } + + private static void fixPlayerNbt(CompoundTag player, boolean[] changed, MigrationProfile data) { + //Checking Inventory + ListTag inventory = player.getList("Inventory", 10); + fixInventory(inventory, changed, data, true); + + //Checking EnderChest + ListTag enderitems = player.getList("EnderItems", 10); + fixInventory(enderitems, changed, data, true); + } private static void fixRegion(MigrationProfile data, boolean[] allOk, File file) { try { @@ -59,9 +116,9 @@ public class DataFixerAPI { if (region.hasChunk(pos)) { DataInputStream input = region.getChunkDataInputStream(pos); CompoundTag root = NbtIo.read(input); - if ((root.toString().contains("betternether:chest") || root.toString().contains("bclib:chest"))) { - NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - } + // if ((root.toString().contains("betternether:chest") || root.toString().contains("bclib:chest"))) { + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); + // } input.close(); //Checking TileEntities @@ -73,7 +130,6 @@ public class DataFixerAPI { ListTag entities = root.getList("Entities", 10); fixItemArrayWithID(entities, changed, data, true); - //Checking Block Palette ListTag sections = root.getCompound("Level") .getList("Sections", 10); @@ -87,7 +143,7 @@ public class DataFixerAPI { if (changed[0]) { LOGGER.warning("Writing '{}': {}/{}", file, x, z); - NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + "-changed.nbt")); + // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + "-changed.nbt")); DataOutputStream output = region.getChunkDataOutputStream(pos); NbtIo.write(root, output); output.close(); @@ -111,22 +167,56 @@ public class DataFixerAPI { } return patchConfTag; } - - private static boolean fixItemArrayWithID(ListTag items, boolean[] changed, MigrationProfile data, boolean recursive) { - items.forEach(inTag -> { - final CompoundTag tag = (CompoundTag) inTag; - - changed[0] |= data.replaceStringFromIDs(tag, "id"); - - if (recursive && tag.contains("Items")) { - changed[0] |= fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); - } - if (recursive && tag.contains("Inventory")) { - changed[0] |= fixItemArrayWithID(tag.getList("Inventory", 10), changed, data, true); + + private static void fixInventory(ListTag inventory, boolean[] changed, MigrationProfile data, boolean recursive) { + inventory.forEach(item -> { + changed[0] |= data.replaceStringFromIDs((CompoundTag)item, "id"); + + if (((CompoundTag) item).contains("tag")) { + CompoundTag tag = (CompoundTag)((CompoundTag) item).get("tag"); + if (tag.contains("BlockEntityTag")){ + CompoundTag blockEntityTag = (CompoundTag)((CompoundTag) tag).get("BlockEntityTag"); + ListTag items = blockEntityTag.getList("Items", 10); + fixItemArrayWithID(items, changed, data, recursive); + } } }); - - return changed[0]; + } + + private static void fixItemArrayWithID(ListTag items, boolean[] changed, MigrationProfile data, boolean recursive) { + items.forEach(inTag -> { + fixID((CompoundTag) inTag, changed, data, recursive); + }); + } + + + private static void fixID(CompoundTag inTag, boolean[] changed, MigrationProfile data, boolean recursive) { + final CompoundTag tag = inTag; + + changed[0] |= data.replaceStringFromIDs(tag, "id"); + if (tag.contains("Item")) { + CompoundTag item = (CompoundTag)tag.get("Item"); + fixID(item, changed, data, recursive); + } + + if (recursive && tag.contains("Items")) { + fixItemArrayWithID(tag.getList("Items", 10), changed, data, true); + } + if (recursive && tag.contains("Inventory")) { + ListTag inventory = tag.getList("Inventory", 10); + fixInventory(inventory, changed, data, recursive); + } + } + + private static List getAllPlayers(File dir) { + List list = new ArrayList<>(); + dir = new File(dir, "playerdata"); + for (File file : dir.listFiles()) { + if (file.isFile() && file.getName().endsWith(".dat")) { + list.add(file); + } + } + return list; } private static List getAllRegions(File dir, List list) { From 89d548caf94b0a35fc41a3f1dac6c1a4dd1e36db Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 13:17:36 +0200 Subject: [PATCH 0088/1033] Start fixer before the world is loaded (otherwise no changes to level.dat are possible) --- .../bclib/mixin/common/ServerLevelMixin.java | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 58aec99b..dc76f988 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -32,8 +32,19 @@ public abstract class ServerLevelMixin extends Level { protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(writableLevelData, resourceKey, dimensionType, supplier, bl, bl2, l); } - - @Inject(method = "*", at = @At("TAIL")) + @Inject(method = "*", at = @At("HEAD")) + private void bclib_onServerWorldInitStart(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { + ServerLevel world = ServerLevel.class.cast(this); + File dir = session.getDimensionPath(world.dimension()); + if (!new File(dir, "level.dat").exists()) { + dir = dir.getParentFile(); + } + + WorldDataAPI.load(new File(dir, "data")); + DataFixerAPI.fixData(dir); + } + + @Inject(method = "*", at = @At("TAIL")) private void bclib_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { BiomeAPI.initRegistry(server); @@ -42,14 +53,5 @@ public abstract class ServerLevelMixin extends Level { } bclib_lastWorld = session.getLevelId(); - - ServerLevel world = ServerLevel.class.cast(this); - File dir = session.getDimensionPath(world.dimension()); - if (!new File(dir, "level.dat").exists()) { - dir = dir.getParentFile(); - } - - WorldDataAPI.load(new File(dir, "data")); - DataFixerAPI.fixData(dir); } } From 5a56064e8630de2b7cc8cb157c255e51bf1642f1 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 15:20:49 +0200 Subject: [PATCH 0089/1033] Moved DataFixer call --- .../mixin/common/MinecraftServerMixin.java | 17 ++++++++++++++++- .../ru/bclib/mixin/common/ServerLevelMixin.java | 14 ++------------ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index d5876718..9cd8378b 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -5,18 +5,25 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerResources; import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.progress.ChunkProgressListener; import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.WorldData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; +import ru.bclib.api.WorldDataAPI; +import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.recipes.BCLRecipeManager; +import java.io.File; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -33,7 +40,15 @@ public class MinecraftServerMixin { @Final @Shadow protected WorldData worldData; - + + @Inject(method="convertFromRegionFormatIfNeeded", at = @At("HEAD")) + private static void bclib_applyPatches(LevelStorageSource.LevelStorageAccess session, CallbackInfo ci){ + File levelPath = session.getLevelPath(LevelResource.ROOT).toFile(); + WorldDataAPI.load(new File(levelPath, "data")); + DataFixerAPI.fixData(levelPath); + } + + @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) private void bclib_reloadResources(Collection collection, CallbackInfoReturnable> info) { bclib_injectRecipes(); diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index dc76f988..285fda1e 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -15,6 +15,7 @@ import net.minecraft.world.level.storage.WritableLevelData; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.BiomeAPI; import ru.bclib.api.WorldDataAPI; @@ -32,19 +33,8 @@ public abstract class ServerLevelMixin extends Level { protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(writableLevelData, resourceKey, dimensionType, supplier, bl, bl2, l); } - @Inject(method = "*", at = @At("HEAD")) - private void bclib_onServerWorldInitStart(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { - ServerLevel world = ServerLevel.class.cast(this); - File dir = session.getDimensionPath(world.dimension()); - if (!new File(dir, "level.dat").exists()) { - dir = dir.getParentFile(); - } - WorldDataAPI.load(new File(dir, "data")); - DataFixerAPI.fixData(dir); - } - - @Inject(method = "*", at = @At("TAIL")) + @Inject(method = "*", at = @At("TAIL")) private void bclib_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { BiomeAPI.initRegistry(server); From 4e9fda44f84358e303495b4e065c551917ffd784 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 23:16:58 +0300 Subject: [PATCH 0090/1033] Ladder block vanilla class extend --- .../java/ru/bclib/blocks/BaseLadderBlock.java | 124 ++---------------- 1 file changed, 12 insertions(+), 112 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index a5a5fa5b..d43d8fdf 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -5,27 +5,12 @@ import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.HorizontalDirectionalBlock; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.LadderBlock; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.DirectionProperty; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; +import net.minecraft.world.level.storage.loot.LootContext; import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; @@ -33,108 +18,17 @@ import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.RenderLayerProvider; -import ru.bclib.util.BlocksHelper; +import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Optional; -@SuppressWarnings("deprecation") -public class BaseLadderBlock extends BaseBlockNotFull implements RenderLayerProvider, BlockModelProvider { - public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; - public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; - protected static final VoxelShape EAST_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); - protected static final VoxelShape WEST_SHAPE = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); - protected static final VoxelShape SOUTH_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); - protected static final VoxelShape NORTH_SHAPE = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); - +public class BaseLadderBlock extends LadderBlock implements RenderLayerProvider, BlockModelProvider { public BaseLadderBlock(Block block) { super(FabricBlockSettings.copyOf(block).noOcclusion()); } - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(FACING); - stateManager.add(WATERLOGGED); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return switch (state.getValue(FACING)) { - case SOUTH -> SOUTH_SHAPE; - case WEST -> WEST_SHAPE; - case EAST -> EAST_SHAPE; - default -> NORTH_SHAPE; - }; - } - - private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) { - BlockState blockState = world.getBlockState(pos); - return !blockState.isSignalSource() && blockState.isFaceSturdy(world, pos, side); - } - - @Override - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - Direction direction = state.getValue(FACING); - return canPlaceOn(world, pos.relative(direction.getOpposite()), direction); - } - - @Override - public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { - if (facing.getOpposite() == state.getValue(FACING) && !state.canSurvive(world, pos)) { - return Blocks.AIR.defaultBlockState(); - } - else { - if (state.getValue(WATERLOGGED)) { - world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); - } - - return super.updateShape(state, facing, neighborState, world, pos, neighborPos); - } - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - BlockState blockState; - if (!ctx.replacingClickedOnBlock()) { - blockState = ctx.getLevel().getBlockState(ctx.getClickedPos().relative(ctx.getClickedFace().getOpposite())); - if (blockState.getBlock() == this && blockState.getValue(FACING) == ctx.getClickedFace()) { - return null; - } - } - - blockState = defaultBlockState(); - LevelReader worldView = ctx.getLevel(); - BlockPos blockPos = ctx.getClickedPos(); - FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); - Direction[] directions = ctx.getNearestLookingDirections(); - - for (Direction direction : directions) { - if (direction.getAxis().isHorizontal()) { - blockState = blockState.setValue(FACING, direction.getOpposite()); - if (blockState.canSurvive(worldView, blockPos)) { - return blockState.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); - } - } - } - - return null; - } - - @Override - public BlockState rotate(BlockState state, Rotation rotation) { - return BlocksHelper.rotateHorizontal(state, rotation, FACING); - } - - @Override - public BlockState mirror(BlockState state, Mirror mirror) { - return BlocksHelper.mirrorHorizontal(state, mirror, FACING); - } - - @Override - public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); - } - @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; @@ -160,4 +54,10 @@ public class BaseLadderBlock extends BaseBlockNotFull implements RenderLayerProv registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true); } + + @Override + @SuppressWarnings("deprecation") + public List getDrops(BlockState state, LootContext.Builder builder) { + return Collections.singletonList(new ItemStack(this)); + } } From 50ccbace6de9084dbc612753a2071222de1348f0 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 23:23:14 +0300 Subject: [PATCH 0091/1033] Post init API --- src/main/java/ru/bclib/api/PostInitAPI.java | 29 +++++++++++++++++++ .../java/ru/bclib/client/BCLibClient.java | 7 ++--- .../java/ru/bclib/server/BCLibServer.java | 7 ++--- 3 files changed, 33 insertions(+), 10 deletions(-) create mode 100644 src/main/java/ru/bclib/api/PostInitAPI.java diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java new file mode 100644 index 00000000..7a0afd95 --- /dev/null +++ b/src/main/java/ru/bclib/api/PostInitAPI.java @@ -0,0 +1,29 @@ +package ru.bclib.api; + +import com.google.common.collect.Lists; +import net.minecraft.core.Registry; +import ru.bclib.interfaces.PostInitable; + +import java.util.List; +import java.util.function.Consumer; + +public class PostInitAPI { + private static List> postInitFunctions = Lists.newArrayList(); + + public static void register(Consumer function) { + postInitFunctions.add(function); + } + + public static void postInit() { + if (postInitFunctions == null) { + return; + } + postInitFunctions.forEach(function -> function.accept(null)); + Registry.BLOCK.forEach(block -> { + if (block instanceof PostInitable) { + ((PostInitable) block).postInit(); + } + }); + postInitFunctions = null; + } +} diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 7b85b66c..4c9e3698 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -5,6 +5,7 @@ import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; +import ru.bclib.api.PostInitAPI; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.PostInitable; import ru.bclib.interfaces.RenderLayerProvider; @@ -16,11 +17,7 @@ public class BCLibClient implements ClientModInitializer { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); registerRenderLayers(); - Registry.BLOCK.forEach(block -> { - if (block instanceof PostInitable) { - ((PostInitable) block).postInit(); - } - }); + PostInitAPI.postInit(); } private void registerRenderLayers() { diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index 35520c02..402e6a2a 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -3,16 +3,13 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; +import ru.bclib.api.PostInitAPI; import ru.bclib.interfaces.PostInitable; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); - Registry.BLOCK.forEach(block -> { - if (block instanceof PostInitable) { - ((PostInitable) block).postInit(); - } - }); + PostInitAPI.postInit(); } } From 551bf6865c0bf76fd1aee853f86d43e23024afde Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 23:38:32 +0300 Subject: [PATCH 0092/1033] Post init API enhancement, automatic render registry (WIP) --- src/main/java/ru/bclib/api/PostInitAPI.java | 39 +++++++++++++++++-- .../java/ru/bclib/client/BCLibClient.java | 15 +------ .../interfaces/TileEntityRenderProvider.java | 5 +++ .../java/ru/bclib/server/BCLibServer.java | 2 +- 4 files changed, 43 insertions(+), 18 deletions(-) create mode 100644 src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java index 7a0afd95..8cc068e0 100644 --- a/src/main/java/ru/bclib/api/PostInitAPI.java +++ b/src/main/java/ru/bclib/api/PostInitAPI.java @@ -1,8 +1,19 @@ package ru.bclib.api; import com.google.common.collect.Lists; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; +import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; +import net.minecraft.world.level.block.Block; +import ru.bclib.blocks.BaseChestBlock; +import ru.bclib.blocks.BaseSignBlock; +import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.client.render.BaseChestBlockEntityRenderer; +import ru.bclib.client.render.BaseSignBlockEntityRenderer; import ru.bclib.interfaces.PostInitable; +import ru.bclib.interfaces.RenderLayerProvider; import java.util.List; import java.util.function.Consumer; @@ -14,16 +25,38 @@ public class PostInitAPI { postInitFunctions.add(function); } - public static void postInit() { + public static void postInit(boolean isClient) { if (postInitFunctions == null) { return; } postInitFunctions.forEach(function -> function.accept(null)); Registry.BLOCK.forEach(block -> { - if (block instanceof PostInitable) { - ((PostInitable) block).postInit(); + processBlockCommon(block); + if (isClient) { + processBlockClient(block); } }); postInitFunctions = null; } + + @Environment(EnvType.CLIENT) + private static void processBlockClient(Block block) { + if (block instanceof RenderLayerProvider) { + BCLRenderLayer layer = ((RenderLayerProvider) block).getRenderLayer(); + if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, RenderType.cutout()); + else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, RenderType.translucent()); + } + if (block instanceof BaseChestBlock) { + BaseChestBlockEntityRenderer.registerRenderLayer(block); + } + else if (block instanceof BaseSignBlock) { + BaseSignBlockEntityRenderer.registerRenderLayer(block); + } + } + + private static void processBlockCommon(Block block) { + if (block instanceof PostInitable) { + ((PostInitable) block).postInit(); + } + } } diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 4c9e3698..8935ce7e 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -16,19 +16,6 @@ public class BCLibClient implements ClientModInitializer { public void onInitializeClient() { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); - registerRenderLayers(); - PostInitAPI.postInit(); - } - - private void registerRenderLayers() { - RenderType cutout = RenderType.cutout(); - RenderType translucent = RenderType.translucent(); - Registry.BLOCK.forEach(block -> { - if (block instanceof RenderLayerProvider) { - BCLRenderLayer layer = ((RenderLayerProvider) block).getRenderLayer(); - if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); - else if (layer == BCLRenderLayer.TRANSLUCENT) BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); - } - }); + PostInitAPI.postInit(true); } } diff --git a/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java b/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java new file mode 100644 index 00000000..5d59f113 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java @@ -0,0 +1,5 @@ +package ru.bclib.interfaces; + +public interface TileEntityRenderProvider { + +} diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index 402e6a2a..0cd2b803 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -10,6 +10,6 @@ public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); - PostInitAPI.postInit(); + PostInitAPI.postInit(false); } } From ceeb36fc2a785131196fbcf97634313fd51fb340 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 23:55:28 +0300 Subject: [PATCH 0093/1033] Translation Helper fixes --- .../java/ru/bclib/util/TranslationHelper.java | 99 ++++++++++--------- 1 file changed, 50 insertions(+), 49 deletions(-) diff --git a/src/main/java/ru/bclib/util/TranslationHelper.java b/src/main/java/ru/bclib/util/TranslationHelper.java index 3540a39a..bb661fa5 100644 --- a/src/main/java/ru/bclib/util/TranslationHelper.java +++ b/src/main/java/ru/bclib/util/TranslationHelper.java @@ -1,6 +1,6 @@ package ru.bclib.util; -import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.JsonObject; import net.minecraft.core.Registry; @@ -9,28 +9,34 @@ import net.minecraft.resources.ResourceLocation; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.Collections; -import java.util.List; +import java.util.Set; public class TranslationHelper { - public static void printMissingNames(String modID) { - List missingNamesEn = Lists.newArrayList(); - List missingNamesRu = Lists.newArrayList(); + /** + * Print English translation file lines. Translation is "auto-beautified" text (example "strange_thing" -> "Strange Thing"). + * @param modID {@link String} mod ID string. + */ + public static void printMissingEnNames(String modID) { + printMissingNames(modID, "en_us"); + } + + /** + * Prints translation file lines for specified language. + * @param modID {@link String} mod ID string; + * @param languageCode {@link String} language code (example "en_us", "ru_ru"). + */ + public static void printMissingNames(String modID, String languageCode) { + Set missingNames = Sets.newHashSet(); Gson gson = new Gson(); - InputStream streamEn = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/en_us.json"); - InputStream streamRu = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/ru_ru.json"); - JsonObject translationEn = gson.fromJson(new InputStreamReader(streamEn), JsonObject.class); - JsonObject translationRu = gson.fromJson(new InputStreamReader(streamRu), JsonObject.class); + InputStream inputStream = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/" + languageCode + ".json"); + JsonObject translation = gson.fromJson(new InputStreamReader(inputStream), JsonObject.class); Registry.BLOCK.forEach(block -> { if (Registry.BLOCK.getKey(block).getNamespace().equals(modID)) { String name = block.getName().getString(); - if (!translationEn.has(name)) { - missingNamesEn.add(name); - } - if (!translationRu.has(name)) { - missingNamesRu.add(name); + if (!translation.has(name)) { + missingNames.add(name); } } }); @@ -38,11 +44,8 @@ public class TranslationHelper { Registry.ITEM.forEach(item -> { if (Registry.ITEM.getKey(item).getNamespace().equals(modID)) { String name = item.getDescription().getString(); - if (!translationEn.has(name)) { - missingNamesEn.add(name); - } - if (!translationRu.has(name)) { - missingNamesRu.add(name); + if (!translation.has(name)) { + missingNames.add(name); } } }); @@ -51,11 +54,8 @@ public class TranslationHelper { ResourceLocation id = BuiltinRegistries.BIOME.getKey(biome); if (id.getNamespace().equals(modID)) { String name = "biome." + modID + "." + id.getPath(); - if (!translationEn.has(name)) { - missingNamesEn.add(name); - } - if (!translationRu.has(name)) { - missingNamesRu.add(name); + if (!translation.has(name)) { + missingNames.add(name); } } }); @@ -64,44 +64,45 @@ public class TranslationHelper { ResourceLocation id = Registry.ENTITY_TYPE.getKey(entity); if (id.getNamespace().equals(modID)) { String name = "entity." + modID + "." + id.getPath(); - if (!translationEn.has(name)) { - missingNamesEn.add(name); - } - if (!translationRu.has(name)) { - missingNamesRu.add(name); + if (!translation.has(name)) { + missingNames.add(name); } } }); - if (!missingNamesEn.isEmpty() || !missingNamesRu.isEmpty()) { + if (!missingNames.isEmpty()) { System.out.println("========================================"); System.out.println(" MISSING NAMES LIST"); - if (!missingNamesEn.isEmpty()) { - Collections.sort(missingNamesEn); - System.out.println("========================================"); - System.out.println(" ENGLISH"); - System.out.println("========================================"); - missingNamesEn.forEach((name) -> { - System.out.println(" \"" + name + "\": \"" + fastTranslateEn(name) + "\","); - }); - } - - if (!missingNamesRu.isEmpty()) { - Collections.sort(missingNamesRu); - System.out.println("========================================"); - System.out.println(" RUSSIAN"); - System.out.println("========================================"); - missingNamesRu.forEach((name) -> { - System.out.println(" \"" + name + "\": \"\","); - }); + if (!missingNames.isEmpty()) { + if (languageCode.equals("en_us")) { + System.out.println("========================================"); + System.out.println(" AUTO ENGLISH BEAUTIFICATION"); + System.out.println("========================================"); + missingNames.stream().sorted().forEach(name -> { + System.out.println(" \"" + name + "\": \"" + fastTranslateEn(name) + "\","); + }); + } + else { + System.out.println("========================================"); + System.out.println(" TEMPLATE: [" + languageCode + "]"); + System.out.println("========================================"); + missingNames.stream().sorted().forEach(name -> { + System.out.println(" \"" + name + "\": \"\","); + }); + } } System.out.println("========================================"); } } + /** + * Simple fast text beautification (example "strange_thing" -> "Strange Thing"). + * @param text {@link String} to process; + * @return {@link String} result. + */ public static String fastTranslateEn(String text) { String[] words = text.substring(text.lastIndexOf('.') + 1).split("_"); StringBuilder builder = new StringBuilder(); From 7be63c814df782f2c23c86834207b3adbbf48d94 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Thu, 22 Jul 2021 23:57:32 +0300 Subject: [PATCH 0094/1033] Small formatting fixes --- src/main/java/ru/bclib/util/TranslationHelper.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/util/TranslationHelper.java b/src/main/java/ru/bclib/util/TranslationHelper.java index bb661fa5..bb1b5735 100644 --- a/src/main/java/ru/bclib/util/TranslationHelper.java +++ b/src/main/java/ru/bclib/util/TranslationHelper.java @@ -78,7 +78,7 @@ public class TranslationHelper { if (!missingNames.isEmpty()) { if (languageCode.equals("en_us")) { System.out.println("========================================"); - System.out.println(" AUTO ENGLISH BEAUTIFICATION"); + System.out.println(" AUTO ENGLISH BEAUTIFICATION"); System.out.println("========================================"); missingNames.stream().sorted().forEach(name -> { System.out.println(" \"" + name + "\": \"" + fastTranslateEn(name) + "\","); @@ -86,7 +86,7 @@ public class TranslationHelper { } else { System.out.println("========================================"); - System.out.println(" TEMPLATE: [" + languageCode + "]"); + System.out.println(" TEMPLATE: [" + languageCode + "]"); System.out.println("========================================"); missingNames.stream().sorted().forEach(name -> { System.out.println(" \"" + name + "\": \"\","); From 080bd36714113fc6d00721703ea7fa6b656849c9 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 23:05:37 +0200 Subject: [PATCH 0095/1033] Added first draft of WoodenMaterial (from BetterEnd) --- .../bclib/blocks/complex/WoodenMaterial.java | 246 ++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java diff --git a/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java b/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java new file mode 100644 index 00000000..9ea1528c --- /dev/null +++ b/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java @@ -0,0 +1,246 @@ +package ru.bclib.blocks.complex; + +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.MaterialColor; +import org.jetbrains.annotations.NotNull; +import ru.bclib.api.TagAPI; +import ru.bclib.blocks.BaseBarkBlock; +import ru.bclib.blocks.BaseBarrelBlock; +import ru.bclib.blocks.BaseBlock; +import ru.bclib.blocks.BaseBookshelfBlock; +import ru.bclib.blocks.BaseChestBlock; +import ru.bclib.blocks.BaseComposterBlock; +import ru.bclib.blocks.BaseCraftingTableBlock; +import ru.bclib.blocks.BaseDoorBlock; +import ru.bclib.blocks.BaseFenceBlock; +import ru.bclib.blocks.BaseGateBlock; +import ru.bclib.blocks.BaseLadderBlock; +import ru.bclib.blocks.BaseRotatedPillarBlock; +import ru.bclib.blocks.BaseSignBlock; +import ru.bclib.blocks.BaseSlabBlock; +import ru.bclib.blocks.BaseStairsBlock; +import ru.bclib.blocks.BaseStripableLogBlock; +import ru.bclib.blocks.BaseTrapdoorBlock; +import ru.bclib.blocks.BaseWoodenButtonBlock; +import ru.bclib.blocks.StripableBarkBlock; +import ru.bclib.blocks.WoodenPressurePlateBlock; +import ru.bclib.config.Configs; +import ru.bclib.recipes.GridRecipe; + +import java.util.function.BiFunction; + +public class WoodenMaterial { + public final static String NAME_STRIPPED_LOG = "stripped_log"; + public final static String NAME_STRIPPED_BARK = "stripped_bark"; + public final static String NAME_LOG = "log"; + public final static String NAME_BARK = "bark"; + public final static String NAME_PLANKS = "planks"; + public final static String NAME_STAIRS = "stairs"; + public final static String NAME_SLAB = "slab"; + public final static String NAME_FENCE = "fence"; + public final static String NAME_GATE = "gate"; + public final static String NAME_BUTTON = "button"; + public final static String NAME_PLATE = "plate"; + public final static String NAME_TRAPDOOR = "trapdoor"; + public final static String NAME_DOOR = "door"; + public final static String NAME_CRAFTING_TABLE = "crafting_table"; + public final static String NAME_LADDER = "ladder"; + public final static String NAME_SIGN = "sign"; + public final static String NAME_CHEST = "chest"; + public final static String NAME_BARREL = "barrel"; + public final static String NAME_BOOKSHELF = "bookshelf"; + public final static String NAME_COMPOSTER = "composter"; + + public final static String NAME_PRESSURE_PLATE = "pressure_plate"; + public final static String NAME_SHULKER = "shulker"; + + public final Block log; + public final Block bark; + + public final Block log_stripped; + public final Block bark_stripped; + + public final Block planks; + + public final Block stairs; + public final Block slab; + public final Block fence; + public final Block gate; + public final Block button; + public final Block pressurePlate; + public final Block trapdoor; + public final Block door; + + public final Block craftingTable; + public final Block ladder; + public final Block sign; + + public final Block chest; + public final Block barrel; + //public final Block shelf; + //public final Block composter; + + protected final FabricBlockSettings materialPlanks; + protected final String modID; + protected final String name; + protected final String receipGroupPrefix; + + public final Tag.Named logBlockTag; + public final Tag.Named logItemTag; + + protected Block newLogStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseRotatedPillarBlock(materialPlanks); } + protected Block newBarkStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarkBlock(materialPlanks); } + protected Block newLog(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (log_stripped!=null) return new BaseStripableLogBlock(woodColor, log_stripped); else return null;} + protected Block newBark(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (bark_stripped!=null) return new StripableBarkBlock(woodColor, bark_stripped); else return null;} + protected Block newPlanks(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBlock(materialPlanks); } + protected Block newStairs(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseStairsBlock(planks); } + protected Block newSlab(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSlabBlock(planks); } + protected Block newFence(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseFenceBlock(planks); } + protected Block newGate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseGateBlock(planks); } + protected Block newButton(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseWoodenButtonBlock(planks); } + protected Block newPressurePlate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new WoodenPressurePlateBlock(planks); } + protected Block newTrapdoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseTrapdoorBlock(planks); } + protected Block newDoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseDoorBlock(planks); } + protected Block newCraftingTable(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseCraftingTableBlock(planks); } + protected Block newLadder(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseLadderBlock(planks); } + protected Block newSign(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSignBlock(planks); } + protected Block newChest(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseChestBlock(planks); } + protected Block newBarrel(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarrelBlock(planks); } + //protected Block newShelf(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBookshelfBlock(planks); } + //protected Block newComposter(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseComposterBlock(planks); } + + public WoodenMaterial(String modID, String name, MaterialColor woodColor, MaterialColor planksColor, String receipGroupPrefix, BiFunction registerBlock) { + materialPlanks = FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).mapColor(planksColor); + this.modID = modID; + this.receipGroupPrefix = receipGroupPrefix; + this.name = name; + + log_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_LOG, newLogStripped(materialPlanks, woodColor)); + bark_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_BARK, newBarkStripped(materialPlanks, woodColor)); + + log = registerBlock.apply(name + "_" + NAME_LOG, newLog(materialPlanks, woodColor)); + bark = registerBlock.apply(name + "_" + NAME_BARK, newBark(materialPlanks, woodColor)); + + planks = registerBlock.apply(name + "_" + NAME_PLANKS, newPlanks(materialPlanks, woodColor)); + stairs = registerBlock.apply(name + "_" + NAME_STAIRS, newStairs(materialPlanks, woodColor)); + slab = registerBlock.apply(name + "_" + NAME_SLAB, newSlab(materialPlanks, woodColor)); + fence = registerBlock.apply(name + "_" + NAME_FENCE, newFence(materialPlanks, woodColor)); + gate = registerBlock.apply(name + "_" + NAME_GATE, newGate(materialPlanks, woodColor)); + button = registerBlock.apply(name + "_" + NAME_BUTTON, newButton(materialPlanks, woodColor)); + pressurePlate = registerBlock.apply(name + "_" + NAME_PLATE, newPressurePlate(materialPlanks, woodColor)); + trapdoor = registerBlock.apply(name + "_" + NAME_TRAPDOOR, newTrapdoor(materialPlanks, woodColor)); + door = registerBlock.apply(name + "_" + NAME_DOOR, newDoor(materialPlanks, woodColor)); + + craftingTable = registerBlock.apply(name + "_" + NAME_CRAFTING_TABLE, newCraftingTable(materialPlanks, woodColor)); + ladder = registerBlock.apply(name + "_" + NAME_LADDER, newLadder(materialPlanks, woodColor)); + sign = registerBlock.apply(name + "_" + NAME_SIGN, newSign(materialPlanks, woodColor)); + + chest = registerBlock.apply(name + "_" + NAME_CHEST, newChest(materialPlanks, woodColor)); + barrel = registerBlock.apply(name + "_" + NAME_BARREL, newBarrel(materialPlanks, woodColor)); + //shelf = registerBlock.apply(name + "_" + NAME_BOOKSHELF, newShelf(materialPlanks, woodColor)); + //composter = registerBlock.apply(name + "_" + NAME_COMPOSTER, newComposter(materialPlanks, woodColor)); + + // Recipes // + GridRecipe.make(modID, name + "_" + NAME_PLANKS, planks).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setList("#").addMaterial('#', log, bark, log_stripped, bark_stripped).setGroup(receipGroupPrefix + "_planks").build(); + GridRecipe.make(modID, name + "_" + NAME_STAIRS, stairs).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setShape("# ", "## ", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_stairs").build(); + GridRecipe.make(modID, name + "_" + NAME_SLAB, slab).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(6).setShape("###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_slabs").build(); + GridRecipe.make(modID, name + "_" + NAME_FENCE, fence).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("#I#", "#I#").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_fences").build(); + GridRecipe.make(modID, name + "_" + NAME_GATE, gate).checkConfig(Configs.RECIPE_CONFIG).setShape("I#I", "I#I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_gates").build(); + GridRecipe.make(modID, name + "_" + NAME_BUTTON, button).checkConfig(Configs.RECIPE_CONFIG).setList("#").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_buttons").build(); + GridRecipe.make(modID, name + "_" + NAME_PRESSURE_PLATE, pressurePlate).checkConfig(Configs.RECIPE_CONFIG).setShape("##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_plates").build(); + GridRecipe.make(modID, name + "_" + NAME_TRAPDOOR, trapdoor).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(2).setShape("###", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_trapdoors").build(); + GridRecipe.make(modID, name + "_" + NAME_DOOR, door).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("##", "##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_doors").build(); + GridRecipe.make(modID, name + "_" + NAME_CRAFTING_TABLE, craftingTable).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_tables").build(); + GridRecipe.make(modID, name + "_" + NAME_LADDER, ladder).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("I I", "I#I", "I I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_ladders").build(); + GridRecipe.make(modID, name + "_" + NAME_SIGN, sign).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("###", "###", " I ").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_signs").build(); + GridRecipe.make(modID, name + "_" + NAME_CHEST, chest).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "# #", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_chests").build(); + GridRecipe.make(modID, name + "_" + NAME_BARREL, barrel).checkConfig(Configs.RECIPE_CONFIG).setShape("#S#", "# #", "#S#").addMaterial('#', planks).addMaterial('S', slab).setGroup(receipGroupPrefix + "_barrels").build(); + //GridRecipe.make(modID, name + "_" + NAME_BOOKSHELF, shelf).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "PPP", "###").addMaterial('#', planks).addMaterial('P', Items.BOOK).setGroup(receipGroupPrefix + "_bookshelves").build(); + GridRecipe.make(modID, name + "_" + NAME_BARK, bark).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', log).setOutputCount(3).build(); + GridRecipe.make(modID, name + "_" + NAME_LOG, log).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', bark).setOutputCount(3).build(); + //GridRecipe.make(modID, name + "_" + NAME_COMPOSTER, composter).checkConfig(Configs.RECIPE_CONFIG).setShape("# #", "# #", "###").addMaterial('#', slab).build(); + GridRecipe.make(modID, name + "_" + NAME_SHULKER, Items.SHULKER_BOX).checkConfig(Configs.RECIPE_CONFIG).setShape("S", "#", "S").addMaterial('S', Items.SHULKER_SHELL).addMaterial('#', chest).build(); + + // Item Tags // + TagAPI.addTag(ItemTags.PLANKS, planks); + TagAPI.addTag(ItemTags.WOODEN_PRESSURE_PLATES, pressurePlate); + TagAPI.addTag(ItemTags.LOGS, log, bark, log_stripped, bark_stripped); + TagAPI.addTag(ItemTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); + + + TagAPI.addTags(button, ItemTags.WOODEN_BUTTONS, ItemTags.BUTTONS); + TagAPI.addTags(door, ItemTags.WOODEN_DOORS, ItemTags.DOORS); + TagAPI.addTags(fence, ItemTags.WOODEN_FENCES, ItemTags.FENCES); + TagAPI.addTags(slab, ItemTags.WOODEN_SLABS, ItemTags.SLABS); + TagAPI.addTags(stairs, ItemTags.WOODEN_STAIRS, ItemTags.STAIRS); + TagAPI.addTags(trapdoor, ItemTags.WOODEN_TRAPDOORS, ItemTags.TRAPDOORS); + TagAPI.addTag(TagAPI.ITEM_CHEST, chest); + + // Block Tags // + TagAPI.addTag(BlockTags.PLANKS, planks); + TagAPI.addTag(BlockTags.CLIMBABLE, ladder); + TagAPI.addTag(BlockTags.LOGS, log, bark, log_stripped, bark_stripped); + TagAPI.addTag(BlockTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); + + + TagAPI.addTags(button, BlockTags.WOODEN_BUTTONS, BlockTags.BUTTONS); + TagAPI.addTags(door, BlockTags.WOODEN_DOORS, BlockTags.DOORS); + TagAPI.addTags(fence, BlockTags.WOODEN_FENCES, BlockTags.FENCES); + TagAPI.addTags(slab, BlockTags.WOODEN_SLABS, BlockTags.SLABS); + TagAPI.addTags(stairs, BlockTags.WOODEN_STAIRS, BlockTags.STAIRS); + TagAPI.addTags(trapdoor, BlockTags.WOODEN_TRAPDOORS, BlockTags.TRAPDOORS); + //TagAPI.addTag(TagAPI.BLOCK_BOOKSHELVES, shelf); + TagAPI.addTag(TagAPI.BLOCK_CHEST, chest); + + logBlockTag = TagAPI.makeBlockTag(modID, name + "_logs"); + logItemTag = TagAPI.makeItemTag(modID, name + "_logs"); + TagAPI.addTag(logBlockTag, log_stripped, bark_stripped, log, bark); + TagAPI.addTag(logItemTag, log_stripped, bark_stripped, log, bark); + + addFlammable(); + } + + protected void addFlammable() { + FlammableBlockRegistry.getDefaultInstance().add(log, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(bark, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(log_stripped, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(bark_stripped, 5, 5); + + FlammableBlockRegistry.getDefaultInstance().add(planks, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(stairs, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(slab, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(fence, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(gate, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(button, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(pressurePlate, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(trapdoor, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(door, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(craftingTable, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(ladder, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(sign, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(chest, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(barrel, 5, 20); + //FlammableBlockRegistry.getDefaultInstance().add(shelf, 5, 20); + //FlammableBlockRegistry.getDefaultInstance().add(composter, 5, 20); + } + + public boolean isTreeLog(Block block) { + return block!=null && (block == log || block == bark); + } + + public boolean isTreeLog(BlockState state) { + return isTreeLog(state.getBlock()); + } +} \ No newline at end of file From 6385480e9e4cade0940acff9eccc70955cb6eb2f Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 22 Jul 2021 23:05:37 +0200 Subject: [PATCH 0096/1033] Added first draft of WoodenMaterial (from BetterEnd) --- .../bclib/blocks/complex/WoodenMaterial.java | 246 ++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java diff --git a/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java b/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java new file mode 100644 index 00000000..9ea1528c --- /dev/null +++ b/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java @@ -0,0 +1,246 @@ +package ru.bclib.blocks.complex; + +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.MaterialColor; +import org.jetbrains.annotations.NotNull; +import ru.bclib.api.TagAPI; +import ru.bclib.blocks.BaseBarkBlock; +import ru.bclib.blocks.BaseBarrelBlock; +import ru.bclib.blocks.BaseBlock; +import ru.bclib.blocks.BaseBookshelfBlock; +import ru.bclib.blocks.BaseChestBlock; +import ru.bclib.blocks.BaseComposterBlock; +import ru.bclib.blocks.BaseCraftingTableBlock; +import ru.bclib.blocks.BaseDoorBlock; +import ru.bclib.blocks.BaseFenceBlock; +import ru.bclib.blocks.BaseGateBlock; +import ru.bclib.blocks.BaseLadderBlock; +import ru.bclib.blocks.BaseRotatedPillarBlock; +import ru.bclib.blocks.BaseSignBlock; +import ru.bclib.blocks.BaseSlabBlock; +import ru.bclib.blocks.BaseStairsBlock; +import ru.bclib.blocks.BaseStripableLogBlock; +import ru.bclib.blocks.BaseTrapdoorBlock; +import ru.bclib.blocks.BaseWoodenButtonBlock; +import ru.bclib.blocks.StripableBarkBlock; +import ru.bclib.blocks.WoodenPressurePlateBlock; +import ru.bclib.config.Configs; +import ru.bclib.recipes.GridRecipe; + +import java.util.function.BiFunction; + +public class WoodenMaterial { + public final static String NAME_STRIPPED_LOG = "stripped_log"; + public final static String NAME_STRIPPED_BARK = "stripped_bark"; + public final static String NAME_LOG = "log"; + public final static String NAME_BARK = "bark"; + public final static String NAME_PLANKS = "planks"; + public final static String NAME_STAIRS = "stairs"; + public final static String NAME_SLAB = "slab"; + public final static String NAME_FENCE = "fence"; + public final static String NAME_GATE = "gate"; + public final static String NAME_BUTTON = "button"; + public final static String NAME_PLATE = "plate"; + public final static String NAME_TRAPDOOR = "trapdoor"; + public final static String NAME_DOOR = "door"; + public final static String NAME_CRAFTING_TABLE = "crafting_table"; + public final static String NAME_LADDER = "ladder"; + public final static String NAME_SIGN = "sign"; + public final static String NAME_CHEST = "chest"; + public final static String NAME_BARREL = "barrel"; + public final static String NAME_BOOKSHELF = "bookshelf"; + public final static String NAME_COMPOSTER = "composter"; + + public final static String NAME_PRESSURE_PLATE = "pressure_plate"; + public final static String NAME_SHULKER = "shulker"; + + public final Block log; + public final Block bark; + + public final Block log_stripped; + public final Block bark_stripped; + + public final Block planks; + + public final Block stairs; + public final Block slab; + public final Block fence; + public final Block gate; + public final Block button; + public final Block pressurePlate; + public final Block trapdoor; + public final Block door; + + public final Block craftingTable; + public final Block ladder; + public final Block sign; + + public final Block chest; + public final Block barrel; + //public final Block shelf; + //public final Block composter; + + protected final FabricBlockSettings materialPlanks; + protected final String modID; + protected final String name; + protected final String receipGroupPrefix; + + public final Tag.Named logBlockTag; + public final Tag.Named logItemTag; + + protected Block newLogStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseRotatedPillarBlock(materialPlanks); } + protected Block newBarkStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarkBlock(materialPlanks); } + protected Block newLog(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (log_stripped!=null) return new BaseStripableLogBlock(woodColor, log_stripped); else return null;} + protected Block newBark(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (bark_stripped!=null) return new StripableBarkBlock(woodColor, bark_stripped); else return null;} + protected Block newPlanks(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBlock(materialPlanks); } + protected Block newStairs(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseStairsBlock(planks); } + protected Block newSlab(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSlabBlock(planks); } + protected Block newFence(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseFenceBlock(planks); } + protected Block newGate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseGateBlock(planks); } + protected Block newButton(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseWoodenButtonBlock(planks); } + protected Block newPressurePlate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new WoodenPressurePlateBlock(planks); } + protected Block newTrapdoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseTrapdoorBlock(planks); } + protected Block newDoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseDoorBlock(planks); } + protected Block newCraftingTable(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseCraftingTableBlock(planks); } + protected Block newLadder(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseLadderBlock(planks); } + protected Block newSign(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSignBlock(planks); } + protected Block newChest(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseChestBlock(planks); } + protected Block newBarrel(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarrelBlock(planks); } + //protected Block newShelf(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBookshelfBlock(planks); } + //protected Block newComposter(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseComposterBlock(planks); } + + public WoodenMaterial(String modID, String name, MaterialColor woodColor, MaterialColor planksColor, String receipGroupPrefix, BiFunction registerBlock) { + materialPlanks = FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).mapColor(planksColor); + this.modID = modID; + this.receipGroupPrefix = receipGroupPrefix; + this.name = name; + + log_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_LOG, newLogStripped(materialPlanks, woodColor)); + bark_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_BARK, newBarkStripped(materialPlanks, woodColor)); + + log = registerBlock.apply(name + "_" + NAME_LOG, newLog(materialPlanks, woodColor)); + bark = registerBlock.apply(name + "_" + NAME_BARK, newBark(materialPlanks, woodColor)); + + planks = registerBlock.apply(name + "_" + NAME_PLANKS, newPlanks(materialPlanks, woodColor)); + stairs = registerBlock.apply(name + "_" + NAME_STAIRS, newStairs(materialPlanks, woodColor)); + slab = registerBlock.apply(name + "_" + NAME_SLAB, newSlab(materialPlanks, woodColor)); + fence = registerBlock.apply(name + "_" + NAME_FENCE, newFence(materialPlanks, woodColor)); + gate = registerBlock.apply(name + "_" + NAME_GATE, newGate(materialPlanks, woodColor)); + button = registerBlock.apply(name + "_" + NAME_BUTTON, newButton(materialPlanks, woodColor)); + pressurePlate = registerBlock.apply(name + "_" + NAME_PLATE, newPressurePlate(materialPlanks, woodColor)); + trapdoor = registerBlock.apply(name + "_" + NAME_TRAPDOOR, newTrapdoor(materialPlanks, woodColor)); + door = registerBlock.apply(name + "_" + NAME_DOOR, newDoor(materialPlanks, woodColor)); + + craftingTable = registerBlock.apply(name + "_" + NAME_CRAFTING_TABLE, newCraftingTable(materialPlanks, woodColor)); + ladder = registerBlock.apply(name + "_" + NAME_LADDER, newLadder(materialPlanks, woodColor)); + sign = registerBlock.apply(name + "_" + NAME_SIGN, newSign(materialPlanks, woodColor)); + + chest = registerBlock.apply(name + "_" + NAME_CHEST, newChest(materialPlanks, woodColor)); + barrel = registerBlock.apply(name + "_" + NAME_BARREL, newBarrel(materialPlanks, woodColor)); + //shelf = registerBlock.apply(name + "_" + NAME_BOOKSHELF, newShelf(materialPlanks, woodColor)); + //composter = registerBlock.apply(name + "_" + NAME_COMPOSTER, newComposter(materialPlanks, woodColor)); + + // Recipes // + GridRecipe.make(modID, name + "_" + NAME_PLANKS, planks).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setList("#").addMaterial('#', log, bark, log_stripped, bark_stripped).setGroup(receipGroupPrefix + "_planks").build(); + GridRecipe.make(modID, name + "_" + NAME_STAIRS, stairs).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setShape("# ", "## ", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_stairs").build(); + GridRecipe.make(modID, name + "_" + NAME_SLAB, slab).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(6).setShape("###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_slabs").build(); + GridRecipe.make(modID, name + "_" + NAME_FENCE, fence).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("#I#", "#I#").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_fences").build(); + GridRecipe.make(modID, name + "_" + NAME_GATE, gate).checkConfig(Configs.RECIPE_CONFIG).setShape("I#I", "I#I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_gates").build(); + GridRecipe.make(modID, name + "_" + NAME_BUTTON, button).checkConfig(Configs.RECIPE_CONFIG).setList("#").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_buttons").build(); + GridRecipe.make(modID, name + "_" + NAME_PRESSURE_PLATE, pressurePlate).checkConfig(Configs.RECIPE_CONFIG).setShape("##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_plates").build(); + GridRecipe.make(modID, name + "_" + NAME_TRAPDOOR, trapdoor).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(2).setShape("###", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_trapdoors").build(); + GridRecipe.make(modID, name + "_" + NAME_DOOR, door).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("##", "##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_doors").build(); + GridRecipe.make(modID, name + "_" + NAME_CRAFTING_TABLE, craftingTable).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_tables").build(); + GridRecipe.make(modID, name + "_" + NAME_LADDER, ladder).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("I I", "I#I", "I I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_ladders").build(); + GridRecipe.make(modID, name + "_" + NAME_SIGN, sign).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("###", "###", " I ").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_signs").build(); + GridRecipe.make(modID, name + "_" + NAME_CHEST, chest).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "# #", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_chests").build(); + GridRecipe.make(modID, name + "_" + NAME_BARREL, barrel).checkConfig(Configs.RECIPE_CONFIG).setShape("#S#", "# #", "#S#").addMaterial('#', planks).addMaterial('S', slab).setGroup(receipGroupPrefix + "_barrels").build(); + //GridRecipe.make(modID, name + "_" + NAME_BOOKSHELF, shelf).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "PPP", "###").addMaterial('#', planks).addMaterial('P', Items.BOOK).setGroup(receipGroupPrefix + "_bookshelves").build(); + GridRecipe.make(modID, name + "_" + NAME_BARK, bark).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', log).setOutputCount(3).build(); + GridRecipe.make(modID, name + "_" + NAME_LOG, log).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', bark).setOutputCount(3).build(); + //GridRecipe.make(modID, name + "_" + NAME_COMPOSTER, composter).checkConfig(Configs.RECIPE_CONFIG).setShape("# #", "# #", "###").addMaterial('#', slab).build(); + GridRecipe.make(modID, name + "_" + NAME_SHULKER, Items.SHULKER_BOX).checkConfig(Configs.RECIPE_CONFIG).setShape("S", "#", "S").addMaterial('S', Items.SHULKER_SHELL).addMaterial('#', chest).build(); + + // Item Tags // + TagAPI.addTag(ItemTags.PLANKS, planks); + TagAPI.addTag(ItemTags.WOODEN_PRESSURE_PLATES, pressurePlate); + TagAPI.addTag(ItemTags.LOGS, log, bark, log_stripped, bark_stripped); + TagAPI.addTag(ItemTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); + + + TagAPI.addTags(button, ItemTags.WOODEN_BUTTONS, ItemTags.BUTTONS); + TagAPI.addTags(door, ItemTags.WOODEN_DOORS, ItemTags.DOORS); + TagAPI.addTags(fence, ItemTags.WOODEN_FENCES, ItemTags.FENCES); + TagAPI.addTags(slab, ItemTags.WOODEN_SLABS, ItemTags.SLABS); + TagAPI.addTags(stairs, ItemTags.WOODEN_STAIRS, ItemTags.STAIRS); + TagAPI.addTags(trapdoor, ItemTags.WOODEN_TRAPDOORS, ItemTags.TRAPDOORS); + TagAPI.addTag(TagAPI.ITEM_CHEST, chest); + + // Block Tags // + TagAPI.addTag(BlockTags.PLANKS, planks); + TagAPI.addTag(BlockTags.CLIMBABLE, ladder); + TagAPI.addTag(BlockTags.LOGS, log, bark, log_stripped, bark_stripped); + TagAPI.addTag(BlockTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); + + + TagAPI.addTags(button, BlockTags.WOODEN_BUTTONS, BlockTags.BUTTONS); + TagAPI.addTags(door, BlockTags.WOODEN_DOORS, BlockTags.DOORS); + TagAPI.addTags(fence, BlockTags.WOODEN_FENCES, BlockTags.FENCES); + TagAPI.addTags(slab, BlockTags.WOODEN_SLABS, BlockTags.SLABS); + TagAPI.addTags(stairs, BlockTags.WOODEN_STAIRS, BlockTags.STAIRS); + TagAPI.addTags(trapdoor, BlockTags.WOODEN_TRAPDOORS, BlockTags.TRAPDOORS); + //TagAPI.addTag(TagAPI.BLOCK_BOOKSHELVES, shelf); + TagAPI.addTag(TagAPI.BLOCK_CHEST, chest); + + logBlockTag = TagAPI.makeBlockTag(modID, name + "_logs"); + logItemTag = TagAPI.makeItemTag(modID, name + "_logs"); + TagAPI.addTag(logBlockTag, log_stripped, bark_stripped, log, bark); + TagAPI.addTag(logItemTag, log_stripped, bark_stripped, log, bark); + + addFlammable(); + } + + protected void addFlammable() { + FlammableBlockRegistry.getDefaultInstance().add(log, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(bark, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(log_stripped, 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(bark_stripped, 5, 5); + + FlammableBlockRegistry.getDefaultInstance().add(planks, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(stairs, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(slab, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(fence, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(gate, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(button, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(pressurePlate, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(trapdoor, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(door, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(craftingTable, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(ladder, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(sign, 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(chest, 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(barrel, 5, 20); + //FlammableBlockRegistry.getDefaultInstance().add(shelf, 5, 20); + //FlammableBlockRegistry.getDefaultInstance().add(composter, 5, 20); + } + + public boolean isTreeLog(Block block) { + return block!=null && (block == log || block == bark); + } + + public boolean isTreeLog(BlockState state) { + return isTreeLog(state.getBlock()); + } +} \ No newline at end of file From 8dbce734d5748505172cdbb2aa782c1dac77c431 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 00:07:47 +0300 Subject: [PATCH 0097/1033] Small format fixes, javadocs --- src/main/java/ru/bclib/api/PostInitAPI.java | 14 +++++++--- .../render/BaseChestBlockEntityRenderer.java | 11 +++----- .../render/BaseSignBlockEntityRenderer.java | 26 +++++++------------ 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java index 8cc068e0..fe9de248 100644 --- a/src/main/java/ru/bclib/api/PostInitAPI.java +++ b/src/main/java/ru/bclib/api/PostInitAPI.java @@ -19,17 +19,25 @@ import java.util.List; import java.util.function.Consumer; public class PostInitAPI { - private static List> postInitFunctions = Lists.newArrayList(); + private static List> postInitFunctions = Lists.newArrayList(); - public static void register(Consumer function) { + /** + * Register a new function which will be called after all mods are initiated. Will be called on both client and server. + * @param function {@link Consumer} with {@code boolean} parameter ({@code true} for client, {@code false} for server). + */ + public static void register(Consumer function) { postInitFunctions.add(function); } + /** + * Called in proper BCLib entry points, for internal usage only. + * @param isClient {@code boolean}, {@code true} for client, {@code false} for server. + */ public static void postInit(boolean isClient) { if (postInitFunctions == null) { return; } - postInitFunctions.forEach(function -> function.accept(null)); + postInitFunctions.forEach(function -> function.accept(isClient)); Registry.BLOCK.forEach(block -> { processBlockCommon(block); if (isClient) { diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 2ac5e080..42e2f689 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -35,7 +35,7 @@ import java.util.HashMap; @Environment(EnvType.CLIENT) public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { private static final HashMap LAYERS = Maps.newHashMap(); - private static final RenderType[] defaultLayer; + private static final RenderType[] RENDER_TYPES; private static final int ID_NORMAL = 0; private static final int ID_LEFT = 1; @@ -147,7 +147,7 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { - private static final HashMap LAYERS = Maps.newHashMap(); - private static final RenderType defaultLayer; - private final Font font; - private final SignRenderer.SignModel model; - - + private static final HashMap RENDER_TYPES = Maps.newHashMap(); private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16); + private static final RenderType RENDER_TYPE; + private final SignRenderer.SignModel model; + private final Font font; + public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { super(); this.font = ctx.getFont(); - - //set up a default model model = new SignRenderer.SignModel(ctx.bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); } @@ -76,9 +73,7 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer Date: Fri, 23 Jul 2021 13:40:37 +0300 Subject: [PATCH 0098/1033] Complex materials, wood material (WIP) --- .../bclib/blocks/complex/WoodenMaterial.java | 246 ------------------ .../complexmaterials/ComplexMaterial.java | 169 ++++++++++++ .../complexmaterials/WoodenMaterial.java | 149 +++++++++++ .../complexmaterials/entry/BlockEntry.java | 58 +++++ .../entry/ComplexMaterialEntry.java | 19 ++ .../complexmaterials/entry/ItemEntry.java | 37 +++ .../ru/bclib/registry/BlocksRegistry.java | 7 +- 7 files changed, 435 insertions(+), 250 deletions(-) delete mode 100644 src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java create mode 100644 src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java create mode 100644 src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java create mode 100644 src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java create mode 100644 src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java create mode 100644 src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java diff --git a/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java b/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java deleted file mode 100644 index 9ea1528c..00000000 --- a/src/main/java/ru/bclib/blocks/complex/WoodenMaterial.java +++ /dev/null @@ -1,246 +0,0 @@ -package ru.bclib.blocks.complex; - -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.Tag; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import org.jetbrains.annotations.NotNull; -import ru.bclib.api.TagAPI; -import ru.bclib.blocks.BaseBarkBlock; -import ru.bclib.blocks.BaseBarrelBlock; -import ru.bclib.blocks.BaseBlock; -import ru.bclib.blocks.BaseBookshelfBlock; -import ru.bclib.blocks.BaseChestBlock; -import ru.bclib.blocks.BaseComposterBlock; -import ru.bclib.blocks.BaseCraftingTableBlock; -import ru.bclib.blocks.BaseDoorBlock; -import ru.bclib.blocks.BaseFenceBlock; -import ru.bclib.blocks.BaseGateBlock; -import ru.bclib.blocks.BaseLadderBlock; -import ru.bclib.blocks.BaseRotatedPillarBlock; -import ru.bclib.blocks.BaseSignBlock; -import ru.bclib.blocks.BaseSlabBlock; -import ru.bclib.blocks.BaseStairsBlock; -import ru.bclib.blocks.BaseStripableLogBlock; -import ru.bclib.blocks.BaseTrapdoorBlock; -import ru.bclib.blocks.BaseWoodenButtonBlock; -import ru.bclib.blocks.StripableBarkBlock; -import ru.bclib.blocks.WoodenPressurePlateBlock; -import ru.bclib.config.Configs; -import ru.bclib.recipes.GridRecipe; - -import java.util.function.BiFunction; - -public class WoodenMaterial { - public final static String NAME_STRIPPED_LOG = "stripped_log"; - public final static String NAME_STRIPPED_BARK = "stripped_bark"; - public final static String NAME_LOG = "log"; - public final static String NAME_BARK = "bark"; - public final static String NAME_PLANKS = "planks"; - public final static String NAME_STAIRS = "stairs"; - public final static String NAME_SLAB = "slab"; - public final static String NAME_FENCE = "fence"; - public final static String NAME_GATE = "gate"; - public final static String NAME_BUTTON = "button"; - public final static String NAME_PLATE = "plate"; - public final static String NAME_TRAPDOOR = "trapdoor"; - public final static String NAME_DOOR = "door"; - public final static String NAME_CRAFTING_TABLE = "crafting_table"; - public final static String NAME_LADDER = "ladder"; - public final static String NAME_SIGN = "sign"; - public final static String NAME_CHEST = "chest"; - public final static String NAME_BARREL = "barrel"; - public final static String NAME_BOOKSHELF = "bookshelf"; - public final static String NAME_COMPOSTER = "composter"; - - public final static String NAME_PRESSURE_PLATE = "pressure_plate"; - public final static String NAME_SHULKER = "shulker"; - - public final Block log; - public final Block bark; - - public final Block log_stripped; - public final Block bark_stripped; - - public final Block planks; - - public final Block stairs; - public final Block slab; - public final Block fence; - public final Block gate; - public final Block button; - public final Block pressurePlate; - public final Block trapdoor; - public final Block door; - - public final Block craftingTable; - public final Block ladder; - public final Block sign; - - public final Block chest; - public final Block barrel; - //public final Block shelf; - //public final Block composter; - - protected final FabricBlockSettings materialPlanks; - protected final String modID; - protected final String name; - protected final String receipGroupPrefix; - - public final Tag.Named logBlockTag; - public final Tag.Named logItemTag; - - protected Block newLogStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseRotatedPillarBlock(materialPlanks); } - protected Block newBarkStripped(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarkBlock(materialPlanks); } - protected Block newLog(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (log_stripped!=null) return new BaseStripableLogBlock(woodColor, log_stripped); else return null;} - protected Block newBark(FabricBlockSettings materialPlanks, MaterialColor woodColor) { if (bark_stripped!=null) return new StripableBarkBlock(woodColor, bark_stripped); else return null;} - protected Block newPlanks(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBlock(materialPlanks); } - protected Block newStairs(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseStairsBlock(planks); } - protected Block newSlab(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSlabBlock(planks); } - protected Block newFence(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseFenceBlock(planks); } - protected Block newGate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseGateBlock(planks); } - protected Block newButton(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseWoodenButtonBlock(planks); } - protected Block newPressurePlate(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new WoodenPressurePlateBlock(planks); } - protected Block newTrapdoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseTrapdoorBlock(planks); } - protected Block newDoor(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseDoorBlock(planks); } - protected Block newCraftingTable(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseCraftingTableBlock(planks); } - protected Block newLadder(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseLadderBlock(planks); } - protected Block newSign(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseSignBlock(planks); } - protected Block newChest(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseChestBlock(planks); } - protected Block newBarrel(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBarrelBlock(planks); } - //protected Block newShelf(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseBookshelfBlock(planks); } - //protected Block newComposter(FabricBlockSettings materialPlanks, MaterialColor woodColor) { return new BaseComposterBlock(planks); } - - public WoodenMaterial(String modID, String name, MaterialColor woodColor, MaterialColor planksColor, String receipGroupPrefix, BiFunction registerBlock) { - materialPlanks = FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).mapColor(planksColor); - this.modID = modID; - this.receipGroupPrefix = receipGroupPrefix; - this.name = name; - - log_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_LOG, newLogStripped(materialPlanks, woodColor)); - bark_stripped = registerBlock.apply(name + "_" + NAME_STRIPPED_BARK, newBarkStripped(materialPlanks, woodColor)); - - log = registerBlock.apply(name + "_" + NAME_LOG, newLog(materialPlanks, woodColor)); - bark = registerBlock.apply(name + "_" + NAME_BARK, newBark(materialPlanks, woodColor)); - - planks = registerBlock.apply(name + "_" + NAME_PLANKS, newPlanks(materialPlanks, woodColor)); - stairs = registerBlock.apply(name + "_" + NAME_STAIRS, newStairs(materialPlanks, woodColor)); - slab = registerBlock.apply(name + "_" + NAME_SLAB, newSlab(materialPlanks, woodColor)); - fence = registerBlock.apply(name + "_" + NAME_FENCE, newFence(materialPlanks, woodColor)); - gate = registerBlock.apply(name + "_" + NAME_GATE, newGate(materialPlanks, woodColor)); - button = registerBlock.apply(name + "_" + NAME_BUTTON, newButton(materialPlanks, woodColor)); - pressurePlate = registerBlock.apply(name + "_" + NAME_PLATE, newPressurePlate(materialPlanks, woodColor)); - trapdoor = registerBlock.apply(name + "_" + NAME_TRAPDOOR, newTrapdoor(materialPlanks, woodColor)); - door = registerBlock.apply(name + "_" + NAME_DOOR, newDoor(materialPlanks, woodColor)); - - craftingTable = registerBlock.apply(name + "_" + NAME_CRAFTING_TABLE, newCraftingTable(materialPlanks, woodColor)); - ladder = registerBlock.apply(name + "_" + NAME_LADDER, newLadder(materialPlanks, woodColor)); - sign = registerBlock.apply(name + "_" + NAME_SIGN, newSign(materialPlanks, woodColor)); - - chest = registerBlock.apply(name + "_" + NAME_CHEST, newChest(materialPlanks, woodColor)); - barrel = registerBlock.apply(name + "_" + NAME_BARREL, newBarrel(materialPlanks, woodColor)); - //shelf = registerBlock.apply(name + "_" + NAME_BOOKSHELF, newShelf(materialPlanks, woodColor)); - //composter = registerBlock.apply(name + "_" + NAME_COMPOSTER, newComposter(materialPlanks, woodColor)); - - // Recipes // - GridRecipe.make(modID, name + "_" + NAME_PLANKS, planks).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setList("#").addMaterial('#', log, bark, log_stripped, bark_stripped).setGroup(receipGroupPrefix + "_planks").build(); - GridRecipe.make(modID, name + "_" + NAME_STAIRS, stairs).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(4).setShape("# ", "## ", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_stairs").build(); - GridRecipe.make(modID, name + "_" + NAME_SLAB, slab).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(6).setShape("###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_slabs").build(); - GridRecipe.make(modID, name + "_" + NAME_FENCE, fence).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("#I#", "#I#").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_fences").build(); - GridRecipe.make(modID, name + "_" + NAME_GATE, gate).checkConfig(Configs.RECIPE_CONFIG).setShape("I#I", "I#I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_planks_gates").build(); - GridRecipe.make(modID, name + "_" + NAME_BUTTON, button).checkConfig(Configs.RECIPE_CONFIG).setList("#").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_buttons").build(); - GridRecipe.make(modID, name + "_" + NAME_PRESSURE_PLATE, pressurePlate).checkConfig(Configs.RECIPE_CONFIG).setShape("##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_planks_plates").build(); - GridRecipe.make(modID, name + "_" + NAME_TRAPDOOR, trapdoor).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(2).setShape("###", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_trapdoors").build(); - GridRecipe.make(modID, name + "_" + NAME_DOOR, door).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("##", "##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_doors").build(); - GridRecipe.make(modID, name + "_" + NAME_CRAFTING_TABLE, craftingTable).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', planks).setGroup(receipGroupPrefix + "_tables").build(); - GridRecipe.make(modID, name + "_" + NAME_LADDER, ladder).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("I I", "I#I", "I I").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_ladders").build(); - GridRecipe.make(modID, name + "_" + NAME_SIGN, sign).checkConfig(Configs.RECIPE_CONFIG).setOutputCount(3).setShape("###", "###", " I ").addMaterial('#', planks).addMaterial('I', Items.STICK).setGroup(receipGroupPrefix + "_signs").build(); - GridRecipe.make(modID, name + "_" + NAME_CHEST, chest).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "# #", "###").addMaterial('#', planks).setGroup(receipGroupPrefix + "_chests").build(); - GridRecipe.make(modID, name + "_" + NAME_BARREL, barrel).checkConfig(Configs.RECIPE_CONFIG).setShape("#S#", "# #", "#S#").addMaterial('#', planks).addMaterial('S', slab).setGroup(receipGroupPrefix + "_barrels").build(); - //GridRecipe.make(modID, name + "_" + NAME_BOOKSHELF, shelf).checkConfig(Configs.RECIPE_CONFIG).setShape("###", "PPP", "###").addMaterial('#', planks).addMaterial('P', Items.BOOK).setGroup(receipGroupPrefix + "_bookshelves").build(); - GridRecipe.make(modID, name + "_" + NAME_BARK, bark).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', log).setOutputCount(3).build(); - GridRecipe.make(modID, name + "_" + NAME_LOG, log).checkConfig(Configs.RECIPE_CONFIG).setShape("##", "##").addMaterial('#', bark).setOutputCount(3).build(); - //GridRecipe.make(modID, name + "_" + NAME_COMPOSTER, composter).checkConfig(Configs.RECIPE_CONFIG).setShape("# #", "# #", "###").addMaterial('#', slab).build(); - GridRecipe.make(modID, name + "_" + NAME_SHULKER, Items.SHULKER_BOX).checkConfig(Configs.RECIPE_CONFIG).setShape("S", "#", "S").addMaterial('S', Items.SHULKER_SHELL).addMaterial('#', chest).build(); - - // Item Tags // - TagAPI.addTag(ItemTags.PLANKS, planks); - TagAPI.addTag(ItemTags.WOODEN_PRESSURE_PLATES, pressurePlate); - TagAPI.addTag(ItemTags.LOGS, log, bark, log_stripped, bark_stripped); - TagAPI.addTag(ItemTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); - - - TagAPI.addTags(button, ItemTags.WOODEN_BUTTONS, ItemTags.BUTTONS); - TagAPI.addTags(door, ItemTags.WOODEN_DOORS, ItemTags.DOORS); - TagAPI.addTags(fence, ItemTags.WOODEN_FENCES, ItemTags.FENCES); - TagAPI.addTags(slab, ItemTags.WOODEN_SLABS, ItemTags.SLABS); - TagAPI.addTags(stairs, ItemTags.WOODEN_STAIRS, ItemTags.STAIRS); - TagAPI.addTags(trapdoor, ItemTags.WOODEN_TRAPDOORS, ItemTags.TRAPDOORS); - TagAPI.addTag(TagAPI.ITEM_CHEST, chest); - - // Block Tags // - TagAPI.addTag(BlockTags.PLANKS, planks); - TagAPI.addTag(BlockTags.CLIMBABLE, ladder); - TagAPI.addTag(BlockTags.LOGS, log, bark, log_stripped, bark_stripped); - TagAPI.addTag(BlockTags.LOGS_THAT_BURN, log, bark, log_stripped, bark_stripped); - - - TagAPI.addTags(button, BlockTags.WOODEN_BUTTONS, BlockTags.BUTTONS); - TagAPI.addTags(door, BlockTags.WOODEN_DOORS, BlockTags.DOORS); - TagAPI.addTags(fence, BlockTags.WOODEN_FENCES, BlockTags.FENCES); - TagAPI.addTags(slab, BlockTags.WOODEN_SLABS, BlockTags.SLABS); - TagAPI.addTags(stairs, BlockTags.WOODEN_STAIRS, BlockTags.STAIRS); - TagAPI.addTags(trapdoor, BlockTags.WOODEN_TRAPDOORS, BlockTags.TRAPDOORS); - //TagAPI.addTag(TagAPI.BLOCK_BOOKSHELVES, shelf); - TagAPI.addTag(TagAPI.BLOCK_CHEST, chest); - - logBlockTag = TagAPI.makeBlockTag(modID, name + "_logs"); - logItemTag = TagAPI.makeItemTag(modID, name + "_logs"); - TagAPI.addTag(logBlockTag, log_stripped, bark_stripped, log, bark); - TagAPI.addTag(logItemTag, log_stripped, bark_stripped, log, bark); - - addFlammable(); - } - - protected void addFlammable() { - FlammableBlockRegistry.getDefaultInstance().add(log, 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(bark, 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(log_stripped, 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(bark_stripped, 5, 5); - - FlammableBlockRegistry.getDefaultInstance().add(planks, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(stairs, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(slab, 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(fence, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(gate, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(button, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(pressurePlate, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(trapdoor, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(door, 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(craftingTable, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(ladder, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(sign, 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(chest, 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(barrel, 5, 20); - //FlammableBlockRegistry.getDefaultInstance().add(shelf, 5, 20); - //FlammableBlockRegistry.getDefaultInstance().add(composter, 5, 20); - } - - public boolean isTreeLog(Block block) { - return block!=null && (block == log || block == bark); - } - - public boolean isTreeLog(BlockState state) { - return isTreeLog(state.getBlock()); - } -} \ No newline at end of file diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java new file mode 100644 index 00000000..e2dd8b5e --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -0,0 +1,169 @@ +package ru.bclib.complexmaterials; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import org.jetbrains.annotations.Nullable; +import ru.bclib.complexmaterials.entry.BlockEntry; +import ru.bclib.complexmaterials.entry.ItemEntry; +import ru.bclib.registry.BlocksRegistry; +import ru.bclib.registry.ItemsRegistry; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public abstract class ComplexMaterial { + private static final Map, List> BLOCK_ENTRIES = Maps.newHashMap(); + private static final Map, List> ITEM_ENTRIES = Maps.newHashMap(); + private static final List MATERIALS = Lists.newArrayList(); + + private final List defaultBlockEntries = Lists.newArrayList(); + private final List defaultItemEntries = Lists.newArrayList(); + private final Map> blockTags = Maps.newHashMap(); + private final Map> itemTags = Maps.newHashMap(); + private final Map blocks = Maps.newHashMap(); + private final Map items = Maps.newHashMap(); + + private final BlocksRegistry blocksRegistry; + private final ItemsRegistry itemsRegistry; + + private final String baseName; + private final String modID; + + public ComplexMaterial(String modID, String baseName, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry) { + this.blocksRegistry = blocksRegistry; + this.itemsRegistry = itemsRegistry; + this.baseName = baseName; + this.modID = modID; + MATERIALS.add(this); + } + + public void init() { + initTags(); + + final FabricBlockSettings blockSettings = getBlockSettings(); + final FabricItemSettings itemSettings = getItemSettings(itemsRegistry); + initDefault(blockSettings, itemSettings); + + getBlockEntries().forEach(entry -> { + Block block = entry.init(this, blockSettings, blocksRegistry); + blocks.put(entry.getName(baseName), block); + }); + + getItemEntries().forEach(entry -> { + Item item = entry.init(this, itemSettings, itemsRegistry); + items.put(entry.getName(baseName), item); + }); + + initRecipes(); + } + + public abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); + + public void initTags() {} + + public void initRecipes() {} + + protected void addBlockTag(Tag.Named tag) { + blockTags.put(tag.getName().getPath(), tag); + } + + protected void addItemTag(Tag.Named tag) { + itemTags.put(tag.getName().getPath(), tag); + } + + @Nullable + public Tag.Named getBlockTag(String key) { + return blockTags.get(key); + } + + @Nullable + public Tag.Named getItemTag(String key) { + return itemTags.get(key); + } + + @Nullable + public Block getBlock(String key) { + return blocks.get(key); + } + + @Nullable + public Item getItem(String key) { + return items.get(key); + } + + protected abstract FabricBlockSettings getBlockSettings(); + + protected FabricItemSettings getItemSettings(ItemsRegistry registry) { + return registry.makeItemSettings(); + } + + private Collection getBlockEntries() { + List result = Lists.newArrayList(defaultBlockEntries); + List entries = BLOCK_ENTRIES.get(this.getClass()); + if (entries != null) { + result.addAll(entries); + } + return result; + } + + private Collection getItemEntries() { + List result = Lists.newArrayList(defaultItemEntries); + List entries = ITEM_ENTRIES.get(this.getClass()); + if (entries != null) { + result.addAll(entries); + } + return result; + } + + public BlocksRegistry getBlocksRegistry() { + return blocksRegistry; + } + + public ItemsRegistry getItemsRegistry() { + return itemsRegistry; + } + + public String getBaseName() { + return baseName; + } + + public String getModID() { + return modID; + } + + protected void addBlockEntry(BlockEntry entry) { + defaultBlockEntries.add(entry); + } + + protected void addItemEntry(ItemEntry entry) { + defaultItemEntries.add(entry); + } + + public static void addBlockEntry(Class key, BlockEntry entry) { + List entries = BLOCK_ENTRIES.get(key); + if (entries == null) { + entries = Lists.newArrayList(); + BLOCK_ENTRIES.put(key, entries); + } + entries.add(entry); + } + + public static void addItemEntry(Class key, ItemEntry entry) { + List entries = ITEM_ENTRIES.get(key); + if (entries == null) { + entries = Lists.newArrayList(); + ITEM_ENTRIES.put(key, entries); + } + entries.add(entry); + } + + public static Collection getAllMaterials() { + return MATERIALS; + } +} diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java new file mode 100644 index 00000000..036dc405 --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -0,0 +1,149 @@ +package ru.bclib.complexmaterials; + +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.tags.BlockTags; +import net.minecraft.tags.ItemTags; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.MaterialColor; +import ru.bclib.api.TagAPI; +import ru.bclib.blocks.BaseBarkBlock; +import ru.bclib.blocks.BaseBarrelBlock; +import ru.bclib.blocks.BaseBlock; +import ru.bclib.blocks.BaseBookshelfBlock; +import ru.bclib.blocks.BaseChestBlock; +import ru.bclib.blocks.BaseComposterBlock; +import ru.bclib.blocks.BaseCraftingTableBlock; +import ru.bclib.blocks.BaseDoorBlock; +import ru.bclib.blocks.BaseFenceBlock; +import ru.bclib.blocks.BaseGateBlock; +import ru.bclib.blocks.BaseLadderBlock; +import ru.bclib.blocks.BaseRotatedPillarBlock; +import ru.bclib.blocks.BaseSignBlock; +import ru.bclib.blocks.BaseSlabBlock; +import ru.bclib.blocks.BaseStairsBlock; +import ru.bclib.blocks.BaseTrapdoorBlock; +import ru.bclib.blocks.BaseWoodenButtonBlock; +import ru.bclib.blocks.StripableBarkBlock; +import ru.bclib.blocks.WoodenPressurePlateBlock; +import ru.bclib.complexmaterials.entry.BlockEntry; +import ru.bclib.registry.BlocksRegistry; +import ru.bclib.registry.ItemsRegistry; + +public class WoodenMaterial extends ComplexMaterial { + public final MaterialColor planksColor; + public final MaterialColor woodColor; + + public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry) { + super(modID, baseName, blocksRegistry, itemsRegistry); + this.planksColor = planksColor; + this.woodColor = woodColor; + } + + @Override + protected FabricBlockSettings getBlockSettings() { + return FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).materialColor(planksColor); + } + + @Override + public void initTags() { + addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); + addItemTag(TagAPI.makeItemTag(getModID(), getBaseName() + "_logs")); + } + + @Override + public void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + Tag.Named tagBlockLog = getBlockTag(getBaseName() + "_logs"); + Tag.Named tagItemLog = getItemTag(getBaseName() + "_logs"); + + addBlockEntry( + new BlockEntry("stripped_log", (complexMaterial, settings) -> { + return new BaseRotatedPillarBlock(settings); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry( + new BlockEntry("stripped_bark", (complexMaterial, settings) -> { + return new BaseBarkBlock(settings); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + + addBlockEntry( + new BlockEntry("log", (complexMaterial, settings) -> { + return new StripableBarkBlock(woodColor, getBlock("log_stripped")); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry( + new BlockEntry("bark", (complexMaterial, settings) -> { + return new StripableBarkBlock(woodColor, getBlock("bark_stripped")); + }) + .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) + .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) + ); + addBlockEntry(new BlockEntry("planks", (complexMaterial, settings) -> { + return new BaseBlock(settings); + }).setBlockTags(BlockTags.PLANKS)); + + final Block planks = getBlock("planks"); + addBlockEntry(new BlockEntry("stairs", (complexMaterial, settings) -> { + return new BaseStairsBlock(planks); + })); + addBlockEntry(new BlockEntry("slab", (complexMaterial, settings) -> { + return new BaseSlabBlock(planks); + })); + addBlockEntry(new BlockEntry("fence", (complexMaterial, settings) -> { + return new BaseFenceBlock(planks); + })); + addBlockEntry(new BlockEntry("gate", (complexMaterial, settings) -> { + return new BaseGateBlock(planks); + })); + addBlockEntry(new BlockEntry("button", (complexMaterial, settings) -> { + return new BaseWoodenButtonBlock(planks); + })); + addBlockEntry(new BlockEntry("plate", (complexMaterial, settings) -> { + return new WoodenPressurePlateBlock(planks); + })); + addBlockEntry(new BlockEntry("trapdoor", (complexMaterial, settings) -> { + return new BaseTrapdoorBlock(planks); + })); + addBlockEntry(new BlockEntry("door", (complexMaterial, settings) -> { + return new BaseDoorBlock(planks); + })); + + addBlockEntry(new BlockEntry("crafting_table", (complexMaterial, settings) -> { + return new BaseCraftingTableBlock(planks); + })); + addBlockEntry(new BlockEntry("ladder", (complexMaterial, settings) -> { + return new BaseLadderBlock(planks); + }).setBlockTags(BlockTags.CLIMBABLE)); + addBlockEntry(new BlockEntry("sign", (complexMaterial, settings) -> { + return new BaseSignBlock(planks); + })); + + addBlockEntry(new BlockEntry("chest", (complexMaterial, settings) -> { + return new BaseChestBlock(planks); + })); + addBlockEntry(new BlockEntry("barrel", (complexMaterial, settings) -> { + return new BaseBarrelBlock(planks); + })); + addBlockEntry(new BlockEntry("bookshelf", (complexMaterial, settings) -> { + return new BaseBookshelfBlock(planks); + })); + addBlockEntry(new BlockEntry("composter", (complexMaterial, settings) -> { + return new BaseComposterBlock(planks); + })); + } + + @Override + public void initRecipes() { + + } +} \ No newline at end of file diff --git a/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java new file mode 100644 index 00000000..b892c1ab --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java @@ -0,0 +1,58 @@ +package ru.bclib.complexmaterials.entry; + +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import ru.bclib.api.TagAPI; +import ru.bclib.complexmaterials.ComplexMaterial; +import ru.bclib.registry.BlocksRegistry; + +import java.util.function.BiFunction; + +public class BlockEntry extends ComplexMaterialEntry { + final BiFunction initFunction; + final boolean hasItem; + + Tag.Named[] blockTags; + Tag.Named[] itemTags; + + public BlockEntry(String suffix, BiFunction initFunction) { + this(suffix, true, initFunction); + } + + public BlockEntry(String suffix, boolean hasItem, BiFunction initFunction) { + super(suffix); + this.initFunction = initFunction; + this.hasItem = hasItem; + } + + public BlockEntry setBlockTags(Tag.Named... blockTags) { + this.blockTags = blockTags; + return this; + } + + public BlockEntry setItemTags(Tag.Named... itemTags) { + this.itemTags = itemTags; + return this; + } + + public Block init(ComplexMaterial material, FabricBlockSettings blockSettings, BlocksRegistry registry) { + ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); + Block block = initFunction.apply(material, blockSettings); + if (hasItem) { + registry.register(location, block); + if (itemTags != null) { + TagAPI.addTags(block, itemTags); + } + } + else { + registry.registerBlockOnly(location, block); + } + if (blockTags != null) { + TagAPI.addTags(block, blockTags); + } + return block; + } +} diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java new file mode 100644 index 00000000..4f7ebc3f --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java @@ -0,0 +1,19 @@ +package ru.bclib.complexmaterials.entry; + +import net.minecraft.resources.ResourceLocation; + +public abstract class ComplexMaterialEntry { + private final String suffix; + + protected ComplexMaterialEntry(String suffix) { + this.suffix = suffix; + } + + public String getName(String baseName) { + return baseName + "_" + suffix; + } + + public ResourceLocation getLocation(String modID, String baseName) { + return new ResourceLocation(modID, getName(baseName)); + } +} diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java new file mode 100644 index 00000000..9377d9c9 --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java @@ -0,0 +1,37 @@ +package ru.bclib.complexmaterials.entry; + +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import ru.bclib.api.TagAPI; +import ru.bclib.complexmaterials.ComplexMaterial; +import ru.bclib.registry.ItemsRegistry; + +import java.util.function.BiFunction; + +public class ItemEntry extends ComplexMaterialEntry { + final BiFunction initFunction; + + Tag.Named[] itemTags; + + public ItemEntry(String suffix, BiFunction initFunction) { + super(suffix); + this.initFunction = initFunction; + } + + public ItemEntry setItemTags(Tag.Named[] itemTags) { + this.itemTags = itemTags; + return this; + } + + public Item init(ComplexMaterial material, FabricItemSettings itemSettings, ItemsRegistry registry) { + ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); + Item item = initFunction.apply(material, itemSettings); + registry.register(location, item); + if (itemTags != null) { + TagAPI.addTags(item, itemTags); + } + return item; + } +} diff --git a/src/main/java/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlocksRegistry.java index 4af14c9c..4521b94a 100644 --- a/src/main/java/ru/bclib/registry/BlocksRegistry.java +++ b/src/main/java/ru/bclib/registry/BlocksRegistry.java @@ -10,7 +10,6 @@ import net.minecraft.world.level.block.Block; import ru.bclib.interfaces.CustomItemProvider; public abstract class BlocksRegistry extends BaseRegistry { - protected BlocksRegistry(CreativeModeTab creativeTab) { super(creativeTab); } @@ -33,11 +32,11 @@ public abstract class BlocksRegistry extends BaseRegistry { return Registry.register(Registry.BLOCK, id, block); } - public Block registerBlockOnly(String name, Block block) { - return Registry.register(Registry.BLOCK, createModId(name), block); + public Block registerBlockOnly(ResourceLocation id, Block block) { + return Registry.register(Registry.BLOCK, id, block); } - public Item registerBlockItem(ResourceLocation id, Item item) { + private Item registerBlockItem(ResourceLocation id, Item item) { registerItem(id, item, BaseRegistry.getModBlocks(id.getNamespace())); return item; } From edf9e1d004c24533c69353b69496f5473463e8b6 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 13:41:54 +0300 Subject: [PATCH 0099/1033] Material init --- src/main/java/ru/bclib/client/BCLibClient.java | 2 ++ src/main/java/ru/bclib/server/BCLibServer.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 8935ce7e..b2a78a56 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -7,6 +7,7 @@ import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.complexmaterials.ComplexMaterial; import ru.bclib.interfaces.PostInitable; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.registry.BaseBlockEntityRenders; @@ -14,6 +15,7 @@ import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @Override public void onInitializeClient() { + ComplexMaterial.getAllMaterials().forEach(material -> material.init()); ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); PostInitAPI.postInit(true); diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index 0cd2b803..e16f8ca3 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -4,11 +4,13 @@ import net.fabricmc.api.DedicatedServerModInitializer; import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; +import ru.bclib.complexmaterials.ComplexMaterial; import ru.bclib.interfaces.PostInitable; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { + ComplexMaterial.getAllMaterials().forEach(material -> material.init()); ModIntegrationAPI.registerAll(); PostInitAPI.postInit(false); } From ddbdc0207de15a18ea509641ec1be3170fca5ebb Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 14:13:36 +0300 Subject: [PATCH 0100/1033] Wooden material tags --- .../complexmaterials/ComplexMaterial.java | 13 +++-- .../complexmaterials/WoodenMaterial.java | 58 ++++++++++++++----- .../entry/ComplexMaterialEntry.java | 4 ++ 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index e2dd8b5e..beb06dd9 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -52,22 +52,25 @@ public abstract class ComplexMaterial { getBlockEntries().forEach(entry -> { Block block = entry.init(this, blockSettings, blocksRegistry); - blocks.put(entry.getName(baseName), block); + blocks.put(entry.getSuffix(), block); }); getItemEntries().forEach(entry -> { Item item = entry.init(this, itemSettings, itemsRegistry); - items.put(entry.getName(baseName), item); + items.put(entry.getSuffix(), item); }); initRecipes(); + initFlammable(); } - public abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); + protected abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); - public void initTags() {} + protected void initTags() {} - public void initRecipes() {} + protected void initRecipes() {} + + protected void initFlammable() {} protected void addBlockTag(Tag.Named tag) { blockTags.put(tag.getName().getPath(), tag); diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index 036dc405..cbcd81f7 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -2,6 +2,7 @@ package ru.bclib.complexmaterials; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; @@ -49,13 +50,13 @@ public class WoodenMaterial extends ComplexMaterial { } @Override - public void initTags() { + protected void initTags() { addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); addItemTag(TagAPI.makeItemTag(getModID(), getBaseName() + "_logs")); } @Override - public void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { Tag.Named tagBlockLog = getBlockTag(getBaseName() + "_logs"); Tag.Named tagItemLog = getItemTag(getBaseName() + "_logs"); @@ -90,58 +91,85 @@ public class WoodenMaterial extends ComplexMaterial { ); addBlockEntry(new BlockEntry("planks", (complexMaterial, settings) -> { return new BaseBlock(settings); - }).setBlockTags(BlockTags.PLANKS)); + }).setBlockTags(BlockTags.PLANKS).setItemTags(ItemTags.PLANKS)); final Block planks = getBlock("planks"); addBlockEntry(new BlockEntry("stairs", (complexMaterial, settings) -> { return new BaseStairsBlock(planks); - })); + }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS).setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); addBlockEntry(new BlockEntry("slab", (complexMaterial, settings) -> { return new BaseSlabBlock(planks); - })); + }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS).setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); addBlockEntry(new BlockEntry("fence", (complexMaterial, settings) -> { return new BaseFenceBlock(planks); - })); + }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES).setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); addBlockEntry(new BlockEntry("gate", (complexMaterial, settings) -> { return new BaseGateBlock(planks); - })); + }).setBlockTags(BlockTags.FENCE_GATES)); addBlockEntry(new BlockEntry("button", (complexMaterial, settings) -> { return new BaseWoodenButtonBlock(planks); - })); + }).setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS).setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); addBlockEntry(new BlockEntry("plate", (complexMaterial, settings) -> { return new WoodenPressurePlateBlock(planks); - })); + }).setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES).setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); addBlockEntry(new BlockEntry("trapdoor", (complexMaterial, settings) -> { return new BaseTrapdoorBlock(planks); - })); + }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS).setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); addBlockEntry(new BlockEntry("door", (complexMaterial, settings) -> { return new BaseDoorBlock(planks); - })); + }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS).setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); addBlockEntry(new BlockEntry("crafting_table", (complexMaterial, settings) -> { return new BaseCraftingTableBlock(planks); - })); + }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); addBlockEntry(new BlockEntry("ladder", (complexMaterial, settings) -> { return new BaseLadderBlock(planks); }).setBlockTags(BlockTags.CLIMBABLE)); addBlockEntry(new BlockEntry("sign", (complexMaterial, settings) -> { return new BaseSignBlock(planks); - })); + }).setBlockTags(BlockTags.SIGNS).setItemTags(ItemTags.SIGNS)); addBlockEntry(new BlockEntry("chest", (complexMaterial, settings) -> { return new BaseChestBlock(planks); - })); + }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); addBlockEntry(new BlockEntry("barrel", (complexMaterial, settings) -> { return new BaseBarrelBlock(planks); })); addBlockEntry(new BlockEntry("bookshelf", (complexMaterial, settings) -> { return new BaseBookshelfBlock(planks); - })); + }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); addBlockEntry(new BlockEntry("composter", (complexMaterial, settings) -> { return new BaseComposterBlock(planks); })); } + protected void initFlammable() { + FlammableBlockRegistry.getDefaultInstance().add(getBlock("log"), 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("bark"), 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("log_stripped"), 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("bark_stripped"), 5, 5); + + FlammableBlockRegistry.getDefaultInstance().add(getBlock("planks"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("stairs"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("slab"), 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(getBlock("fence"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("gate"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("button"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("pressurePlate"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("trapdoor"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("door"), 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(getBlock("craftingTable"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("ladder"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("sign"), 5, 20); + + FlammableBlockRegistry.getDefaultInstance().add(getBlock("chest"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("barrel"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("shelf"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("composter"), 5, 20); + } + @Override public void initRecipes() { diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java index 4f7ebc3f..3a1cf5fa 100644 --- a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java +++ b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java @@ -16,4 +16,8 @@ public abstract class ComplexMaterialEntry { public ResourceLocation getLocation(String modID, String baseName) { return new ResourceLocation(modID, getName(baseName)); } + + public String getSuffix() { + return suffix; + } } From b661aedd60d27696d8196e78972a33c93058d5a3 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 14:24:02 +0300 Subject: [PATCH 0101/1033] Recipes, fixes --- .../complexmaterials/ComplexMaterial.java | 9 +- .../complexmaterials/WoodenMaterial.java | 165 +++++++++++++++++- 2 files changed, 164 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index beb06dd9..0830f3c8 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -10,6 +10,7 @@ import net.minecraft.world.level.block.Block; import org.jetbrains.annotations.Nullable; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.complexmaterials.entry.ItemEntry; +import ru.bclib.config.PathConfig; import ru.bclib.registry.BlocksRegistry; import ru.bclib.registry.ItemsRegistry; @@ -31,13 +32,15 @@ public abstract class ComplexMaterial { private final BlocksRegistry blocksRegistry; private final ItemsRegistry itemsRegistry; + private final PathConfig recipeConfig; private final String baseName; private final String modID; - public ComplexMaterial(String modID, String baseName, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry) { + public ComplexMaterial(String modID, String baseName, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry, PathConfig recipeConfig) { this.blocksRegistry = blocksRegistry; this.itemsRegistry = itemsRegistry; + this.recipeConfig = recipeConfig; this.baseName = baseName; this.modID = modID; MATERIALS.add(this); @@ -60,7 +63,7 @@ public abstract class ComplexMaterial { items.put(entry.getSuffix(), item); }); - initRecipes(); + initRecipes(recipeConfig); initFlammable(); } @@ -68,7 +71,7 @@ public abstract class ComplexMaterial { protected void initTags() {} - protected void initRecipes() {} + protected void initRecipes(PathConfig recipeConfig) {} protected void initFlammable() {} diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index cbcd81f7..e56a5ce0 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -7,6 +7,7 @@ import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.material.MaterialColor; @@ -26,11 +27,14 @@ import ru.bclib.blocks.BaseRotatedPillarBlock; import ru.bclib.blocks.BaseSignBlock; import ru.bclib.blocks.BaseSlabBlock; import ru.bclib.blocks.BaseStairsBlock; +import ru.bclib.blocks.BaseStripableLogBlock; import ru.bclib.blocks.BaseTrapdoorBlock; import ru.bclib.blocks.BaseWoodenButtonBlock; import ru.bclib.blocks.StripableBarkBlock; import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; +import ru.bclib.config.PathConfig; +import ru.bclib.recipes.GridRecipe; import ru.bclib.registry.BlocksRegistry; import ru.bclib.registry.ItemsRegistry; @@ -38,8 +42,8 @@ public class WoodenMaterial extends ComplexMaterial { public final MaterialColor planksColor; public final MaterialColor woodColor; - public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry) { - super(modID, baseName, blocksRegistry, itemsRegistry); + public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry, PathConfig recipeConfig) { + super(modID, baseName, blocksRegistry, itemsRegistry, recipeConfig); this.planksColor = planksColor; this.woodColor = woodColor; } @@ -156,22 +160,169 @@ public class WoodenMaterial extends ComplexMaterial { FlammableBlockRegistry.getDefaultInstance().add(getBlock("fence"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("gate"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("button"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("pressurePlate"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("plate"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("trapdoor"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("door"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("craftingTable"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("crafting_table"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("ladder"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("sign"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("chest"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("barrel"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("shelf"), 5, 20); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("bookshelf"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("composter"), 5, 20); } @Override - public void initRecipes() { - + public void initRecipes(PathConfig recipeConfig) { + Block log_stripped = getBlock("stripped_log"); + Block bark_stripped = getBlock("stripped_bark"); + Block log = getBlock("log"); + Block bark = getBlock("bark"); + Block planks = getBlock("planks"); + Block stairs = getBlock("stairs"); + Block slab = getBlock("slab"); + Block fence = getBlock("fence"); + Block gate = getBlock("gate"); + Block button = getBlock("button"); + Block pressurePlate = getBlock("plate"); + Block trapdoor = getBlock("trapdoor"); + Block door = getBlock("door"); + Block craftingTable = getBlock("crafting_table"); + Block ladder = getBlock("ladder"); + Block sign = getBlock("sign"); + Block chest = getBlock("chest"); + Block barrel = getBlock("barrel"); + Block shelf = getBlock("bookshelf"); + Block composter = getBlock("composter"); + + GridRecipe.make(getModID(), getBaseName() + "_planks", planks) + .checkConfig(recipeConfig) + .setOutputCount(4) + .setList("#") + .addMaterial('#', log, bark, log_stripped, bark_stripped) + .setGroup("end_planks") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_stairs", stairs) + .checkConfig(recipeConfig) + .setOutputCount(4) + .setShape("# ", "## ", "###") + .addMaterial('#', planks) + .setGroup("end_planks_stairs") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_slab", slab) + .checkConfig(recipeConfig) + .setOutputCount(6) + .setShape("###") + .addMaterial('#', planks) + .setGroup("end_planks_slabs") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_fence", fence) + .checkConfig(recipeConfig) + .setOutputCount(3) + .setShape("#I#", "#I#") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_planks_fences") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_gate", gate) + .checkConfig(recipeConfig) + .setShape("I#I", "I#I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_planks_gates") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_button", button) + .checkConfig(recipeConfig) + .setList("#") + .addMaterial('#', planks) + .setGroup("end_planks_buttons") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_pressure_plate", pressurePlate) + .checkConfig(recipeConfig) + .setShape("##") + .addMaterial('#', planks) + .setGroup("end_planks_plates") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_trapdoor", trapdoor) + .checkConfig(recipeConfig) + .setOutputCount(2) + .setShape("###", "###") + .addMaterial('#', planks) + .setGroup("end_trapdoors") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_door", door) + .checkConfig(recipeConfig) + .setOutputCount(3) + .setShape("##", "##", "##") + .addMaterial('#', planks) + .setGroup("end_doors") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_crafting_table", craftingTable) + .checkConfig(recipeConfig) + .setShape("##", "##") + .addMaterial('#', planks) + .setGroup("end_tables") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_ladder", ladder) + .checkConfig(recipeConfig) + .setOutputCount(3) + .setShape("I I", "I#I", "I I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_ladders") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_sign", sign) + .checkConfig(recipeConfig) + .setOutputCount(3) + .setShape("###", "###", " I ") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_signs") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_chest", chest) + .checkConfig(recipeConfig) + .setShape("###", "# #", "###") + .addMaterial('#', planks) + .setGroup("end_chests") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_barrel", barrel) + .checkConfig(recipeConfig) + .setShape("#S#", "# #", "#S#") + .addMaterial('#', planks) + .addMaterial('S', slab) + .setGroup("end_barrels") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_bookshelf", shelf) + .checkConfig(recipeConfig) + .setShape("###", "PPP", "###") + .addMaterial('#', planks) + .addMaterial('P', Items.BOOK) + .setGroup("end_BLOCK_BOOKSHELVES") + .build(); + GridRecipe.make(getModID(), getBaseName() + "_bark", bark) + .checkConfig(recipeConfig) + .setShape("##", "##") + .addMaterial('#', log) + .setOutputCount(3) + .build(); + GridRecipe.make(getModID(), getBaseName() + "_log", log) + .checkConfig(recipeConfig) + .setShape("##", "##") + .addMaterial('#', bark) + .setOutputCount(3) + .build(); + GridRecipe.make(getModID(), getBaseName() + "_composter", composter) + .checkConfig(recipeConfig) + .setShape("# #", "# #", "###") + .addMaterial('#', slab) + .build(); + GridRecipe.make(getModID(), getBaseName() + "_shulker", Items.SHULKER_BOX) + .checkConfig(recipeConfig) + .setShape("S", "#", "S") + .addMaterial('S', Items.SHULKER_SHELL) + .addMaterial('#', chest) + .build(); } } \ No newline at end of file From eb18fa63afd1343a082da3931ebc69a17ba4e58b Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 15:03:16 +0300 Subject: [PATCH 0102/1033] Complex material fixes --- .../complexmaterials/ComplexMaterial.java | 32 ++++++++----------- .../complexmaterials/WoodenMaterial.java | 11 +++---- .../complexmaterials/entry/BlockEntry.java | 4 +-- .../complexmaterials/entry/ItemEntry.java | 4 +-- ...BlocksRegistry.java => BlockRegistry.java} | 4 +-- .../{ItemsRegistry.java => ItemRegistry.java} | 4 +-- 6 files changed, 26 insertions(+), 33 deletions(-) rename src/main/java/ru/bclib/registry/{BlocksRegistry.java => BlockRegistry.java} (91%) rename src/main/java/ru/bclib/registry/{ItemsRegistry.java => ItemRegistry.java} (97%) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 0830f3c8..49bc71f4 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -11,8 +11,8 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.complexmaterials.entry.ItemEntry; import ru.bclib.config.PathConfig; -import ru.bclib.registry.BlocksRegistry; -import ru.bclib.registry.ItemsRegistry; +import ru.bclib.registry.BlockRegistry; +import ru.bclib.registry.ItemRegistry; import java.util.Collection; import java.util.List; @@ -30,17 +30,10 @@ public abstract class ComplexMaterial { private final Map blocks = Maps.newHashMap(); private final Map items = Maps.newHashMap(); - private final BlocksRegistry blocksRegistry; - private final ItemsRegistry itemsRegistry; - private final PathConfig recipeConfig; - private final String baseName; private final String modID; - public ComplexMaterial(String modID, String baseName, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry, PathConfig recipeConfig) { - this.blocksRegistry = blocksRegistry; - this.itemsRegistry = itemsRegistry; - this.recipeConfig = recipeConfig; + public ComplexMaterial(String modID, String baseName) { this.baseName = baseName; this.modID = modID; MATERIALS.add(this); @@ -49,6 +42,9 @@ public abstract class ComplexMaterial { public void init() { initTags(); + final BlockRegistry blocksRegistry = getBlockRegistry(); + final ItemRegistry itemsRegistry = getItemRegistry(); + final PathConfig recipeConfig = getRecipeConfig(); final FabricBlockSettings blockSettings = getBlockSettings(); final FabricItemSettings itemSettings = getItemSettings(itemsRegistry); initDefault(blockSettings, itemSettings); @@ -67,6 +63,12 @@ public abstract class ComplexMaterial { initFlammable(); } + protected abstract BlockRegistry getBlockRegistry(); + + protected abstract ItemRegistry getItemRegistry(); + + protected abstract PathConfig getRecipeConfig(); + protected abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); protected void initTags() {} @@ -105,7 +107,7 @@ public abstract class ComplexMaterial { protected abstract FabricBlockSettings getBlockSettings(); - protected FabricItemSettings getItemSettings(ItemsRegistry registry) { + protected FabricItemSettings getItemSettings(ItemRegistry registry) { return registry.makeItemSettings(); } @@ -127,14 +129,6 @@ public abstract class ComplexMaterial { return result; } - public BlocksRegistry getBlocksRegistry() { - return blocksRegistry; - } - - public ItemsRegistry getItemsRegistry() { - return itemsRegistry; - } - public String getBaseName() { return baseName; } diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index e56a5ce0..0d0f74e1 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -27,7 +27,6 @@ import ru.bclib.blocks.BaseRotatedPillarBlock; import ru.bclib.blocks.BaseSignBlock; import ru.bclib.blocks.BaseSlabBlock; import ru.bclib.blocks.BaseStairsBlock; -import ru.bclib.blocks.BaseStripableLogBlock; import ru.bclib.blocks.BaseTrapdoorBlock; import ru.bclib.blocks.BaseWoodenButtonBlock; import ru.bclib.blocks.StripableBarkBlock; @@ -35,15 +34,15 @@ import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; -import ru.bclib.registry.BlocksRegistry; -import ru.bclib.registry.ItemsRegistry; +import ru.bclib.registry.BlockRegistry; +import ru.bclib.registry.ItemRegistry; -public class WoodenMaterial extends ComplexMaterial { +public abstract class WoodenMaterial extends ComplexMaterial { public final MaterialColor planksColor; public final MaterialColor woodColor; - public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor, BlocksRegistry blocksRegistry, ItemsRegistry itemsRegistry, PathConfig recipeConfig) { - super(modID, baseName, blocksRegistry, itemsRegistry, recipeConfig); + public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor) { + super(modID, baseName); this.planksColor = planksColor; this.woodColor = woodColor; } diff --git a/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java index b892c1ab..edda7b8a 100644 --- a/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java +++ b/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java @@ -7,7 +7,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import ru.bclib.api.TagAPI; import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.registry.BlocksRegistry; +import ru.bclib.registry.BlockRegistry; import java.util.function.BiFunction; @@ -38,7 +38,7 @@ public class BlockEntry extends ComplexMaterialEntry { return this; } - public Block init(ComplexMaterial material, FabricBlockSettings blockSettings, BlocksRegistry registry) { + public Block init(ComplexMaterial material, FabricBlockSettings blockSettings, BlockRegistry registry) { ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); Block block = initFunction.apply(material, blockSettings); if (hasItem) { diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java index 9377d9c9..a9be883b 100644 --- a/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java +++ b/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java @@ -6,7 +6,7 @@ import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; import ru.bclib.api.TagAPI; import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.registry.ItemsRegistry; +import ru.bclib.registry.ItemRegistry; import java.util.function.BiFunction; @@ -25,7 +25,7 @@ public class ItemEntry extends ComplexMaterialEntry { return this; } - public Item init(ComplexMaterial material, FabricItemSettings itemSettings, ItemsRegistry registry) { + public Item init(ComplexMaterial material, FabricItemSettings itemSettings, ItemRegistry registry) { ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); Item item = initFunction.apply(material, itemSettings); registry.register(location, item); diff --git a/src/main/java/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java similarity index 91% rename from src/main/java/ru/bclib/registry/BlocksRegistry.java rename to src/main/java/ru/bclib/registry/BlockRegistry.java index 4521b94a..80ee433b 100644 --- a/src/main/java/ru/bclib/registry/BlocksRegistry.java +++ b/src/main/java/ru/bclib/registry/BlockRegistry.java @@ -9,8 +9,8 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import ru.bclib.interfaces.CustomItemProvider; -public abstract class BlocksRegistry extends BaseRegistry { - protected BlocksRegistry(CreativeModeTab creativeTab) { +public abstract class BlockRegistry extends BaseRegistry { + protected BlockRegistry(CreativeModeTab creativeTab) { super(creativeTab); } diff --git a/src/main/java/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java similarity index 97% rename from src/main/java/ru/bclib/registry/ItemsRegistry.java rename to src/main/java/ru/bclib/registry/ItemRegistry.java index dde6333b..d2bc980a 100644 --- a/src/main/java/ru/bclib/registry/ItemsRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -29,9 +29,9 @@ import ru.bclib.items.tool.BaseHoeItem; import ru.bclib.items.tool.BasePickaxeItem; import ru.bclib.api.TagAPI; -public abstract class ItemsRegistry extends BaseRegistry { +public abstract class ItemRegistry extends BaseRegistry { - protected ItemsRegistry(CreativeModeTab creativeTab) { + protected ItemRegistry(CreativeModeTab creativeTab) { super(creativeTab); } From 806992759ad3b593dee1bb83bc7b726f71b0565c Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 17:26:02 +0300 Subject: [PATCH 0103/1033] Complex material init changes --- src/main/java/ru/bclib/client/BCLibClient.java | 8 -------- .../ru/bclib/complexmaterials/ComplexMaterial.java | 12 ++---------- .../ru/bclib/complexmaterials/WoodenMaterial.java | 4 +--- .../bclib/mixin/client/BackgroundRendererMixin.java | 6 ------ .../ru/bclib/mixin/common/MinecraftServerMixin.java | 2 -- .../java/ru/bclib/mixin/common/ServerLevelMixin.java | 4 ---- src/main/java/ru/bclib/registry/ItemRegistry.java | 2 +- src/main/java/ru/bclib/server/BCLibServer.java | 4 ---- 8 files changed, 4 insertions(+), 38 deletions(-) diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index b2a78a56..7b338cfa 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -1,21 +1,13 @@ package ru.bclib.client; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; -import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.interfaces.PostInitable; -import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @Override public void onInitializeClient() { - ComplexMaterial.getAllMaterials().forEach(material -> material.init()); ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); PostInitAPI.postInit(true); diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 49bc71f4..c533a27b 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -39,12 +39,9 @@ public abstract class ComplexMaterial { MATERIALS.add(this); } - public void init() { + public ComplexMaterial init(BlockRegistry blocksRegistry, ItemRegistry itemsRegistry, PathConfig recipeConfig) { initTags(); - final BlockRegistry blocksRegistry = getBlockRegistry(); - final ItemRegistry itemsRegistry = getItemRegistry(); - final PathConfig recipeConfig = getRecipeConfig(); final FabricBlockSettings blockSettings = getBlockSettings(); final FabricItemSettings itemSettings = getItemSettings(itemsRegistry); initDefault(blockSettings, itemSettings); @@ -61,14 +58,9 @@ public abstract class ComplexMaterial { initRecipes(recipeConfig); initFlammable(); + return this; } - protected abstract BlockRegistry getBlockRegistry(); - - protected abstract ItemRegistry getItemRegistry(); - - protected abstract PathConfig getRecipeConfig(); - protected abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); protected void initTags() {} diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index 0d0f74e1..3f259391 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -34,10 +34,8 @@ import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; -import ru.bclib.registry.BlockRegistry; -import ru.bclib.registry.ItemRegistry; -public abstract class WoodenMaterial extends ComplexMaterial { +public class WoodenMaterial extends ComplexMaterial { public final MaterialColor planksColor; public final MaterialColor woodColor; diff --git a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index f8576f4d..916619e5 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -1,28 +1,22 @@ package ru.bclib.mixin.client; -import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Camera; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.FogRenderer; import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.util.Mth; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.material.FogType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import ru.bclib.api.BiomeAPI; import ru.bclib.client.render.CustomBackgroundRenderer; import ru.bclib.util.BackgroundInfo; -import ru.bclib.util.MHelper; -import ru.bclib.world.biomes.BCLBiome; @Mixin(FogRenderer.class) public class BackgroundRendererMixin { diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index 9cd8378b..52495509 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -5,7 +5,6 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerResources; import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.progress.ChunkProgressListener; import net.minecraft.world.level.Level; import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.LevelStorageSource; @@ -15,7 +14,6 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 285fda1e..1717d4f7 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -15,13 +15,9 @@ import net.minecraft.world.level.storage.WritableLevelData; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import ru.bclib.api.BiomeAPI; -import ru.bclib.api.WorldDataAPI; -import ru.bclib.api.datafixer.DataFixerAPI; -import java.io.File; import java.util.List; import java.util.concurrent.Executor; import java.util.function.Supplier; diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java index d2bc980a..270e06da 100644 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -20,6 +20,7 @@ import net.minecraft.world.item.SpawnEggItem; import net.minecraft.world.item.SwordItem; import net.minecraft.world.item.TieredItem; import net.minecraft.world.level.block.DispenserBlock; +import ru.bclib.api.TagAPI; import ru.bclib.items.BaseDiscItem; import ru.bclib.items.BaseDrinkItem; import ru.bclib.items.BaseSpawnEggItem; @@ -27,7 +28,6 @@ import ru.bclib.items.ModelProviderItem; import ru.bclib.items.tool.BaseAxeItem; import ru.bclib.items.tool.BaseHoeItem; import ru.bclib.items.tool.BasePickaxeItem; -import ru.bclib.api.TagAPI; public abstract class ItemRegistry extends BaseRegistry { diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index e16f8ca3..e1ba1107 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -1,16 +1,12 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; -import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; -import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.interfaces.PostInitable; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { - ComplexMaterial.getAllMaterials().forEach(material -> material.init()); ModIntegrationAPI.registerAll(); PostInitAPI.postInit(false); } From 65aae74979179ea544c1b353436f579314c8d6ab Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 17:34:55 +0300 Subject: [PATCH 0104/1033] Small null fix --- .../complexmaterials/WoodenMaterial.java | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index 3f259391..2da51c77 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -94,53 +94,52 @@ public class WoodenMaterial extends ComplexMaterial { return new BaseBlock(settings); }).setBlockTags(BlockTags.PLANKS).setItemTags(ItemTags.PLANKS)); - final Block planks = getBlock("planks"); addBlockEntry(new BlockEntry("stairs", (complexMaterial, settings) -> { - return new BaseStairsBlock(planks); + return new BaseStairsBlock(getBlock("planks")); }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS).setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); addBlockEntry(new BlockEntry("slab", (complexMaterial, settings) -> { - return new BaseSlabBlock(planks); + return new BaseSlabBlock(getBlock("planks")); }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS).setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); addBlockEntry(new BlockEntry("fence", (complexMaterial, settings) -> { - return new BaseFenceBlock(planks); + return new BaseFenceBlock(getBlock("planks")); }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES).setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); addBlockEntry(new BlockEntry("gate", (complexMaterial, settings) -> { - return new BaseGateBlock(planks); + return new BaseGateBlock(getBlock("planks")); }).setBlockTags(BlockTags.FENCE_GATES)); addBlockEntry(new BlockEntry("button", (complexMaterial, settings) -> { - return new BaseWoodenButtonBlock(planks); + return new BaseWoodenButtonBlock(getBlock("planks")); }).setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS).setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); addBlockEntry(new BlockEntry("plate", (complexMaterial, settings) -> { - return new WoodenPressurePlateBlock(planks); + return new WoodenPressurePlateBlock(getBlock("planks")); }).setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES).setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); addBlockEntry(new BlockEntry("trapdoor", (complexMaterial, settings) -> { - return new BaseTrapdoorBlock(planks); + return new BaseTrapdoorBlock(getBlock("planks")); }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS).setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); addBlockEntry(new BlockEntry("door", (complexMaterial, settings) -> { - return new BaseDoorBlock(planks); + return new BaseDoorBlock(getBlock("planks")); }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS).setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); addBlockEntry(new BlockEntry("crafting_table", (complexMaterial, settings) -> { - return new BaseCraftingTableBlock(planks); + return new BaseCraftingTableBlock(getBlock("planks")); }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); addBlockEntry(new BlockEntry("ladder", (complexMaterial, settings) -> { - return new BaseLadderBlock(planks); + return new BaseLadderBlock(getBlock("planks")); }).setBlockTags(BlockTags.CLIMBABLE)); addBlockEntry(new BlockEntry("sign", (complexMaterial, settings) -> { - return new BaseSignBlock(planks); + return new BaseSignBlock(getBlock("planks")); }).setBlockTags(BlockTags.SIGNS).setItemTags(ItemTags.SIGNS)); addBlockEntry(new BlockEntry("chest", (complexMaterial, settings) -> { - return new BaseChestBlock(planks); + return new BaseChestBlock(getBlock("planks")); }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); addBlockEntry(new BlockEntry("barrel", (complexMaterial, settings) -> { - return new BaseBarrelBlock(planks); + return new BaseBarrelBlock(getBlock("planks")); })); addBlockEntry(new BlockEntry("bookshelf", (complexMaterial, settings) -> { - return new BaseBookshelfBlock(planks); + return new BaseBookshelfBlock(getBlock("planks")); }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); addBlockEntry(new BlockEntry("composter", (complexMaterial, settings) -> { - return new BaseComposterBlock(planks); + return new BaseComposterBlock(getBlock("planks")); })); } From ec61f22682b37b4a06d3f368dae27edc4751ac17 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 17:54:42 +0300 Subject: [PATCH 0105/1033] Small fixes --- .../java/ru/bclib/complexmaterials/WoodenMaterial.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index 2da51c77..049879b2 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -27,6 +27,7 @@ import ru.bclib.blocks.BaseRotatedPillarBlock; import ru.bclib.blocks.BaseSignBlock; import ru.bclib.blocks.BaseSlabBlock; import ru.bclib.blocks.BaseStairsBlock; +import ru.bclib.blocks.BaseStripableLogBlock; import ru.bclib.blocks.BaseTrapdoorBlock; import ru.bclib.blocks.BaseWoodenButtonBlock; import ru.bclib.blocks.StripableBarkBlock; @@ -78,14 +79,14 @@ public class WoodenMaterial extends ComplexMaterial { addBlockEntry( new BlockEntry("log", (complexMaterial, settings) -> { - return new StripableBarkBlock(woodColor, getBlock("log_stripped")); + return new BaseStripableLogBlock(woodColor, getBlock("stripped_log")); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) ); addBlockEntry( new BlockEntry("bark", (complexMaterial, settings) -> { - return new StripableBarkBlock(woodColor, getBlock("bark_stripped")); + return new StripableBarkBlock(woodColor, getBlock("stripped_bark")); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) @@ -146,8 +147,8 @@ public class WoodenMaterial extends ComplexMaterial { protected void initFlammable() { FlammableBlockRegistry.getDefaultInstance().add(getBlock("log"), 5, 5); FlammableBlockRegistry.getDefaultInstance().add(getBlock("bark"), 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("log_stripped"), 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("bark_stripped"), 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("stripped_log"), 5, 5); + FlammableBlockRegistry.getDefaultInstance().add(getBlock("stripped_bark"), 5, 5); FlammableBlockRegistry.getDefaultInstance().add(getBlock("planks"), 5, 20); FlammableBlockRegistry.getDefaultInstance().add(getBlock("stairs"), 5, 20); From 0c73d69a93b910d558ed65d685df668c55cf8d10 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 18:35:13 +0300 Subject: [PATCH 0106/1033] Entites fixes --- src/main/java/ru/bclib/api/PostInitAPI.java | 15 ++++ .../ru/bclib/registry/BaseBlockEntities.java | 75 +++++-------------- 2 files changed, 35 insertions(+), 55 deletions(-) diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java index fe9de248..5dae1dd7 100644 --- a/src/main/java/ru/bclib/api/PostInitAPI.java +++ b/src/main/java/ru/bclib/api/PostInitAPI.java @@ -7,13 +7,16 @@ import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import net.minecraft.world.level.block.Block; +import ru.bclib.blocks.BaseBarrelBlock; import ru.bclib.blocks.BaseChestBlock; +import ru.bclib.blocks.BaseFurnaceBlock; import ru.bclib.blocks.BaseSignBlock; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.client.render.BaseChestBlockEntityRenderer; import ru.bclib.client.render.BaseSignBlockEntityRenderer; import ru.bclib.interfaces.PostInitable; import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.function.Consumer; @@ -66,5 +69,17 @@ public class PostInitAPI { if (block instanceof PostInitable) { ((PostInitable) block).postInit(); } + if (block instanceof BaseChestBlock) { + BaseBlockEntities.CHEST.registerBlock(block); + } + else if (block instanceof BaseSignBlock) { + BaseBlockEntities.SIGN.registerBlock(block); + } + else if (block instanceof BaseBarrelBlock) { + BaseBlockEntities.BARREL.registerBlock(block); + } + else if (block instanceof BaseFurnaceBlock) { + BaseBlockEntities.FURNACE.registerBlock(block); + } } } diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index 7e3c0bcb..b369eda1 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -18,16 +18,10 @@ import ru.bclib.blocks.BaseFurnaceBlock; import ru.bclib.blocks.BaseSignBlock; public class BaseBlockEntities { - public static final DynamicBlockEntityType CHEST = registerBlockEntityType(BCLib.makeID( - "chest"), BaseChestBlockEntity::new); - public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID( - "barrel"), BaseBarrelBlockEntity::new); - public static final DynamicBlockEntityType SIGN = registerBlockEntityType( - BCLib.makeID("sign"), - BaseSignBlockEntity::new - ); - public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID( - "furnace"), BaseFurnaceBlockEntity::new); + public static final DynamicBlockEntityType CHEST = registerBlockEntityType(BCLib.makeID("chest"), BaseChestBlockEntity::new); + public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID("barrel"), BaseBarrelBlockEntity::new); + public static final DynamicBlockEntityType SIGN = registerBlockEntityType(BCLib.makeID("sign"), BaseSignBlockEntity::new); + public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID("furnace"), BaseFurnaceBlockEntity::new); public static DynamicBlockEntityType registerBlockEntityType(ResourceLocation typeId, BlockEntitySupplier supplier) { return Registry.register(Registry.BLOCK_ENTITY_TYPE, typeId, new DynamicBlockEntityType<>(supplier)); @@ -36,59 +30,30 @@ public class BaseBlockEntities { public static void register() {} public static Block[] getChests() { - return BaseRegistry.getRegisteredBlocks() - .values() - .stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock) - .map(item -> ((BlockItem) item).getBlock()) - .toArray(Block[]::new); + return Registry.BLOCK + .stream() + .filter(block -> block instanceof BaseChestBlock) + .toArray(Block[]::new); } public static Block[] getBarrels() { - return BaseRegistry.getRegisteredBlocks() - .values() - .stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock) - .map(item -> ((BlockItem) item).getBlock()) - .toArray(Block[]::new); + return Registry.BLOCK + .stream() + .filter(block -> block instanceof BaseBarrelBlock) + .toArray(Block[]::new); } public static Block[] getSigns() { - return BaseRegistry.getRegisteredBlocks() - .values() - .stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock) - .map(item -> ((BlockItem) item).getBlock()) - .toArray(Block[]::new); + return Registry.BLOCK + .stream() + .filter(block -> block instanceof BaseSignBlock) + .toArray(Block[]::new); } public static Block[] getFurnaces() { - return BaseRegistry.getRegisteredBlocks() - .values() - .stream() - .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock) - .map(item -> ((BlockItem) item).getBlock()) - .toArray(Block[]::new); - } - - public static boolean registerSpecialBlock(Block block) { - if (block instanceof BaseChestBlock) { - BaseBlockEntities.CHEST.registerBlock(block); - return true; - } - if (block instanceof BaseSignBlock) { - BaseBlockEntities.SIGN.registerBlock(block); - return true; - } - if (block instanceof BaseBarrelBlock) { - BaseBlockEntities.BARREL.registerBlock(block); - return true; - } - if (block instanceof BaseFurnaceBlock) { - BaseBlockEntities.FURNACE.registerBlock(block); - return true; - } - - return false; + return Registry.BLOCK + .stream() + .filter(block -> block instanceof BaseFurnaceBlock) + .toArray(Block[]::new); } } From 0e6fa962dece9ae9129c99ce78f2056f064e6f28 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 19:24:59 +0300 Subject: [PATCH 0107/1033] Material ID --- .../complexmaterials/ComplexMaterial.java | 23 +++++++++++-------- .../complexmaterials/WoodenMaterial.java | 12 ++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index c533a27b..f67ef314 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -4,6 +4,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; @@ -19,8 +20,8 @@ import java.util.List; import java.util.Map; public abstract class ComplexMaterial { - private static final Map, List> BLOCK_ENTRIES = Maps.newHashMap(); - private static final Map, List> ITEM_ENTRIES = Maps.newHashMap(); + private static final Map> BLOCK_ENTRIES = Maps.newHashMap(); + private static final Map> ITEM_ENTRIES = Maps.newHashMap(); private static final List MATERIALS = Lists.newArrayList(); private final List defaultBlockEntries = Lists.newArrayList(); @@ -105,7 +106,7 @@ public abstract class ComplexMaterial { private Collection getBlockEntries() { List result = Lists.newArrayList(defaultBlockEntries); - List entries = BLOCK_ENTRIES.get(this.getClass()); + List entries = BLOCK_ENTRIES.get(this.getMaterialID()); if (entries != null) { result.addAll(entries); } @@ -114,7 +115,7 @@ public abstract class ComplexMaterial { private Collection getItemEntries() { List result = Lists.newArrayList(defaultItemEntries); - List entries = ITEM_ENTRIES.get(this.getClass()); + List entries = ITEM_ENTRIES.get(this.getMaterialID()); if (entries != null) { result.addAll(entries); } @@ -129,6 +130,8 @@ public abstract class ComplexMaterial { return modID; } + public abstract ResourceLocation getMaterialID(); + protected void addBlockEntry(BlockEntry entry) { defaultBlockEntries.add(entry); } @@ -137,20 +140,20 @@ public abstract class ComplexMaterial { defaultItemEntries.add(entry); } - public static void addBlockEntry(Class key, BlockEntry entry) { - List entries = BLOCK_ENTRIES.get(key); + public static void addBlockEntry(ResourceLocation materialName, BlockEntry entry) { + List entries = BLOCK_ENTRIES.get(materialName); if (entries == null) { entries = Lists.newArrayList(); - BLOCK_ENTRIES.put(key, entries); + BLOCK_ENTRIES.put(materialName, entries); } entries.add(entry); } - public static void addItemEntry(Class key, ItemEntry entry) { - List entries = ITEM_ENTRIES.get(key); + public static void addItemEntry(ResourceLocation materialName, ItemEntry entry) { + List entries = ITEM_ENTRIES.get(materialName); if (entries == null) { entries = Lists.newArrayList(); - ITEM_ENTRIES.put(key, entries); + ITEM_ENTRIES.put(materialName, entries); } entries.add(entry); } diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java index 049879b2..3c6c8070 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java @@ -1,8 +1,10 @@ package ru.bclib.complexmaterials; +import com.google.common.collect.Lists; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; +import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; @@ -11,6 +13,7 @@ import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.material.MaterialColor; +import ru.bclib.BCLib; import ru.bclib.api.TagAPI; import ru.bclib.blocks.BaseBarkBlock; import ru.bclib.blocks.BaseBarrelBlock; @@ -33,10 +36,14 @@ import ru.bclib.blocks.BaseWoodenButtonBlock; import ru.bclib.blocks.StripableBarkBlock; import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; +import ru.bclib.complexmaterials.entry.ItemEntry; import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; +import java.util.List; + public class WoodenMaterial extends ComplexMaterial { + public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); public final MaterialColor planksColor; public final MaterialColor woodColor; @@ -51,6 +58,11 @@ public class WoodenMaterial extends ComplexMaterial { return FabricBlockSettings.copyOf(Blocks.OAK_PLANKS).materialColor(planksColor); } + @Override + public ResourceLocation getMaterialID() { + return MATERIAL_ID; + } + @Override protected void initTags() { addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); From 863562ac8723f54f2a859e919bf3949c36d9ee95 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 21:56:10 +0300 Subject: [PATCH 0108/1033] Complex material javadocs --- .../complexmaterials/ComplexMaterial.java | 127 ++++++++++++++- .../complexmaterials/WoodenMaterial.java | 147 ++++++++++-------- .../java/ru/bclib/recipes/GridRecipe.java | 2 +- 3 files changed, 202 insertions(+), 74 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index f67ef314..06afd420 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -4,6 +4,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; @@ -40,6 +41,13 @@ public abstract class ComplexMaterial { MATERIALS.add(this); } + /** + * Initialize and registers all content inside material, return material itself. + * @param blocksRegistry {@link BlockRegistry} instance to add blocks in; + * @param itemsRegistry {@link ItemRegistry} instance to add items in; + * @param recipeConfig {@link PathConfig} for recipes check. + * @return {@link ComplexMaterial}. + */ public ComplexMaterial init(BlockRegistry blocksRegistry, ItemRegistry itemsRegistry, PathConfig recipeConfig) { initTags(); @@ -58,48 +66,100 @@ public abstract class ComplexMaterial { }); initRecipes(recipeConfig); - initFlammable(); + initFlammable(FlammableBlockRegistry.getDefaultInstance()); return this; } + /** + * Init default content for {@link ComplexMaterial} - blocks and items. + * @param blockSettings {@link FabricBlockSettings} default block settings for this material; + * @param itemSettings {@link FabricItemSettings} default item settings for this material. + */ protected abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings); + /** + * Init custom tags for this {@link ComplexMaterial}, not required. + */ protected void initTags() {} + /** + * Init custom recipes for this {@link ComplexMaterial}, not required. + */ protected void initRecipes(PathConfig recipeConfig) {} - protected void initFlammable() {} + /** + * Allows to add blocks into Fabric {@link FlammableBlockRegistry} for this {@link ComplexMaterial}, not required. + */ + protected void initFlammable(FlammableBlockRegistry registry) {} + /** + * Adds custom block tag for this {@link ComplexMaterial}, tag can be created with {@link ru.bclib.api.TagAPI} or you can use one of already created tags. + * @param tag {@link Tag.Named} for {@link Block} + */ protected void addBlockTag(Tag.Named tag) { - blockTags.put(tag.getName().getPath(), tag); + String key = tag.getName().getPath().replace(getBaseName() + "_", ""); + blockTags.put(key, tag); } + /** + * Adds custom iten tag for this {@link ComplexMaterial}, tag can be created with {@link ru.bclib.api.TagAPI} or you can use one of already created tags. + * @param tag {@link Tag.Named} for {@link Item} + */ protected void addItemTag(Tag.Named tag) { - itemTags.put(tag.getName().getPath(), tag); + String key = tag.getName().getPath().replace(getBaseName() + "_", ""); + itemTags.put(key, tag); } + /** + * Get custom {@link Block} {@link Tag.Named} from this {@link ComplexMaterial}. + * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. + * @return {@link Tag.Named} for {@link Block} or {@code null} if nothing is stored. + */ @Nullable public Tag.Named getBlockTag(String key) { return blockTags.get(key); } + /** + * Get custom {@link Item} {@link Tag.Named} from this {@link ComplexMaterial}. + * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. + * @return {@link Tag.Named} for {@link Item} or {@code null} if nothing is stored. + */ @Nullable public Tag.Named getItemTag(String key) { return itemTags.get(key); } + /** + * Get initiated {@link Block} from this {@link ComplexMaterial}. + * @param key {@link String} block name suffix (example: "mod:custom_log" will have a "log" suffix if "custom" is a base name of this material) + * @return {@link Block} or {@code null} if nothing is stored. + */ @Nullable public Block getBlock(String key) { return blocks.get(key); } + /** + * Get initiated {@link Item} from this {@link ComplexMaterial}. + * @param key {@link String} block name suffix (example: "mod:custom_apple" will have a "apple" suffix if "custom" is a base name of this material) + * @return {@link Item} or {@code null} if nothing is stored. + */ @Nullable public Item getItem(String key) { return items.get(key); } + /** + * Get default block settings for this material. + * @return {@link FabricBlockSettings} + */ protected abstract FabricBlockSettings getBlockSettings(); + /** + * Get default item settings for this material. + * @return {@link FabricItemSettings} + */ protected FabricItemSettings getItemSettings(ItemRegistry registry) { return registry.makeItemSettings(); } @@ -122,24 +182,71 @@ public abstract class ComplexMaterial { return result; } + /** + * Get base name of this {@link ComplexMaterial}. + * @return {@link String} name + */ public String getBaseName() { return baseName; } + /** + * Get mod ID for this {@link ComplexMaterial}. + * @return {@link String} mod ID. + */ public String getModID() { return modID; } + /** + * Get a unique {@link ResourceLocation} for each material class. + * For example WoodenComplexMaterial will have a "bclib:Wooden_Complex_Material" {@link ResourceLocation}. + * This is used to add custom entries before mods init using Fabric "preLaunch" entry point. + * @see tagBlockLog = getBlockTag(getBaseName() + "_logs"); - Tag.Named tagItemLog = getItemTag(getBaseName() + "_logs"); + Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); + Tag.Named tagItemLog = getItemTag(TAG_LOGS); addBlockEntry( - new BlockEntry("stripped_log", (complexMaterial, settings) -> { + new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { return new BaseRotatedPillarBlock(settings); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) ); addBlockEntry( - new BlockEntry("stripped_bark", (complexMaterial, settings) -> { + new BlockEntry(BLOCK_STRIPPED_BARK, (complexMaterial, settings) -> { return new BaseBarkBlock(settings); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) @@ -90,109 +114,94 @@ public class WoodenMaterial extends ComplexMaterial { ); addBlockEntry( - new BlockEntry("log", (complexMaterial, settings) -> { + new BlockEntry(BLOCK_LOG, (complexMaterial, settings) -> { return new BaseStripableLogBlock(woodColor, getBlock("stripped_log")); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) ); addBlockEntry( - new BlockEntry("bark", (complexMaterial, settings) -> { + new BlockEntry(BLOCK_BARK, (complexMaterial, settings) -> { return new StripableBarkBlock(woodColor, getBlock("stripped_bark")); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) ); - addBlockEntry(new BlockEntry("planks", (complexMaterial, settings) -> { + addBlockEntry(new BlockEntry(BLOCK_PLANKS, (complexMaterial, settings) -> { return new BaseBlock(settings); }).setBlockTags(BlockTags.PLANKS).setItemTags(ItemTags.PLANKS)); - addBlockEntry(new BlockEntry("stairs", (complexMaterial, settings) -> { - return new BaseStairsBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_STAIRS, (complexMaterial, settings) -> { + return new BaseStairsBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS).setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); - addBlockEntry(new BlockEntry("slab", (complexMaterial, settings) -> { - return new BaseSlabBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_SLAB, (complexMaterial, settings) -> { + return new BaseSlabBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS).setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); - addBlockEntry(new BlockEntry("fence", (complexMaterial, settings) -> { - return new BaseFenceBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_FENCE, (complexMaterial, settings) -> { + return new BaseFenceBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES).setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); - addBlockEntry(new BlockEntry("gate", (complexMaterial, settings) -> { - return new BaseGateBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_GATE, (complexMaterial, settings) -> { + return new BaseGateBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.FENCE_GATES)); - addBlockEntry(new BlockEntry("button", (complexMaterial, settings) -> { - return new BaseWoodenButtonBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_BUTTON, (complexMaterial, settings) -> { + return new BaseWoodenButtonBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS).setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); - addBlockEntry(new BlockEntry("plate", (complexMaterial, settings) -> { - return new WoodenPressurePlateBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_PRESSURE_PLATE, (complexMaterial, settings) -> { + return new WoodenPressurePlateBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES).setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); - addBlockEntry(new BlockEntry("trapdoor", (complexMaterial, settings) -> { - return new BaseTrapdoorBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_TRAPDOOR, (complexMaterial, settings) -> { + return new BaseTrapdoorBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS).setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); - addBlockEntry(new BlockEntry("door", (complexMaterial, settings) -> { - return new BaseDoorBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_DOOR, (complexMaterial, settings) -> { + return new BaseDoorBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS).setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); - addBlockEntry(new BlockEntry("crafting_table", (complexMaterial, settings) -> { - return new BaseCraftingTableBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { + return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); - addBlockEntry(new BlockEntry("ladder", (complexMaterial, settings) -> { - return new BaseLadderBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_LADDER, (complexMaterial, settings) -> { + return new BaseLadderBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.CLIMBABLE)); - addBlockEntry(new BlockEntry("sign", (complexMaterial, settings) -> { - return new BaseSignBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_SIGN, (complexMaterial, settings) -> { + return new BaseSignBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.SIGNS).setItemTags(ItemTags.SIGNS)); - addBlockEntry(new BlockEntry("chest", (complexMaterial, settings) -> { - return new BaseChestBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { + return new BaseChestBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); - addBlockEntry(new BlockEntry("barrel", (complexMaterial, settings) -> { - return new BaseBarrelBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { + return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); })); - addBlockEntry(new BlockEntry("bookshelf", (complexMaterial, settings) -> { - return new BaseBookshelfBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { + return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - addBlockEntry(new BlockEntry("composter", (complexMaterial, settings) -> { - return new BaseComposterBlock(getBlock("planks")); + addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { + return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); })); } - protected void initFlammable() { - FlammableBlockRegistry.getDefaultInstance().add(getBlock("log"), 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("bark"), 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("stripped_log"), 5, 5); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("stripped_bark"), 5, 5); + @Override + protected void initFlammable(FlammableBlockRegistry registry) { + getBlocks().forEach(block -> { + registry.add(block, 5, 20); + }); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("planks"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("stairs"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("slab"), 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(getBlock("fence"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("gate"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("button"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("plate"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("trapdoor"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("door"), 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(getBlock("crafting_table"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("ladder"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("sign"), 5, 20); - - FlammableBlockRegistry.getDefaultInstance().add(getBlock("chest"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("barrel"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("bookshelf"), 5, 20); - FlammableBlockRegistry.getDefaultInstance().add(getBlock("composter"), 5, 20); + registry.add(getBlock(BLOCK_LOG), 5, 5); + registry.add(getBlock(BLOCK_BARK), 5, 5); + registry.add(getBlock(BLOCK_STRIPPED_LOG), 5, 5); + registry.add(getBlock(BLOCK_STRIPPED_BARK), 5, 5); } @Override public void initRecipes(PathConfig recipeConfig) { - Block log_stripped = getBlock("stripped_log"); - Block bark_stripped = getBlock("stripped_bark"); - Block log = getBlock("log"); - Block bark = getBlock("bark"); - Block planks = getBlock("planks"); - Block stairs = getBlock("stairs"); - Block slab = getBlock("slab"); - Block fence = getBlock("fence"); + Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); + Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); + Block log = getBlock(BLOCK_LOG); + Block bark = getBlock(BLOCK_BARK); + Block planks = getBlock(BLOCK_PLANKS); + Block stairs = getBlock(BLOCK_STAIRS); + Block slab = getBlock(BLOCK_SLAB); + Block fence = getBlock(BLOCK_FENCE); Block gate = getBlock("gate"); Block button = getBlock("button"); Block pressurePlate = getBlock("plate"); diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index cc902a35..655903bf 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -45,7 +45,7 @@ public class GridRecipe { INSTANCE.materialKeys.clear(); INSTANCE.count = 1; - INSTANCE.exist = BCLRecipeManager.exists(output); + INSTANCE.exist = output != null && BCLRecipeManager.exists(output); return INSTANCE; } From 4df19c21939fdffccff82119815db2c49119d8e8 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 23 Jul 2021 22:06:37 +0300 Subject: [PATCH 0109/1033] Readme update --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 67b2b426..0521236a 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,12 @@ BCLib is a library mod for BetterX team mods, developed for Fabric, MC 1.17.1 * Block helper: * Some useful functions to operate with blocks; +### Complex Materials +* Utility classes used for mass content generation (wooden blocks, stone blocks, etc.); +* Contains a set of defined blocks, items, recipes and tags; +* Can be modified before mods startup (will add new block type for all instances in all mods); +* All inner blocks and items are Patterned (will have auto-generated models with ability to override them with resource packs or mod resources). + ### Pre-Defined Blocks and Items: * Most basic blocks from MC; * Automatic item & block model generation; From c8d9d9b252c6e63c0a2fbc06a9f35182b6d22865 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 00:59:22 +0300 Subject: [PATCH 0110/1033] Wooden material rename, javadoc fix, recipe entries --- .../complexmaterials/ComplexMaterial.java | 58 ++- ...terial.java => WoodenComplexMaterial.java} | 339 ++++++++++-------- .../complexmaterials/entry/RecipeEntry.java | 19 + .../java/ru/bclib/recipes/GridRecipe.java | 8 +- src/main/java/ru/bclib/util/TriConsumer.java | 6 + 5 files changed, 270 insertions(+), 160 deletions(-) rename src/main/java/ru/bclib/complexmaterials/{WoodenMaterial.java => WoodenComplexMaterial.java} (58%) create mode 100644 src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java create mode 100644 src/main/java/ru/bclib/util/TriConsumer.java diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 06afd420..9cfb2d2b 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.block.Block; import org.jetbrains.annotations.Nullable; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.complexmaterials.entry.ItemEntry; +import ru.bclib.complexmaterials.entry.RecipeEntry; import ru.bclib.config.PathConfig; import ru.bclib.registry.BlockRegistry; import ru.bclib.registry.ItemRegistry; @@ -21,12 +22,15 @@ import java.util.List; import java.util.Map; public abstract class ComplexMaterial { + private static final Map> RECIPE_ENTRIES = Maps.newHashMap(); private static final Map> BLOCK_ENTRIES = Maps.newHashMap(); private static final Map> ITEM_ENTRIES = Maps.newHashMap(); private static final List MATERIALS = Lists.newArrayList(); - + + private final List defaultRecipeEntries = Lists.newArrayList(); private final List defaultBlockEntries = Lists.newArrayList(); private final List defaultItemEntries = Lists.newArrayList(); + private final Map> blockTags = Maps.newHashMap(); private final Map> itemTags = Maps.newHashMap(); private final Map blocks = Maps.newHashMap(); @@ -64,8 +68,12 @@ public abstract class ComplexMaterial { Item item = entry.init(this, itemSettings, itemsRegistry); items.put(entry.getSuffix(), item); }); - - initRecipes(recipeConfig); + + initDefaultRecipes(); + getRecipeEntries().forEach(entry -> { + entry.init(this, recipeConfig); + }); + initFlammable(FlammableBlockRegistry.getDefaultInstance()); return this; } @@ -83,9 +91,9 @@ public abstract class ComplexMaterial { protected void initTags() {} /** - * Init custom recipes for this {@link ComplexMaterial}, not required. + * Init default recipes for this {@link ComplexMaterial}, not required. */ - protected void initRecipes(PathConfig recipeConfig) {} + protected void initDefaultRecipes() {} /** * Allows to add blocks into Fabric {@link FlammableBlockRegistry} for this {@link ComplexMaterial}, not required. @@ -181,6 +189,15 @@ public abstract class ComplexMaterial { } return result; } + + private Collection getRecipeEntries() { + List result = Lists.newArrayList(defaultRecipeEntries); + List entries = RECIPE_ENTRIES.get(this.getMaterialID()); + if (entries != null) { + result.addAll(entries); + } + return result; + } /** * Get base name of this {@link ComplexMaterial}. @@ -202,8 +219,8 @@ public abstract class ComplexMaterial { * Get a unique {@link ResourceLocation} for each material class. * For example WoodenComplexMaterial will have a "bclib:Wooden_Complex_Material" {@link ResourceLocation}. * This is used to add custom entries before mods init using Fabric "preLaunch" entry point. - * @see Fabric Documentation: Entrypoint */ public abstract ResourceLocation getMaterialID(); @@ -238,14 +255,22 @@ public abstract class ComplexMaterial { protected void addItemEntry(ItemEntry entry) { defaultItemEntries.add(entry); } + + /** + * Adds a default {@link RecipeEntry} to this {@link ComplexMaterial}. Used to initiate items later. + * @param entry {@link RecipeEntry} + */ + protected void addRecipeEntry(RecipeEntry entry) { + defaultRecipeEntries.add(entry); + } /** * Adds a custom {@link BlockEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. * Used to add custom entry for all instances of {@link ComplexMaterial}. * Should be called only using Fabric "preLaunch" entry point. - * @see Fabric Documentation: Entrypoint */ public static void addBlockEntry(ResourceLocation materialName, BlockEntry entry) { List entries = BLOCK_ENTRIES.get(materialName); @@ -260,9 +285,9 @@ public abstract class ComplexMaterial { * Adds a custom {@link ItemEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. * Used to add custom entry for all instances of {@link ComplexMaterial}. * Should be called only using Fabric "preLaunch" entry point. - * @see Fabric Documentation: Entrypoint */ public static void addItemEntry(ResourceLocation materialName, ItemEntry entry) { List entries = ITEM_ENTRIES.get(materialName); @@ -272,6 +297,23 @@ public abstract class ComplexMaterial { } entries.add(entry); } + + /** + * Adds a custom {@link RecipeEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. + * Used to add custom entry for all instances of {@link ComplexMaterial}. + * Should be called only using Fabric "preLaunch" entry point. + * @param materialName {@link ResourceLocation} id of {@link ComplexMaterial}; + * @param entry {@link RecipeEntry}. + * @see Fabric Documentation: Entrypoint + */ + public static void addRecipeEntry(ResourceLocation materialName, RecipeEntry entry) { + List entries = RECIPE_ENTRIES.get(materialName); + if (entries == null) { + entries = Lists.newArrayList(); + RECIPE_ENTRIES.put(materialName, entries); + } + entries.add(entry); + } /** * Get all instances of all materials. diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java similarity index 58% rename from src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java rename to src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 141e6e56..d51c8a3b 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -37,12 +37,13 @@ import ru.bclib.blocks.StripableBarkBlock; import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; import ru.bclib.complexmaterials.entry.ItemEntry; +import ru.bclib.complexmaterials.entry.RecipeEntry; import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; import java.util.List; -public class WoodenMaterial extends ComplexMaterial { +public class WoodenComplexMaterial extends ComplexMaterial { public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); public static final String BLOCK_CRAFTING_TABLE = "crafting_table"; @@ -71,7 +72,7 @@ public class WoodenMaterial extends ComplexMaterial { public final MaterialColor planksColor; public final MaterialColor woodColor; - public WoodenMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor) { + public WoodenComplexMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor) { super(modID, baseName); this.planksColor = planksColor; this.woodColor = woodColor; @@ -193,154 +194,192 @@ public class WoodenMaterial extends ComplexMaterial { } @Override - public void initRecipes(PathConfig recipeConfig) { - Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); - Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); - Block log = getBlock(BLOCK_LOG); - Block bark = getBlock(BLOCK_BARK); + public void initDefaultRecipes() { Block planks = getBlock(BLOCK_PLANKS); - Block stairs = getBlock(BLOCK_STAIRS); - Block slab = getBlock(BLOCK_SLAB); - Block fence = getBlock(BLOCK_FENCE); - Block gate = getBlock("gate"); - Block button = getBlock("button"); - Block pressurePlate = getBlock("plate"); - Block trapdoor = getBlock("trapdoor"); - Block door = getBlock("door"); - Block craftingTable = getBlock("crafting_table"); - Block ladder = getBlock("ladder"); - Block sign = getBlock("sign"); - Block chest = getBlock("chest"); - Block barrel = getBlock("barrel"); - Block shelf = getBlock("bookshelf"); - Block composter = getBlock("composter"); - - GridRecipe.make(getModID(), getBaseName() + "_planks", planks) - .checkConfig(recipeConfig) - .setOutputCount(4) - .setList("#") - .addMaterial('#', log, bark, log_stripped, bark_stripped) - .setGroup("end_planks") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_stairs", stairs) - .checkConfig(recipeConfig) - .setOutputCount(4) - .setShape("# ", "## ", "###") - .addMaterial('#', planks) - .setGroup("end_planks_stairs") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_slab", slab) - .checkConfig(recipeConfig) - .setOutputCount(6) - .setShape("###") - .addMaterial('#', planks) - .setGroup("end_planks_slabs") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_fence", fence) - .checkConfig(recipeConfig) - .setOutputCount(3) - .setShape("#I#", "#I#") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup("end_planks_fences") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_gate", gate) - .checkConfig(recipeConfig) - .setShape("I#I", "I#I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup("end_planks_gates") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_button", button) - .checkConfig(recipeConfig) - .setList("#") - .addMaterial('#', planks) - .setGroup("end_planks_buttons") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_pressure_plate", pressurePlate) - .checkConfig(recipeConfig) - .setShape("##") - .addMaterial('#', planks) - .setGroup("end_planks_plates") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_trapdoor", trapdoor) - .checkConfig(recipeConfig) - .setOutputCount(2) - .setShape("###", "###") - .addMaterial('#', planks) - .setGroup("end_trapdoors") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_door", door) - .checkConfig(recipeConfig) - .setOutputCount(3) - .setShape("##", "##", "##") - .addMaterial('#', planks) - .setGroup("end_doors") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_crafting_table", craftingTable) - .checkConfig(recipeConfig) - .setShape("##", "##") - .addMaterial('#', planks) - .setGroup("end_tables") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_ladder", ladder) - .checkConfig(recipeConfig) - .setOutputCount(3) - .setShape("I I", "I#I", "I I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup("end_ladders") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_sign", sign) - .checkConfig(recipeConfig) - .setOutputCount(3) - .setShape("###", "###", " I ") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup("end_signs") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_chest", chest) - .checkConfig(recipeConfig) - .setShape("###", "# #", "###") - .addMaterial('#', planks) - .setGroup("end_chests") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_barrel", barrel) - .checkConfig(recipeConfig) - .setShape("#S#", "# #", "#S#") - .addMaterial('#', planks) - .addMaterial('S', slab) - .setGroup("end_barrels") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_bookshelf", shelf) - .checkConfig(recipeConfig) - .setShape("###", "PPP", "###") - .addMaterial('#', planks) - .addMaterial('P', Items.BOOK) - .setGroup("end_BLOCK_BOOKSHELVES") - .build(); - GridRecipe.make(getModID(), getBaseName() + "_bark", bark) - .checkConfig(recipeConfig) - .setShape("##", "##") - .addMaterial('#', log) - .setOutputCount(3) - .build(); - GridRecipe.make(getModID(), getBaseName() + "_log", log) - .checkConfig(recipeConfig) - .setShape("##", "##") - .addMaterial('#', bark) - .setOutputCount(3) - .build(); - GridRecipe.make(getModID(), getBaseName() + "_composter", composter) - .checkConfig(recipeConfig) - .setShape("# #", "# #", "###") - .addMaterial('#', slab) - .build(); - GridRecipe.make(getModID(), getBaseName() + "_shulker", Items.SHULKER_BOX) - .checkConfig(recipeConfig) - .setShape("S", "#", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('#', chest) - .build(); + addRecipeEntry(new RecipeEntry("planks", (material, config, id) -> { + Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); + Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); + Block log = getBlock(BLOCK_LOG); + Block bark = getBlock(BLOCK_BARK); + GridRecipe.make(id, planks) + .checkConfig(config) + .setOutputCount(4) + .setList("#") + .addMaterial('#', log, bark, log_stripped, bark_stripped) + .setGroup("end_planks") + .build(); + })); + addRecipeEntry(new RecipeEntry("stairs", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STAIRS)) + .checkConfig(config) + .setOutputCount(4) + .setShape("# ", "## ", "###") + .addMaterial('#', planks) + .setGroup("end_planks_stairs") + .build(); + })); + addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_SLAB)) + .checkConfig(config) + .setOutputCount(6) + .setShape("###") + .addMaterial('#', planks) + .setGroup("end_planks_slabs") + .build(); + })); + addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_FENCE)) + .checkConfig(config) + .setOutputCount(3) + .setShape("#I#", "#I#") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_planks_fences") + .build(); + })); + addRecipeEntry(new RecipeEntry("gate", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_GATE)) + .checkConfig(config) + .setShape("I#I", "I#I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_planks_gates") + .build(); + })); + addRecipeEntry(new RecipeEntry("button", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BUTTON)) + .checkConfig(config) + .setList("#") + .addMaterial('#', planks) + .setGroup("end_planks_buttons") + .build(); + })); + addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_PRESSURE_PLATE)) + .checkConfig(config) + .setShape("##") + .addMaterial('#', planks) + .setGroup("end_planks_plates") + .build(); + })); + addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_TRAPDOOR)) + .checkConfig(config) + .setOutputCount(2) + .setShape("###", "###") + .addMaterial('#', planks) + .setGroup("end_trapdoors") + .build(); + })); + addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_DOOR)) + .checkConfig(config) + .setOutputCount(3) + .setShape("##", "##", "##") + .addMaterial('#', planks) + .setGroup("end_doors") + .build(); + })); + addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_CRAFTING_TABLE)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', planks) + .setGroup("end_tables") + .build(); + })); + addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_LADDER)) + .checkConfig(config) + .setOutputCount(3) + .setShape("I I", "I#I", "I I") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_ladders") + .build(); + })); + addRecipeEntry(new RecipeEntry("sign", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_SIGN)) + .checkConfig(config) + .setOutputCount(3) + .setShape("###", "###", " I ") + .addMaterial('#', planks) + .addMaterial('I', Items.STICK) + .setGroup("end_signs") + .build(); + })); + addRecipeEntry(new RecipeEntry("chest", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_CHEST)) + .checkConfig(config) + .setShape("###", "# #", "###") + .addMaterial('#', planks) + .setGroup("end_chests") + .build(); + })); + addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BARREL)) + .checkConfig(config) + .setShape("#S#", "# #", "#S#") + .addMaterial('#', planks) + .addMaterial('S', getBlock(BLOCK_SLAB)) + .setGroup("end_barrels") + .build(); + })); + addRecipeEntry(new RecipeEntry("bookshelf", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BOOKSHELF)) + .checkConfig(config) + .setShape("###", "PPP", "###") + .addMaterial('#', planks) + .addMaterial('P', Items.BOOK) + .setGroup("end_bookshelves") + .build(); + })); + addRecipeEntry(new RecipeEntry("bark", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_BARK)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_LOG)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("log", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_LOG)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_BARK)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("stripped_bark", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STRIPPED_BARK)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_STRIPPED_LOG)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("stripped_log", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_STRIPPED_LOG)) + .checkConfig(config) + .setShape("##", "##") + .addMaterial('#', getBlock(BLOCK_STRIPPED_BARK)) + .setOutputCount(3) + .build(); + })); + addRecipeEntry(new RecipeEntry("composter", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) + .checkConfig(config) + .setShape("# #", "# #", "###") + .addMaterial('#', getBlock(BLOCK_SLAB)) + .build(); + })); + addRecipeEntry(new RecipeEntry("shulker", (material, config, id) -> { + GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) + .checkConfig(config) + .setShape("S", "#", "S") + .addMaterial('S', Items.SHULKER_SHELL) + .addMaterial('#', getBlock(BLOCK_CHEST)) + .build(); + })); } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java new file mode 100644 index 00000000..d91a7ca8 --- /dev/null +++ b/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java @@ -0,0 +1,19 @@ +package ru.bclib.complexmaterials.entry; + +import net.minecraft.resources.ResourceLocation; +import ru.bclib.complexmaterials.ComplexMaterial; +import ru.bclib.config.PathConfig; +import ru.bclib.util.TriConsumer; + +public class RecipeEntry extends ComplexMaterialEntry { + final TriConsumer initFunction; + + public RecipeEntry(String suffix, TriConsumer initFunction) { + super(suffix); + this.initFunction = initFunction; + } + + public void init(ComplexMaterial material, PathConfig recipeConfig) { + initFunction.accept(material, recipeConfig, getLocation(material.getModID(), material.getBaseName())); + } +} diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index 655903bf..71a6bbc9 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -33,9 +33,13 @@ public class GridRecipe { private boolean exist = true; private GridRecipe() {} - + public static GridRecipe make(String modID, String name, ItemLike output) { - INSTANCE.id = new ResourceLocation(modID, name); + return make(new ResourceLocation(modID, name), output); + } + + public static GridRecipe make(ResourceLocation id, ItemLike output) { + INSTANCE.id = id; INSTANCE.output = output; INSTANCE.group = ""; diff --git a/src/main/java/ru/bclib/util/TriConsumer.java b/src/main/java/ru/bclib/util/TriConsumer.java new file mode 100644 index 00000000..6e5ac17c --- /dev/null +++ b/src/main/java/ru/bclib/util/TriConsumer.java @@ -0,0 +1,6 @@ +package ru.bclib.util; + +@FunctionalInterface +public interface TriConsumer { + void accept(A a, B b, C c); +} From 099ecf68b682fd37ecb2091ed87b3ff08148a145 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 17:05:03 +0300 Subject: [PATCH 0111/1033] OBJ model prototype --- .../ru/bclib/client/models/OBJBlockModel.java | 241 ++++++++++++++++++ .../ru/bclib/client/models/UnbakedQuad.java | 35 +++ src/main/resources/fabric.mod.json | 2 +- 3 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/bclib/client/models/OBJBlockModel.java create mode 100644 src/main/java/ru/bclib/client/models/UnbakedQuad.java diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java new file mode 100644 index 00000000..b4a8fd20 --- /dev/null +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -0,0 +1,241 @@ +package ru.bclib.client.models; + +import com.google.common.collect.Lists; +import com.mojang.datafixers.util.Pair; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemOverrides; +import net.minecraft.client.renderer.block.model.ItemTransforms; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.client.resources.model.Material; +import net.minecraft.client.resources.model.ModelBakery; +import net.minecraft.client.resources.model.ModelState; +import net.minecraft.client.resources.model.UnbakedModel; +import net.minecraft.core.Direction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.util.Mth; +import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.function.Function; + +public class OBJBlockModel implements UnbakedModel, BakedModel { + private static final byte[] QUAD_INDEXES = new byte[] {0, 1, 2, 0, 2, 3}; + + protected TextureAtlasSprite[] sprites; + protected TextureAtlasSprite particles; + protected ItemTransforms transforms; + protected ItemOverrides overrides; + + protected List quadsUnbaked; + protected Material particleMaterial; + protected List materials; + protected List quads; + + public OBJBlockModel(ResourceLocation location, ResourceLocation particleTextureID, ResourceLocation... textureIDs) { + transforms = ItemTransforms.NO_TRANSFORMS; + overrides = ItemOverrides.EMPTY; + + quadsUnbaked = Lists.newArrayList(); + materials = Lists.newArrayList(); + + loadModel(location, textureIDs); + + quads = new ArrayList<>(quadsUnbaked.size()); + particleMaterial = new Material(TextureAtlas.LOCATION_BLOCKS, particleTextureID); + sprites = new TextureAtlasSprite[materials.size()]; + } + + // UnbakedModel // + + @Override + public Collection getDependencies() { + return Collections.emptyList(); + } + + @Override + public Collection getMaterials(Function function, Set> set) { + return materials; + } + + @Nullable + @Override + public BakedModel bake(ModelBakery modelBakery, Function textureGetter, ModelState modelState, ResourceLocation resourceLocation) { + for (int i = 0; i < sprites.length; i++) { + sprites[i] = textureGetter.apply(materials.get(i)); + } + particles = textureGetter.apply(particleMaterial); + quads.clear(); + quadsUnbaked.forEach(quad -> quads.add(quad.bake(sprites))); + return this; + } + + // Baked Model // + + @Override + public List getQuads(@Nullable BlockState blockState, @Nullable Direction direction, Random random) { + return direction == null ? quads : Collections.emptyList(); + } + + @Override + public boolean useAmbientOcclusion() { + return true; + } + + @Override + public boolean isGui3d() { + return true; + } + + @Override + public boolean usesBlockLight() { + return true; + } + + @Override + public boolean isCustomRenderer() { + return false; + } + + @Override + public TextureAtlasSprite getParticleIcon() { + return particles; + } + + @Override + public ItemTransforms getTransforms() { + return transforms; + } + + @Override + public ItemOverrides getOverrides() { + return overrides; + } + + private Resource getResource(ResourceLocation location) { + Resource resource = null; + try { + resource = Minecraft.getInstance().getResourceManager().getResource(location); + } + catch (IOException e) { + e.printStackTrace(); + if (resource != null) { + try { + resource.close(); + } + catch (IOException ioException) { + ioException.printStackTrace(); + } + resource = null; + } + } + return resource; + } + + private void loadModel(ResourceLocation location, ResourceLocation[] textureIDs) { + Resource resource = getResource(location); + if (resource == null) { + return; + } + InputStream input = resource.getInputStream(); + + List vertecies = new ArrayList<>(12); + List uvs = new ArrayList<>(8); + + List vertexIndex = new ArrayList<>(4); + List uvIndex = new ArrayList<>(4); + + byte materialIndex = 0; + int vertCount = 0; + + try { + InputStreamReader streamReader = new InputStreamReader(input); + BufferedReader reader = new BufferedReader(streamReader); + String string; + + while ((string = reader.readLine()) != null) { + if ((string.startsWith("usemtl") || string.startsWith("g")) && vertCount != vertecies.size()) { + vertCount = vertecies.size(); + materialIndex++; + } + else if (string.startsWith("vt")) { + String[] uv = string.split(" "); + uvs.add(Float.parseFloat(uv[1])); + uvs.add(Float.parseFloat(uv[2])); + } + else if (string.startsWith("v")) { + String[] vert = string.split(" "); + for (int i = 1; i < 4; i++) { + vertecies.add(Float.parseFloat(vert[i])); + } + } + else if (string.startsWith("f")) { + String[] members = string.split(" "); + if (members.length != 5) { + System.out.println("Only quads in OBJ are supported! Model [" + location + "] has n-gons or triangles!"); + continue; + } + vertexIndex.clear(); + uvIndex.clear(); + + for (int i = 1; i < members.length; i++) { + String member = members[i]; + + if (member.contains("/")) { + String[] sub = member.split("/"); + vertexIndex.add(Integer.parseInt(sub[0]) - 1); // Vertex + uvIndex.add(Integer.parseInt(sub[1]) - 1); // UV + } + else { + vertexIndex.add(Integer.parseInt(member) - 1); // Vertex + } + } + + boolean hasUV = !uvIndex.isEmpty(); + UnbakedQuad quad = new UnbakedQuad(); + for (int i = 0; i < 4; i++) { + int index = vertexIndex.get(i) * 3; + int quadIndex = i * 5; + quad.addData(quadIndex++, vertecies.get(index++)); // X + quad.addData(quadIndex++, vertecies.get(index++)); // Y + quad.addData(quadIndex++, vertecies.get(index)); // Z + if (hasUV) { + index = uvIndex.get(i) * 2; + quad.addData(quadIndex++, uvs.get(index++) * 16F); // U + quad.addData(quadIndex, (1 - uvs.get(index)) * 16F); // V + } + } + quad.setSpriteIndex(materialIndex); + quadsUnbaked.add(quad); + } + } + + reader.close(); + streamReader.close(); + input.close(); + resource.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + + int maxID = textureIDs.length - 1; + for (int i = 0; i <= materialIndex; i++) { + int index = Math.min(materialIndex, maxID); + materials.add(new Material(TextureAtlas.LOCATION_BLOCKS, textureIDs[index])); + } + } +} diff --git a/src/main/java/ru/bclib/client/models/UnbakedQuad.java b/src/main/java/ru/bclib/client/models/UnbakedQuad.java new file mode 100644 index 00000000..60cd7561 --- /dev/null +++ b/src/main/java/ru/bclib/client/models/UnbakedQuad.java @@ -0,0 +1,35 @@ +package ru.bclib.client.models; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.core.Direction; + +public class UnbakedQuad { + float[] data = new float[20]; // 4 points with 3 positions and 2 uvs, 4 * (3 + 2) + int spriteIndex; + + public void addData(int index, float value) { + data[index] = value; + } + + public void setSpriteIndex(int index) { + spriteIndex = index; + } + + public BakedQuad bake(TextureAtlasSprite[] sprites) { + TextureAtlasSprite sprite = sprites[spriteIndex]; + int[] vertexData = new int[32]; + for (int i = 0; i < 4; i++) { + int index = i << 3; + int dataIndex = i * 5; + vertexData[index] = Float.floatToIntBits(data[dataIndex++]); // X + vertexData[index | 1] = Float.floatToIntBits(data[dataIndex++]); // Y + vertexData[index | 2] = Float.floatToIntBits(data[dataIndex++]); // Z + vertexData[index | 3] = -1; // Unknown constant + vertexData[index | 4] = Float.floatToIntBits(sprite.getU(data[dataIndex++])); // U + vertexData[index | 5] = Float.floatToIntBits(sprite.getV(data[dataIndex])); // V + } + // vertices, tint index, direction, sprite, shade + return new BakedQuad(vertexData, 0, Direction.UP, sprites[spriteIndex], true); + } +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 01ea9f48..2a83ad36 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,6 +34,6 @@ "depends": { "fabricloader": ">=0.11.6", "fabric": ">=0.36.0", - "minecraft": ">=1.17" + "minecraft": ">=1.17.1" } } From ca9e32ae53ba39856e426422bb555dbb0dbd5ff2 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 18:20:29 +0300 Subject: [PATCH 0112/1033] OBJ model enhancements and builder --- .../ru/bclib/client/models/OBJBlockModel.java | 98 +++++++++++++++---- .../bclib/client/models/OBJModelBuilder.java | 95 ++++++++++++++++++ .../ru/bclib/client/models/UnbakedQuad.java | 29 +++++- 3 files changed, 199 insertions(+), 23 deletions(-) create mode 100644 src/main/java/ru/bclib/client/models/OBJModelBuilder.java diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java index b4a8fd20..585040e9 100644 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -1,7 +1,11 @@ package ru.bclib.client.models; import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import com.mojang.datafixers.util.Pair; +import com.mojang.math.Vector3f; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemOverrides; @@ -19,6 +23,8 @@ import net.minecraft.server.packs.resources.Resource; import net.minecraft.util.Mth; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; +import ru.bclib.util.BlocksHelper; +import ru.bclib.util.MHelper; import java.io.BufferedReader; import java.io.IOException; @@ -28,35 +34,42 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Random; import java.util.Set; import java.util.function.Function; +@Environment(EnvType.CLIENT) public class OBJBlockModel implements UnbakedModel, BakedModel { - private static final byte[] QUAD_INDEXES = new byte[] {0, 1, 2, 0, 2, 3}; + private static final Vector3f[] POSITIONS = new Vector3f[] { new Vector3f(), new Vector3f(), new Vector3f() }; + + protected final Map> quadsUnbakedMap = Maps.newHashMap(); + protected final Map> quadsBakedMap = Maps.newHashMap(); + protected final List quadsUnbaked = Lists.newArrayList(); + protected final List quadsBaked = Lists.newArrayList(); protected TextureAtlasSprite[] sprites; - protected TextureAtlasSprite particles; protected ItemTransforms transforms; protected ItemOverrides overrides; - protected List quadsUnbaked; - protected Material particleMaterial; protected List materials; - protected List quads; + protected boolean useCulling; + protected boolean useShading; + protected byte particleIndex; - public OBJBlockModel(ResourceLocation location, ResourceLocation particleTextureID, ResourceLocation... textureIDs) { + public OBJBlockModel(ResourceLocation location, boolean useCulling, boolean useShading, byte particleIndex, ResourceLocation... textureIDs) { + for (Direction dir: BlocksHelper.DIRECTIONS) { + quadsUnbakedMap.put(dir, Lists.newArrayList()); + quadsBakedMap.put(dir, Lists.newArrayList()); + } transforms = ItemTransforms.NO_TRANSFORMS; overrides = ItemOverrides.EMPTY; - - quadsUnbaked = Lists.newArrayList(); - materials = Lists.newArrayList(); - - loadModel(location, textureIDs); - - quads = new ArrayList<>(quadsUnbaked.size()); - particleMaterial = new Material(TextureAtlas.LOCATION_BLOCKS, particleTextureID); + materials = new ArrayList<>(textureIDs.length + 1); sprites = new TextureAtlasSprite[materials.size()]; + this.particleIndex = particleIndex; + this.useCulling = useCulling; + this.useShading = useShading; + loadModel(location, textureIDs); } // UnbakedModel // @@ -77,9 +90,14 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { for (int i = 0; i < sprites.length; i++) { sprites[i] = textureGetter.apply(materials.get(i)); } - particles = textureGetter.apply(particleMaterial); - quads.clear(); - quadsUnbaked.forEach(quad -> quads.add(quad.bake(sprites))); + quadsBaked.clear(); + quadsUnbaked.forEach(quad -> quadsBaked.add(quad.bake(sprites))); + for (Direction dir: BlocksHelper.DIRECTIONS) { + List unbaked = quadsUnbakedMap.get(dir); + List baked = quadsBakedMap.get(dir); + baked.clear(); + unbaked.forEach(quad -> baked.add(quad.bake(sprites))); + } return this; } @@ -87,7 +105,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { @Override public List getQuads(@Nullable BlockState blockState, @Nullable Direction direction, Random random) { - return direction == null ? quads : Collections.emptyList(); + return direction == null ? quadsBaked : quadsBakedMap.get(direction); } @Override @@ -112,7 +130,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { @Override public TextureAtlasSprite getParticleIcon() { - return particles; + return sprites[particleIndex]; } @Override @@ -219,7 +237,18 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { } } quad.setSpriteIndex(materialIndex); - quadsUnbaked.add(quad); + if (useShading) { + Direction dir = getNormalDirection(quad); + quad.setDirection(dir); + quad.setShading(true); + } + if (useCulling) { + Direction dir = getCullingDirection(quad); + quadsUnbakedMap.get(dir).add(quad); + } + else { + quadsUnbaked.add(quad); + } } } @@ -238,4 +267,33 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { materials.add(new Material(TextureAtlas.LOCATION_BLOCKS, textureIDs[index])); } } + + private Direction getNormalDirection(UnbakedQuad quad) { + Vector3f pos = quad.getPos(0, POSITIONS[0]); + Vector3f dirA = quad.getPos(1, POSITIONS[1]); + Vector3f dirB = quad.getPos(2, POSITIONS[2]); + dirA.sub(pos); + dirB.sub(pos); + pos = MHelper.cross(dirA, dirB); + return Direction.getNearest(pos.x(), pos.y(), pos.z()); + } + + @Nullable + private Direction getCullingDirection(UnbakedQuad quad) { + Direction dir = null; + for (int i = 0; i < 4; i++) { + Vector3f pos = quad.getPos(i, POSITIONS[0]); + if (pos.x() < 1 || pos.x() > 0 || pos.y() < 1 || pos.y() > 0 || pos.z() < 1 || pos.z() > 0) { + return null; + } + Direction newDir = Direction.getNearest(pos.x(), pos.y(), pos.z()); + if (dir == null) { + dir = newDir; + } + else if (newDir != dir) { + return null; + } + } + return dir; + } } diff --git a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java new file mode 100644 index 00000000..99b7c8de --- /dev/null +++ b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java @@ -0,0 +1,95 @@ +package ru.bclib.client.models; + +import com.google.common.collect.Lists; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.resources.ResourceLocation; + +import java.util.List; + +@Environment(EnvType.CLIENT) +public class OBJModelBuilder { + private static final OBJModelBuilder INSTANCE = new OBJModelBuilder(); + private final List textures = Lists.newArrayList(); + private ResourceLocation modelLocation; + private ResourceLocation particles; + private boolean useCulling; + private boolean useShading; + + private OBJModelBuilder() {} + + /** + * Start a new bodel building process, clears data of previous builder. + * @return {@link OBJModelBuilder} instance. + */ + public static OBJModelBuilder start(ResourceLocation modelLocation) { + INSTANCE.modelLocation = modelLocation; + INSTANCE.useCulling = true; + INSTANCE.useShading = true; + INSTANCE.particles = null; + INSTANCE.textures.clear(); + return INSTANCE; + } + + /** + * Add texture to the model. All textures have indexes with same order as in source OBJ model. + * @param texture {@link ResourceLocation} texture ID. + * @return this {@link OBJModelBuilder}. + */ + public OBJModelBuilder addTexture(ResourceLocation texture) { + textures.add(texture); + return this; + } + + /** + * Culling used to remove block faces if they are on block faces or outside of the block to reduce faces count in rendering. + * Opaque blocks shoud have this as true to reduce geometry issues, block like plants should have this as false. + * Default value is {@code true}. + * @param useCulling {@link Boolean}. + * @return this {@link OBJModelBuilder}. + */ + public OBJModelBuilder useCulling(boolean useCulling) { + this.useCulling = useCulling; + return this; + } + + /** + * Shading tints block faces in shades of gray to immitate volume in MC rendering. + * Blocks like plants don't have shading, most full opaque blocks - have. + * Default value is {@code true}. + * @param useShading {@link Boolean}. + * @return this {@link OBJModelBuilder}. + */ + public OBJModelBuilder useShading(boolean useShading) { + this.useShading = useShading; + return this; + } + + /** + * Set particle texture for this model. + * Not required, if texture is not selected the first texture will be used instead of it. + * @param texture {@link ResourceLocation} texture ID. + * @return this {@link OBJModelBuilder}. + */ + public OBJModelBuilder setParticlesTexture(ResourceLocation texture) { + this.particles = texture; + return this; + } + + /** + * Builds model from all required data. + * @return {@link OBJBlockModel}. + */ + public OBJBlockModel build() { + byte particleIndex = 0; + if (particles != null) { + particleIndex = (byte) textures.indexOf(particles); + if (particleIndex < 0) { + particleIndex = (byte) textures.size(); + textures.add(particles); + } + } + ResourceLocation[] sprites = textures.toArray(new ResourceLocation[textures.size()]); + return new OBJBlockModel(modelLocation, useCulling, useShading, particleIndex, sprites); + } +} diff --git a/src/main/java/ru/bclib/client/models/UnbakedQuad.java b/src/main/java/ru/bclib/client/models/UnbakedQuad.java index 60cd7561..7df9250c 100644 --- a/src/main/java/ru/bclib/client/models/UnbakedQuad.java +++ b/src/main/java/ru/bclib/client/models/UnbakedQuad.java @@ -1,12 +1,18 @@ package ru.bclib.client.models; +import com.mojang.math.Vector3f; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +@Environment(EnvType.CLIENT) public class UnbakedQuad { - float[] data = new float[20]; // 4 points with 3 positions and 2 uvs, 4 * (3 + 2) - int spriteIndex; + private float[] data = new float[20]; // 4 points with 3 positions and 2 uvs, 4 * (3 + 2) + private Direction dir = Direction.UP; + private boolean useShading = false; + private int spriteIndex; public void addData(int index, float value) { data[index] = value; @@ -16,6 +22,23 @@ public class UnbakedQuad { spriteIndex = index; } + public void setDirection(Direction dir) { + this.dir = dir; + } + + public void setShading(boolean useShading) { + this.useShading = useShading; + } + + public Vector3f getPos(int index, Vector3f result) { + int dataIndex = index * 5; + float x = data[dataIndex++]; + float y = data[dataIndex++]; + float z = data[dataIndex]; + result.set(x, y, z); + return result; + } + public BakedQuad bake(TextureAtlasSprite[] sprites) { TextureAtlasSprite sprite = sprites[spriteIndex]; int[] vertexData = new int[32]; @@ -30,6 +53,6 @@ public class UnbakedQuad { vertexData[index | 5] = Float.floatToIntBits(sprite.getV(data[dataIndex])); // V } // vertices, tint index, direction, sprite, shade - return new BakedQuad(vertexData, 0, Direction.UP, sprites[spriteIndex], true); + return new BakedQuad(vertexData, 0, dir, sprites[spriteIndex], useShading); } } From 5efab225618fc1ec93c9d5986271ea3f718f1d49 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 18:52:22 +0300 Subject: [PATCH 0113/1033] Culling fix & null pointer fix --- .../ru/bclib/client/models/OBJBlockModel.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java index 585040e9..f636ff65 100644 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -43,8 +43,8 @@ import java.util.function.Function; public class OBJBlockModel implements UnbakedModel, BakedModel { private static final Vector3f[] POSITIONS = new Vector3f[] { new Vector3f(), new Vector3f(), new Vector3f() }; - protected final Map> quadsUnbakedMap = Maps.newHashMap(); - protected final Map> quadsBakedMap = Maps.newHashMap(); + protected final Map> quadsUnbakedMap = Maps.newEnumMap(Direction.class); + protected final Map> quadsBakedMap = Maps.newEnumMap(Direction.class); protected final List quadsUnbaked = Lists.newArrayList(); protected final List quadsBaked = Lists.newArrayList(); @@ -65,7 +65,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { transforms = ItemTransforms.NO_TRANSFORMS; overrides = ItemOverrides.EMPTY; materials = new ArrayList<>(textureIDs.length + 1); - sprites = new TextureAtlasSprite[materials.size()]; + sprites = new TextureAtlasSprite[textureIDs.length + 1]; this.particleIndex = particleIndex; this.useCulling = useCulling; this.useShading = useShading; @@ -244,7 +244,12 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { } if (useCulling) { Direction dir = getCullingDirection(quad); - quadsUnbakedMap.get(dir).add(quad); + if (dir == null) { + quadsUnbaked.add(quad); + } + else { + quadsUnbakedMap.get(dir).add(quad); + } } else { quadsUnbaked.add(quad); @@ -283,10 +288,10 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { Direction dir = null; for (int i = 0; i < 4; i++) { Vector3f pos = quad.getPos(i, POSITIONS[0]); - if (pos.x() < 1 || pos.x() > 0 || pos.y() < 1 || pos.y() > 0 || pos.z() < 1 || pos.z() > 0) { + if (pos.x() < 1 && pos.x() > 0 && pos.y() < 1 && pos.y() > 0 && pos.z() < 1 && pos.z() > 0) { return null; } - Direction newDir = Direction.getNearest(pos.x(), pos.y(), pos.z()); + Direction newDir = Direction.getNearest(pos.x() - 0.5F, pos.y() - 0.5F, pos.z() - 0.5F); if (dir == null) { dir = newDir; } From 4a6d618598e04b32441c140e5c245eec252207f6 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 20:02:25 +0300 Subject: [PATCH 0114/1033] OBJ model offset --- .../java/ru/bclib/client/models/OBJBlockModel.java | 12 ++++++------ .../java/ru/bclib/client/models/OBJModelBuilder.java | 10 +++++++++- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java index f636ff65..ea090342 100644 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -57,7 +57,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { protected boolean useShading; protected byte particleIndex; - public OBJBlockModel(ResourceLocation location, boolean useCulling, boolean useShading, byte particleIndex, ResourceLocation... textureIDs) { + public OBJBlockModel(ResourceLocation location, Vector3f offset, boolean useCulling, boolean useShading, byte particleIndex, ResourceLocation... textureIDs) { for (Direction dir: BlocksHelper.DIRECTIONS) { quadsUnbakedMap.put(dir, Lists.newArrayList()); quadsBakedMap.put(dir, Lists.newArrayList()); @@ -69,7 +69,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { this.particleIndex = particleIndex; this.useCulling = useCulling; this.useShading = useShading; - loadModel(location, textureIDs); + loadModel(location, textureIDs, offset); } // UnbakedModel // @@ -163,7 +163,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { return resource; } - private void loadModel(ResourceLocation location, ResourceLocation[] textureIDs) { + private void loadModel(ResourceLocation location, ResourceLocation[] textureIDs, Vector3f offset) { Resource resource = getResource(location); if (resource == null) { return; @@ -227,9 +227,9 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { for (int i = 0; i < 4; i++) { int index = vertexIndex.get(i) * 3; int quadIndex = i * 5; - quad.addData(quadIndex++, vertecies.get(index++)); // X - quad.addData(quadIndex++, vertecies.get(index++)); // Y - quad.addData(quadIndex++, vertecies.get(index)); // Z + quad.addData(quadIndex++, vertecies.get(index++) + offset.x()); // X + quad.addData(quadIndex++, vertecies.get(index++) + offset.y()); // Y + quad.addData(quadIndex++, vertecies.get(index) + offset.z()); // Z if (hasUV) { index = uvIndex.get(i) * 2; quad.addData(quadIndex++, uvs.get(index++) * 16F); // U diff --git a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java index 99b7c8de..56dbcbd0 100644 --- a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java +++ b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java @@ -1,6 +1,7 @@ package ru.bclib.client.models; import com.google.common.collect.Lists; +import com.mojang.math.Vector3f; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.resources.ResourceLocation; @@ -15,6 +16,7 @@ public class OBJModelBuilder { private ResourceLocation particles; private boolean useCulling; private boolean useShading; + private Vector3f offset; private OBJModelBuilder() {} @@ -24,6 +26,7 @@ public class OBJModelBuilder { */ public static OBJModelBuilder start(ResourceLocation modelLocation) { INSTANCE.modelLocation = modelLocation; + INSTANCE.offset.set(0, 0, 0); INSTANCE.useCulling = true; INSTANCE.useShading = true; INSTANCE.particles = null; @@ -76,6 +79,11 @@ public class OBJModelBuilder { return this; } + public OBJModelBuilder setOffset(float x, float y, float z) { + this.offset.set(x, y, z); + return this; + } + /** * Builds model from all required data. * @return {@link OBJBlockModel}. @@ -90,6 +98,6 @@ public class OBJModelBuilder { } } ResourceLocation[] sprites = textures.toArray(new ResourceLocation[textures.size()]); - return new OBJBlockModel(modelLocation, useCulling, useShading, particleIndex, sprites); + return new OBJBlockModel(modelLocation, offset, useCulling, useShading, particleIndex, sprites); } } From d3504250491eae34ed8bec66deab61d7a40b7246 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 20:03:11 +0300 Subject: [PATCH 0115/1033] Small fix --- src/main/java/ru/bclib/client/models/OBJModelBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java index 56dbcbd0..7316985b 100644 --- a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java +++ b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java @@ -12,11 +12,11 @@ import java.util.List; public class OBJModelBuilder { private static final OBJModelBuilder INSTANCE = new OBJModelBuilder(); private final List textures = Lists.newArrayList(); + private Vector3f offset = new Vector3f(); private ResourceLocation modelLocation; private ResourceLocation particles; private boolean useCulling; private boolean useShading; - private Vector3f offset; private OBJModelBuilder() {} From a6acb674289c1e4bffb7a5ba1f5332ce2d47bc15 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 21:01:46 +0300 Subject: [PATCH 0116/1033] Multi material fix --- .../ru/bclib/client/models/ModelsHelper.java | 4 ++- .../ru/bclib/client/models/OBJBlockModel.java | 30 +++++++++++-------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index e8992cbe..b7eec681 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -102,7 +102,9 @@ public class ModelsHelper { private MultiPartBuilder() {} public ModelPart part(ResourceLocation modelId) { - return new ModelPart(modelId); + ModelPart part = new ModelPart(modelId); + modelParts.add(part); + return part; } public MultiPart build() { diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java index ea090342..cf9a5092 100644 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -20,7 +20,6 @@ import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.core.Direction; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; -import net.minecraft.util.Mth; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import ru.bclib.util.BlocksHelper; @@ -62,14 +61,19 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { quadsUnbakedMap.put(dir, Lists.newArrayList()); quadsBakedMap.put(dir, Lists.newArrayList()); } + transforms = ItemTransforms.NO_TRANSFORMS; overrides = ItemOverrides.EMPTY; - materials = new ArrayList<>(textureIDs.length + 1); - sprites = new TextureAtlasSprite[textureIDs.length + 1]; + materials = new ArrayList<>(textureIDs.length); + sprites = new TextureAtlasSprite[textureIDs.length]; this.particleIndex = particleIndex; this.useCulling = useCulling; this.useShading = useShading; - loadModel(location, textureIDs, offset); + loadModel(location, offset, (byte) (textureIDs.length - 1)); + + for (int i = 0; i < textureIDs.length; i++) { + materials.add(new Material(TextureAtlas.LOCATION_BLOCKS, textureIDs[i])); + } } // UnbakedModel // @@ -163,7 +167,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { return resource; } - private void loadModel(ResourceLocation location, ResourceLocation[] textureIDs, Vector3f offset) { + private void loadModel(ResourceLocation location, Vector3f offset, byte maxIndex) { Resource resource = getResource(location); if (resource == null) { return; @@ -176,8 +180,7 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { List vertexIndex = new ArrayList<>(4); List uvIndex = new ArrayList<>(4); - byte materialIndex = 0; - int vertCount = 0; + byte materialIndex = -1; try { InputStreamReader streamReader = new InputStreamReader(input); @@ -185,9 +188,11 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { String string; while ((string = reader.readLine()) != null) { - if ((string.startsWith("usemtl") || string.startsWith("g")) && vertCount != vertecies.size()) { - vertCount = vertecies.size(); + if (string.startsWith("usemtl")) { materialIndex++; + if (materialIndex > maxIndex) { + materialIndex = maxIndex; + } } else if (string.startsWith("vt")) { String[] uv = string.split(" "); @@ -266,10 +271,9 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { e.printStackTrace(); } - int maxID = textureIDs.length - 1; - for (int i = 0; i <= materialIndex; i++) { - int index = Math.min(materialIndex, maxID); - materials.add(new Material(TextureAtlas.LOCATION_BLOCKS, textureIDs[index])); + if (materialIndex < 0) { + quadsUnbaked.forEach(quad -> quad.setSpriteIndex(0)); + quadsUnbakedMap.values().forEach(list -> list.forEach(quad -> quad.setSpriteIndex(0))); } } From 1ea7221f9f0c66f87c57a8b76fb22381ad2ac285 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 21:08:20 +0300 Subject: [PATCH 0117/1033] Small fix --- src/main/java/ru/bclib/client/models/ModelsHelper.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index b7eec681..a27ab958 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -103,7 +103,6 @@ public class ModelsHelper { public ModelPart part(ResourceLocation modelId) { ModelPart part = new ModelPart(modelId); - modelParts.add(part); return part; } From f853ac75d94ac2220725c2d7c2783563ba91abf9 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 24 Jul 2021 21:30:48 +0300 Subject: [PATCH 0118/1033] Model transform --- .../ru/bclib/client/models/OBJBlockModel.java | 4 ++-- .../ru/bclib/client/models/UnbakedQuad.java | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java index cf9a5092..73497925 100644 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ b/src/main/java/ru/bclib/client/models/OBJBlockModel.java @@ -95,12 +95,12 @@ public class OBJBlockModel implements UnbakedModel, BakedModel { sprites[i] = textureGetter.apply(materials.get(i)); } quadsBaked.clear(); - quadsUnbaked.forEach(quad -> quadsBaked.add(quad.bake(sprites))); + quadsUnbaked.forEach(quad -> quadsBaked.add(quad.bake(sprites, modelState))); for (Direction dir: BlocksHelper.DIRECTIONS) { List unbaked = quadsUnbakedMap.get(dir); List baked = quadsBakedMap.get(dir); baked.clear(); - unbaked.forEach(quad -> baked.add(quad.bake(sprites))); + unbaked.forEach(quad -> baked.add(quad.bake(sprites, modelState))); } return this; } diff --git a/src/main/java/ru/bclib/client/models/UnbakedQuad.java b/src/main/java/ru/bclib/client/models/UnbakedQuad.java index 7df9250c..60b4ecc5 100644 --- a/src/main/java/ru/bclib/client/models/UnbakedQuad.java +++ b/src/main/java/ru/bclib/client/models/UnbakedQuad.java @@ -1,14 +1,18 @@ package ru.bclib.client.models; +import com.mojang.math.Matrix4f; import com.mojang.math.Vector3f; +import com.mojang.math.Vector4f; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.ModelState; import net.minecraft.core.Direction; @Environment(EnvType.CLIENT) public class UnbakedQuad { + private static final Vector4f POS = new Vector4f(); private float[] data = new float[20]; // 4 points with 3 positions and 2 uvs, 4 * (3 + 2) private Direction dir = Direction.UP; private boolean useShading = false; @@ -39,15 +43,21 @@ public class UnbakedQuad { return result; } - public BakedQuad bake(TextureAtlasSprite[] sprites) { + public BakedQuad bake(TextureAtlasSprite[] sprites, ModelState modelState) { + Matrix4f matrix = modelState.getRotation().getMatrix(); TextureAtlasSprite sprite = sprites[spriteIndex]; int[] vertexData = new int[32]; for (int i = 0; i < 4; i++) { int index = i << 3; int dataIndex = i * 5; - vertexData[index] = Float.floatToIntBits(data[dataIndex++]); // X - vertexData[index | 1] = Float.floatToIntBits(data[dataIndex++]); // Y - vertexData[index | 2] = Float.floatToIntBits(data[dataIndex++]); // Z + float x = data[dataIndex++]; // X + float y = data[dataIndex++]; // Y + float z = data[dataIndex++]; // Z + POS.set(x, y, z, 0); + POS.transform(matrix); + vertexData[index] = Float.floatToIntBits(POS.x()); // X + vertexData[index | 1] = Float.floatToIntBits(POS.y()); // Y + vertexData[index | 2] = Float.floatToIntBits(POS.z()); // Z vertexData[index | 3] = -1; // Unknown constant vertexData[index | 4] = Float.floatToIntBits(sprite.getU(data[dataIndex++])); // U vertexData[index | 5] = Float.floatToIntBits(sprite.getV(data[dataIndex])); // V From c93c271bd493c6c6d42102a50d62932fa78a4291 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 12:27:44 +0200 Subject: [PATCH 0119/1033] Added Patch-Function for *level.dat * --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 35 +++++++++++++------ .../bclib/api/datafixer/MigrationProfile.java | 18 +++++++++- .../java/ru/bclib/api/datafixer/Patch.java | 14 ++++++++ .../api/datafixer/PatchDidiFailException.java | 10 ++++++ .../ru/bclib/api/datafixer/PatchFunction.java | 6 ++++ 5 files changed, 71 insertions(+), 12 deletions(-) create mode 100644 src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java create mode 100644 src/main/java/ru/bclib/api/datafixer/PatchFunction.java diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index ff7add7d..3f0abcc7 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -22,6 +22,9 @@ import java.util.regex.Pattern; public class DataFixerAPI { static final Logger LOGGER = new Logger("DataFixerAPI"); + static class State { + public boolean didFail = false; + } public static void fixData(File dir) { if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { @@ -36,22 +39,22 @@ public class DataFixerAPI { return; } - boolean[] allOk = {true}; + State state = new State(); List regions = getAllRegions(dir, null); - regions.parallelStream().forEach((file) -> fixRegion(data, allOk, file)); + regions.parallelStream().forEach((file) -> fixRegion(data, state, file)); List players = getAllPlayers(dir); - players.parallelStream().forEach((file) -> fixPlayer(data, allOk, file)); + players.parallelStream().forEach((file) -> fixPlayer(data, state, file)); - fixLevel(data, allOk, new File(dir, "level.dat")); + fixLevel(data, state, new File(dir, "level.dat")); - if (allOk[0]) { + if (!state.didFail) { data.markApplied(); WorldDataAPI.saveFile(BCLib.MOD_ID); } } - private static void fixLevel(MigrationProfile data, boolean[] allOk, File file) { + private static void fixLevel(MigrationProfile data, State state, File file) { try { LOGGER.info("Inspecting " + file); CompoundTag level = NbtIo.readCompressed(file); @@ -64,6 +67,13 @@ public class DataFixerAPI { fixPlayerNbt(player, changed, data); } } + + try { + changed[0] |= data.patchLevelDat(level); + } catch (PatchDidiFailException e){ + state.didFail = true; + BCLib.LOGGER.error(e.getMessage()); + } if (changed[0]) { LOGGER.warning("Writing '{}'", file); @@ -71,12 +81,13 @@ public class DataFixerAPI { } } catch (Exception e) { - allOk[0] = false; + BCLib.LOGGER.error("Failed fixing Level-Data."); + state.didFail = true; e.printStackTrace(); } } - private static void fixPlayer(MigrationProfile data, boolean[] allOk, File file) { + private static void fixPlayer(MigrationProfile data, State state, File file) { try { LOGGER.info("Inspecting " + file); CompoundTag player = NbtIo.readCompressed(file); @@ -89,7 +100,8 @@ public class DataFixerAPI { } } catch (Exception e) { - allOk[0] = false; + BCLib.LOGGER.error("Failed fixing Player-Data."); + state.didFail = true; e.printStackTrace(); } } @@ -104,7 +116,7 @@ public class DataFixerAPI { fixInventory(enderitems, changed, data, true); } - private static void fixRegion(MigrationProfile data, boolean[] allOk, File file) { + private static void fixRegion(MigrationProfile data, State state, File file) { try { LOGGER.info("Inspecting " + file); boolean[] changed = new boolean[1]; @@ -155,7 +167,8 @@ public class DataFixerAPI { region.close(); } catch (Exception e) { - allOk[0] = false; + BCLib.LOGGER.error("Failed fixing Player Data."); + state.didFail = true; e.printStackTrace(); } } diff --git a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java index 644b9d6c..8ad695b6 100644 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java @@ -5,6 +5,8 @@ import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -12,6 +14,8 @@ import java.util.stream.Collectors; class MigrationProfile { final Set mods; final Map idReplacements; + final List> levelPatchers; + private final CompoundTag config; MigrationProfile(CompoundTag config) { @@ -23,6 +27,7 @@ class MigrationProfile { .collect(Collectors.toSet())); HashMap replacements = new HashMap(); + List> levelPatches = new LinkedList<>(); for (String modID : mods) { Patch.getALL() .stream() @@ -30,6 +35,8 @@ class MigrationProfile { .forEach(patch -> { if (currentPatchLevel(modID) < patch.level) { replacements.putAll(patch.getIDReplacements()); + if (patch.getLevelDatPatcher()!=null) + levelPatches.add(patch.getLevelDatPatcher()); DataFixerAPI.LOGGER.info("Applying " + patch); } else { @@ -39,6 +46,7 @@ class MigrationProfile { } this.idReplacements = Collections.unmodifiableMap(replacements); + this.levelPatchers = Collections.unmodifiableList(levelPatches); } final public void markApplied() { @@ -58,7 +66,7 @@ class MigrationProfile { } public boolean hasAnyFixes() { - return idReplacements.size() > 0; + return idReplacements.size() > 0 || levelPatchers.size() > 0; } public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key) { @@ -75,4 +83,12 @@ class MigrationProfile { return false; } + + public boolean patchLevelDat(@NotNull CompoundTag level) throws PatchDidiFailException { + boolean changed = false; + for (PatchFunction f : levelPatchers) { + changed |= f.apply(level); + } + return changed; + } } diff --git a/src/main/java/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java index 1be18145..30db9b4c 100644 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ b/src/main/java/ru/bclib/api/datafixer/Patch.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; public abstract class Patch { + private static List ALL = new ArrayList<>(10); /** @@ -119,6 +120,19 @@ public abstract class Patch { return new HashMap(); } + /** + * Return a {@link PatchFunction} that is called with the content of level.dat. + *

    + * The function needs to return {@code true}, if changes were made to the data. + * If an error occurs, the method shoudl throw a {@link PatchDidiFailException} + * + * The default implementation of this method returns null. + * + * @return The returned function is called a {@code CompoundTag} that contains the + * contents of level.dat + */ + public PatchFunction getLevelDatPatcher() { return null; } + /** * Generates ready to use data for all currently registered patches. The list of * patches is selected by the current patch-level of the world. diff --git a/src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java b/src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java new file mode 100644 index 00000000..737ba402 --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java @@ -0,0 +1,10 @@ +package ru.bclib.api.datafixer; + +public class PatchDidiFailException extends Exception { + public PatchDidiFailException(){ + super(); + } + public PatchDidiFailException(Exception e){ + super(e); + } +} diff --git a/src/main/java/ru/bclib/api/datafixer/PatchFunction.java b/src/main/java/ru/bclib/api/datafixer/PatchFunction.java new file mode 100644 index 00000000..77c70f6b --- /dev/null +++ b/src/main/java/ru/bclib/api/datafixer/PatchFunction.java @@ -0,0 +1,6 @@ +package ru.bclib.api.datafixer; + +@FunctionalInterface +public interface PatchFunction { + R apply(T t) throws PatchDidiFailException; +} From a247b17e7f3e7aa81cc34e93d97dec87ff580adb Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 18:36:20 +0200 Subject: [PATCH 0120/1033] Added Screen to confirm Patches --- .../ru/bclib/api/datafixer/DataFixerAPI.java | 177 +++++++++++++++++- .../complexmaterials/ComplexMaterial.java | 4 +- .../WoodenComplexMaterial.java | 25 ++- .../bclib/gui/screens/ConfirmFixScreen.java | 132 +++++++++++++ .../ru/bclib/mixin/client/MinecraftMixin.java | 52 ++++- .../mixin/common/MinecraftServerMixin.java | 10 +- .../resources/assets/bclib/lang/de_de.json | 3 + .../resources/assets/bclib/lang/en_us.json | 7 +- 8 files changed, 384 insertions(+), 26 deletions(-) create mode 100644 src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java create mode 100644 src/main/resources/assets/bclib/lang/de_de.json diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 3f0abcc7..86df45bb 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -1,59 +1,215 @@ package ru.bclib.api.datafixer; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.toasts.SystemToast; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.worldselection.EditWorldScreen; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtIo; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.util.ProgressListener; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.RegionFile; +import net.minecraft.world.level.storage.LevelResource; +import net.minecraft.world.level.storage.LevelStorageSource; import ru.bclib.BCLib; import ru.bclib.api.WorldDataAPI; import ru.bclib.config.Configs; +import ru.bclib.gui.screens.ConfirmFixScreen; import ru.bclib.util.Logger; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; +/** + * API to manage Patches that need to get applied to a world + */ public class DataFixerAPI { static final Logger LOGGER = new Logger("DataFixerAPI"); static class State { public boolean didFail = false; } - public static void fixData(File dir) { + @FunctionalInterface + public static interface Callback { + public void call(); + } + + /** + * Will apply necessary Patches to the world. + * + * @param levelSource The SourceStorage for this Minecraft instance, You can get this using + * {@code Minecraft.getInstance().getLevelSource()} + * @param levelID The ID of the Level you want to patch + * @param showUI {@code true}, if you want to present the user with a Screen that offers to backup the world + * before applying the patches + * @param onResume When this method retursn {@code true}, this function will be called when the world is ready + * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and + * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. + * + */ + public static boolean fixData(LevelStorageSource levelSource, String levelID, boolean showUI, Consumer onResume) { + + LevelStorageSource.LevelStorageAccess levelStorageAccess; + try { + levelStorageAccess = levelSource.createAccess(levelID); + } catch (IOException e) { + BCLib.LOGGER.warning((String)"Failed to read level {} data", levelID, e); + SystemToast.onWorldAccessFailure(Minecraft.getInstance(), levelID); + Minecraft.getInstance().setScreen((Screen)null); + return true; + } + + boolean cancelRun = fixData(levelStorageAccess, showUI, onResume); + + try { + levelStorageAccess.close(); + } catch (IOException e) { + BCLib.LOGGER.warning((String)"Failed to unlock access to level {}", levelID, e); + } + + return cancelRun; + } + + /** + * Will apply necessary Patches to the world. + * + * @param levelStorageAccess The access class of the level you want to patch + * @param showUI {@code true}, if you want to present the user with a Screen that offers to backup the world + * before applying the patches + * @param onResume When this method retursn {@code true}, this function will be called when the world is ready + * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and + * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. + * + */ + public static boolean fixData(LevelStorageSource.LevelStorageAccess levelStorageAccess, boolean showUI, Consumer onResume){ + File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(); + WorldDataAPI.load(new File(levelPath, "data")); + return fixData(levelPath, levelStorageAccess.getLevelId(), showUI, onResume); + } + + private static boolean fixData(File dir, String levelID, boolean showUI, Consumer onResume) { + MigrationProfile profile = loadProfile(dir, levelID); + + Consumer runFixes = (applyFixes) -> { + if (applyFixes) { + runDataFixes(dir, profile, new ProgressListener() { + private long timeStamp = Util.getMillis(); + + public void progressStartNoAbort(Component component) { + } + + public void progressStart(Component component) { + } + + public void progressStagePercentage(int i) { + if (Util.getMillis() - this.timeStamp >= 1000L) { + this.timeStamp = Util.getMillis(); + BCLib.LOGGER.info((String) "Patching... {}%", (Object) i); + } + } + + public void stop() { + } + + public void progressStage(Component component) { + } + }); + } else { + //System.out.println("NO FIXES"); + } + + //UI is asynchronous, so we need to send the callback now + if (profile != null && showUI) { + onResume.accept(applyFixes); + } + }; + + //we have some migrations + if (profile != null) { + //display the confirm UI. + if (showUI){ + showBackupWarning(levelID, runFixes); + return true; + } else { + BCLib.LOGGER.warning("Applying Fixes on Level"); + runFixes.accept(true); + } + } + return false; + } + + static MigrationProfile loadProfile(File dir, String levelID){ if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { LOGGER.info("World Patches are disabled"); - return; + return null; } final CompoundTag patchConfig = WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); - MigrationProfile data = Patch.createMigrationData(patchConfig); - if (!data.hasAnyFixes()) { + MigrationProfile profile = Patch.createMigrationData(patchConfig); + + if (!profile.hasAnyFixes()) { LOGGER.info("Everything up to date"); - return; - } + return null; + } + + return profile; + } + + static void showBackupWarning(String levelID, Consumer whenFinished){ + TranslatableComponent promptText = new TranslatableComponent("bclib.datafixer.backupWarning.prompt"); + TranslatableComponent buttonTitle = new TranslatableComponent("bclib.datafixer.backupWarning.button"); + + Minecraft.getInstance().setScreen(new ConfirmFixScreen((Screen) null, (createBackup, applyFixes) -> { + if (createBackup) { + EditWorldScreen.makeBackupAndShowToast(Minecraft.getInstance().getLevelSource(), levelID); + } + + Minecraft.getInstance().setScreen((Screen)null); + whenFinished.accept(applyFixes); + })); + + } + private static void runDataFixes(File dir, MigrationProfile profile, ProgressListener progress) { + System.out.println("RUNNING fixes"); + if (dir!= null) return; + State state = new State(); List regions = getAllRegions(dir, null); - regions.parallelStream().forEach((file) -> fixRegion(data, state, file)); + progress.progressStagePercentage(0); + int[] count = {0}; + regions.parallelStream().forEach((file) -> { + fixRegion(profile, state, file); + count[0]++; + progress.progressStagePercentage((100 * count[0])/regions.size()); + }); + progress.stop(); List players = getAllPlayers(dir); - players.parallelStream().forEach((file) -> fixPlayer(data, state, file)); + players.parallelStream().forEach((file) -> fixPlayer(profile, state, file)); - fixLevel(data, state, new File(dir, "level.dat")); + fixLevel(profile, state, new File(dir, "level.dat")); if (!state.didFail) { - data.markApplied(); + profile.markApplied(); WorldDataAPI.saveFile(BCLib.MOD_ID); } } + private static void fixLevel(MigrationProfile data, State state, File file) { try { LOGGER.info("Inspecting " + file); @@ -121,6 +277,7 @@ public class DataFixerAPI { LOGGER.info("Inspecting " + file); boolean[] changed = new boolean[1]; RegionFile region = new RegionFile(file, file.getParentFile(), true); + for (int x = 0; x < 32; x++) { for (int z = 0; z < 32; z++) { ChunkPos pos = new ChunkPos(x, z); diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 9cfb2d2b..b5fceada 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -36,8 +36,8 @@ public abstract class ComplexMaterial { private final Map blocks = Maps.newHashMap(); private final Map items = Maps.newHashMap(); - private final String baseName; - private final String modID; + protected final String baseName; + protected final String modID; public ComplexMaterial(String modID, String baseName) { this.baseName = baseName; diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index d51c8a3b..a4d9abe4 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -41,6 +41,7 @@ import ru.bclib.complexmaterials.entry.RecipeEntry; import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; +import java.util.Arrays; import java.util.List; public class WoodenComplexMaterial extends ComplexMaterial { @@ -96,8 +97,14 @@ public class WoodenComplexMaterial extends ComplexMaterial { @Override protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + initDefault(blockSettings, itemSettings, new String[0]); + } + + final protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings, String[] excludedSuffixes) { Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); Tag.Named tagItemLog = getItemTag(TAG_LOGS); + List excl = Arrays.asList(excludedSuffixes); + addBlockEntry( new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { @@ -173,12 +180,18 @@ public class WoodenComplexMaterial extends ComplexMaterial { addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); })); - addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { - return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { - return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); - })); + + if (!excl.contains(BLOCK_BOOKSHELF)) { + addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { + return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); + } + + if (!excl.contains(BLOCK_COMPOSTER)) { + addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { + return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); + })); + } } @Override diff --git a/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java b/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java new file mode 100644 index 00000000..54ebbbc5 --- /dev/null +++ b/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java @@ -0,0 +1,132 @@ +package ru.bclib.gui.screens; + + + import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.BackupConfirmScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.Mth; +import org.jetbrains.annotations.Nullable; +import ru.bclib.BCLib; + +import java.util.Objects; +class ColoredButton extends Button { + private final float r; + private final float g; + private final float b; + public ColoredButton(int x, int y, int width, int height, Component component, OnPress onPress, float r, float g, float b) { + super(x, y, width, height, component, onPress); + this.r = r; + this.g = g; + this.b = b; + } + + @Override + public void renderButton(PoseStack poseStack, int i, int j, float f) { + Minecraft minecraft = Minecraft.getInstance(); + Font font = minecraft.font; + RenderSystem.setShader(GameRenderer::getPositionTexShader); + RenderSystem.setShaderTexture(0, WIDGETS_LOCATION); + RenderSystem.setShaderColor(r, g, b, this.alpha); + int k = this.getYImage(this.isHovered()); + RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); + RenderSystem.enableDepthTest(); + this.blit(poseStack, this.x, this.y, 0, 46 + k * 20, this.width / 2, this.height); + this.blit(poseStack, this.x + this.width / 2, this.y, 200 - this.width / 2, 46 + k * 20, this.width / 2, this.height); + this.renderBg(poseStack, minecraft, i, j); + int l = this.active ? 16777215 : 10526880; + drawCenteredString(poseStack, font, this.getMessage(), this.x + this.width / 2, this.y + (this.height - 8) / 2, l | Mth.ceil(this.alpha * 255.0F) << 24); + } +} + +@Environment(EnvType.CLIENT) +public class ConfirmFixScreen extends Screen { + static final ResourceLocation BCLIB_LOGO_LOCATION = new ResourceLocation(BCLib.MOD_ID, + "icon.png"); + @Nullable + private final Screen lastScreen; + protected final BackupConfirmScreen.Listener listener; + private final Component description; + private MultiLineLabel message; + protected int id; + + public ConfirmFixScreen(@Nullable Screen screen, BackupConfirmScreen.Listener listener) { + super(new TranslatableComponent("bclib.datafixer.backupWarning.title")); + this.message = MultiLineLabel.EMPTY; + this.lastScreen = screen; + this.listener = listener; + this.description = new TranslatableComponent("bclib.datafixer.backupWarning.message"); + } + + protected void init() { + super.init(); + this.message = MultiLineLabel.create(this.font, this.description, this.width - 50); + int promptLines = this.message.getLineCount() + 1; + Objects.requireNonNull(this.font); + int height = promptLines * 9; + final int BUTTON_WIDTH = 150; + final int BUTTON_SPACE = 10; + final int BUTTON_HEIGHT = 20; + + Button customButton = new Button((this.width -BUTTON_WIDTH)/2, 100 + height, BUTTON_WIDTH, BUTTON_HEIGHT, new TranslatableComponent("bclib.datafixer.backupWarning.backup"), (button) -> { + this.listener.proceed(true, true); + }); + this.addRenderableWidget(customButton); + + + customButton = new Button((this.width - 2*BUTTON_WIDTH - BUTTON_SPACE)/ 2 , 124 + height, BUTTON_WIDTH, BUTTON_HEIGHT, CommonComponents.GUI_CANCEL, (button) -> { + this.minecraft.setScreen(this.lastScreen); + }); + this.addRenderableWidget(customButton); + + customButton = new Button((this.width - 2*BUTTON_WIDTH - BUTTON_SPACE)/ 2 + BUTTON_WIDTH+BUTTON_SPACE, 124 + height, BUTTON_WIDTH, BUTTON_HEIGHT, new TranslatableComponent("bclib.datafixer.backupWarning.continue"), (button) -> { + this.listener.proceed(false, true); + }); + customButton.setAlpha(0.5f); + this.addRenderableWidget(customButton); + + + customButton = new Button((this.width - BUTTON_WIDTH)/ 2, 148 + height, BUTTON_WIDTH, BUTTON_HEIGHT, new TranslatableComponent("bclib.datafixer.backupWarning.nofixes"), (button) -> { + this.listener.proceed(false, false); + }); + customButton.setAlpha(0.5f); + this.addRenderableWidget(customButton); + } + + public void render(PoseStack poseStack, int i, int j, float f) { + this.renderBackground(poseStack); + drawCenteredString(poseStack, this.font, this.title, this.width / 2, 50, 16777215); + this.message.renderCentered(poseStack, this.width / 2, 70); + super.render(poseStack, i, j, f); + } + + public boolean shouldCloseOnEsc() { + return false; + } + + public boolean keyPressed(int i, int j, int k) { + if (i == 256) { + this.minecraft.setScreen(this.lastScreen); + return true; + } else { + return super.keyPressed(i, j, k); + } + } + + @Environment(EnvType.CLIENT) + public interface Listener { + void proceed(boolean bl, boolean bl2); + } +} diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 4633efbe..9970d91f 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -5,16 +5,19 @@ import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.color.item.ItemColors; import net.minecraft.client.main.GameConfig; import net.minecraft.core.Registry; +import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.interfaces.CustomColorProvider; @Mixin(Minecraft.class) -public class MinecraftMixin { +public abstract class MinecraftMixin { @Final @Shadow private BlockColors blockColors; @@ -33,4 +36,51 @@ public class MinecraftMixin { } }); } + + + @Shadow @Final private LevelStorageSource levelSource; + @Shadow public abstract void loadLevel(String string); + private final String BCLIB_RECURSION = "$@BCLIB:"; + + @Inject(method="loadLevel", cancellable = true, at=@At("HEAD")) + private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci){ + boolean recursiveCall = false; + if (levelID.startsWith(BCLIB_RECURSION)) { + levelID = levelID.substring(BCLIB_RECURSION.length()); + recursiveCall = true; + } + + final String recursiveLevelID = BCLIB_RECURSION + levelID; + if (!recursiveCall && DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes)->{ + this.loadLevel(recursiveLevelID); + })){ + ci.cancel(); + } + } + + @ModifyArg(method="loadLevel", at=@At(value="INVOKE", target="Lnet/minecraft/client/Minecraft;doLoadLevel(Ljava/lang/String;Lnet/minecraft/core/RegistryAccess$RegistryHolder;Ljava/util/function/Function;Lcom/mojang/datafixers/util/Function4;ZLnet/minecraft/client/Minecraft$ExperimentalDialogType;)V")) + private String bclib_correctLevelID(String levelID){ + if (levelID.startsWith(BCLIB_RECURSION)) { + levelID = levelID.substring(BCLIB_RECURSION.length()); + } + + return levelID; + } + + +// @Inject(method="doLoadLevel", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, at=@At(value="INVOKE", target="Lnet/minecraft/client/Minecraft;makeServerStem(Lnet/minecraft/core/RegistryAccess$RegistryHolder;Ljava/util/function/Function;Lcom/mojang/datafixers/util/Function4;ZLnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;)Lnet/minecraft/client/Minecraft$ServerStem;")) +// private void bclib_onCallFixer( +// String string, +// RegistryHolder registryHolder, +// Function function, +// Function4 function4, +// boolean bl, +// ExperimentalDialogType experimentalDialogType, +// CallbackInfo ci, +// LevelStorageSource.LevelStorageAccess levelStorageAccess) { +// +// DataFixerAPI.fixData(levelStorageAccess); +// ci.cancel(); +// +// } } diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index 52495509..0fea24a6 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -6,7 +6,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerResources; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; -import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.WorldData; import org.spongepowered.asm.mixin.Final; @@ -17,11 +16,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; -import ru.bclib.api.WorldDataAPI; -import ru.bclib.api.datafixer.DataFixerAPI; import ru.bclib.recipes.BCLRecipeManager; -import java.io.File; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -38,12 +34,14 @@ public class MinecraftServerMixin { @Final @Shadow protected WorldData worldData; + @Inject(method="convertFromRegionFormatIfNeeded", at = @At("HEAD")) private static void bclib_applyPatches(LevelStorageSource.LevelStorageAccess session, CallbackInfo ci){ - File levelPath = session.getLevelPath(LevelResource.ROOT).toFile(); + + /*File levelPath = session.getLevelPath(LevelResource.ROOT).toFile(); WorldDataAPI.load(new File(levelPath, "data")); - DataFixerAPI.fixData(levelPath); + DataFixerAPI.fixData(levelPath, session.getLevelId());*/ } diff --git a/src/main/resources/assets/bclib/lang/de_de.json b/src/main/resources/assets/bclib/lang/de_de.json new file mode 100644 index 00000000..ff0aef35 --- /dev/null +++ b/src/main/resources/assets/bclib/lang/de_de.json @@ -0,0 +1,3 @@ +{ + "message.bclib.anvil_damage": "§cSchaden" +} \ No newline at end of file diff --git a/src/main/resources/assets/bclib/lang/en_us.json b/src/main/resources/assets/bclib/lang/en_us.json index b89551db..6df95514 100644 --- a/src/main/resources/assets/bclib/lang/en_us.json +++ b/src/main/resources/assets/bclib/lang/en_us.json @@ -1,3 +1,8 @@ { - "message.bclib.anvil_damage": "§cDamage" + "message.bclib.anvil_damage": "§cDamage", + "bclib.datafixer.backupWarning.title": "Guardian detected an incompatible World", + "bclib.datafixer.backupWarning.message": "The Guardian detected, that the internals of the following Mods did change since this world was last played.\n\nWe can automatically change the world for you. If you continue without applying the changes the world may not load correct. Before you continue, you should create a Backup.", + "bclib.datafixer.backupWarning.backup": "Create Backup and Continue", + "bclib.datafixer.backupWarning.nofixes": "Continue Without Fixes", + "bclib.datafixer.backupWarning.continue": "Continue Without Backup" } \ No newline at end of file From d3db623de59883ff905d236600c1adda1466f8e6 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 18:50:15 +0200 Subject: [PATCH 0121/1033] Call DataFixer in Server Context --- .../java/ru/bclib/mixin/common/MainMixin.java | 17 +++++++++++++++++ src/main/resources/bclib.mixins.common.json | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/bclib/mixin/common/MainMixin.java diff --git a/src/main/java/ru/bclib/mixin/common/MainMixin.java b/src/main/java/ru/bclib/mixin/common/MainMixin.java new file mode 100644 index 00000000..bb39c129 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/MainMixin.java @@ -0,0 +1,17 @@ +package ru.bclib.mixin.common; + +import net.minecraft.server.Main; +import net.minecraft.world.level.storage.LevelStorageSource; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import ru.bclib.api.datafixer.DataFixerAPI; + +@Mixin(Main.class) +abstract public class MainMixin { + @ModifyArg(method="main", at=@At(value="INVOKE", target="Lnet/minecraft/server/MinecraftServer;convertFromRegionFormatIfNeeded(Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;)V")) + private static LevelStorageSource.LevelStorageAccess bclib_callServerFix(LevelStorageSource.LevelStorageAccess session){ + DataFixerAPI.fixData(session, false, (didFix)->{}); + return session; + } +} diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 5ea05c8b..ecf7c440 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -15,7 +15,8 @@ "AnvilBlockMixin", "AnvilMenuMixin", "TagLoaderMixin", - "BiomeMixin" + "BiomeMixin", + "MainMixin" ], "injectors": { "defaultRequire": 1 From c4d7035ef2c6abb45efd11d6e6f23bfe02e87b41 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 18:52:05 +0200 Subject: [PATCH 0122/1033] Move method to client Environment --- src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 86df45bb..258747a7 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -1,5 +1,7 @@ package ru.bclib.api.datafixer; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.toasts.SystemToast; @@ -168,6 +170,7 @@ public class DataFixerAPI { return profile; } + @Environment(EnvType.CLIENT) static void showBackupWarning(String levelID, Consumer whenFinished){ TranslatableComponent promptText = new TranslatableComponent("bclib.datafixer.backupWarning.prompt"); TranslatableComponent buttonTitle = new TranslatableComponent("bclib.datafixer.backupWarning.button"); From eb8c87468f8854d86d3706f40a2cd4932a3dd5e3 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 21:31:17 +0200 Subject: [PATCH 0123/1033] Initialize new worlds as fully patched --- src/main/java/ru/bclib/api/WorldDataAPI.java | 3 + .../ru/bclib/api/datafixer/DataFixerAPI.java | 103 +++++++++++++----- .../ru/bclib/mixin/client/MinecraftMixin.java | 8 ++ .../java/ru/bclib/mixin/common/MainMixin.java | 2 +- 4 files changed, 89 insertions(+), 27 deletions(-) diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index 1ce22f35..616791fd 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -104,6 +104,9 @@ public class WorldDataAPI { */ public static void saveFile(String modID) { try { + if (!dataDir.exists()){ + dataDir.mkdirs(); + } NbtIo.writeCompressed(getRootTag(modID), new File(dataDir, modID + ".nbt")); } catch (IOException e) { diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 258747a7..269096b3 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -17,6 +17,8 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.storage.RegionFile; import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; +import org.jetbrains.annotations.NotNull; import ru.bclib.BCLib; import ru.bclib.api.WorldDataAPI; import ru.bclib.config.Configs; @@ -31,6 +33,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -49,6 +52,29 @@ public class DataFixerAPI { public void call(); } + private static boolean wrapCall(LevelStorageSource levelSource, String levelID, Function runWithLevel) { + + LevelStorageSource.LevelStorageAccess levelStorageAccess; + try { + levelStorageAccess = levelSource.createAccess(levelID); + } catch (IOException e) { + BCLib.LOGGER.warning((String)"Failed to read level {} data", levelID, e); + SystemToast.onWorldAccessFailure(Minecraft.getInstance(), levelID); + Minecraft.getInstance().setScreen((Screen)null); + return true; + } + + boolean returnValue = runWithLevel.apply(levelStorageAccess); + + try { + levelStorageAccess.close(); + } catch (IOException e) { + BCLib.LOGGER.warning((String)"Failed to unlock access to level {}", levelID, e); + } + + return returnValue; + } + /** * Will apply necessary Patches to the world. * @@ -63,26 +89,7 @@ public class DataFixerAPI { * */ public static boolean fixData(LevelStorageSource levelSource, String levelID, boolean showUI, Consumer onResume) { - - LevelStorageSource.LevelStorageAccess levelStorageAccess; - try { - levelStorageAccess = levelSource.createAccess(levelID); - } catch (IOException e) { - BCLib.LOGGER.warning((String)"Failed to read level {} data", levelID, e); - SystemToast.onWorldAccessFailure(Minecraft.getInstance(), levelID); - Minecraft.getInstance().setScreen((Screen)null); - return true; - } - - boolean cancelRun = fixData(levelStorageAccess, showUI, onResume); - - try { - levelStorageAccess.close(); - } catch (IOException e) { - BCLib.LOGGER.warning((String)"Failed to unlock access to level {}", levelID, e); - } - - return cancelRun; + return wrapCall(levelSource, levelID, (levelStorageAccess) -> fixData(levelStorageAccess, showUI, onResume)); } /** @@ -98,12 +105,50 @@ public class DataFixerAPI { */ public static boolean fixData(LevelStorageSource.LevelStorageAccess levelStorageAccess, boolean showUI, Consumer onResume){ File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(); - WorldDataAPI.load(new File(levelPath, "data")); + + boolean newWorld = false; + if (!levelPath.exists()) { + BCLib.LOGGER.info("Creating a new World, no fixes needed"); + newWorld = true; + } + + initializeWorldData(levelPath, newWorld); + if (newWorld) return false; + return fixData(levelPath, levelStorageAccess.getLevelId(), showUI, onResume); } + /** + * Initializes the DataStorage for this world. If the world is new, the patch registry is initialized to the + * @param levelSource The SourceStorage for this Minecraft instance, You can get this using + * {@code Minecraft.getInstance().getLevelSource()} + * @param levelID The ID of the Level you want to patch + * @param newWorld {@code true} if this is a fresh world + */ + public static void initializeWorldData(LevelStorageSource levelSource, String levelID, boolean newWorld) { + wrapCall(levelSource, levelID, (levelStorageAccess) -> { + initializeWorldData(levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(), newWorld); + return true; + }); + } + + /** + * Initializes the DataStorage for this world. If the world is new, the patch registry is initialized to the + * current versions of the plugins. + * @param levelPath Folder of the world + * @param newWorld {@code true} if this is a fresh world + * + */ + public static void initializeWorldData(File levelPath, boolean newWorld){ + WorldDataAPI.load(new File(levelPath, "data")); + + if (newWorld){ + getMigrationProfile().markApplied(); + WorldDataAPI.saveFile(BCLib.MOD_ID); + } + } private static boolean fixData(File dir, String levelID, boolean showUI, Consumer onResume) { - MigrationProfile profile = loadProfile(dir, levelID); + MigrationProfile profile = loadProfileIfNeeded(); Consumer runFixes = (applyFixes) -> { if (applyFixes) { @@ -153,16 +198,15 @@ public class DataFixerAPI { return false; } - static MigrationProfile loadProfile(File dir, String levelID){ + private static MigrationProfile loadProfileIfNeeded(){ if (!Configs.MAIN_CONFIG.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { LOGGER.info("World Patches are disabled"); return null; } - final CompoundTag patchConfig = WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); - MigrationProfile profile = Patch.createMigrationData(patchConfig); + MigrationProfile profile = getMigrationProfile(); - if (!profile.hasAnyFixes()) { + if (!profile.hasAnyFixes()) { LOGGER.info("Everything up to date"); return null; } @@ -170,6 +214,13 @@ public class DataFixerAPI { return profile; } + @NotNull + private static MigrationProfile getMigrationProfile() { + final CompoundTag patchConfig = WorldDataAPI.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); + MigrationProfile profile = Patch.createMigrationData(patchConfig); + return profile; + } + @Environment(EnvType.CLIENT) static void showBackupWarning(String levelID, Consumer whenFinished){ TranslatableComponent promptText = new TranslatableComponent("bclib.datafixer.backupWarning.prompt"); diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 9970d91f..7cfd889a 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -5,6 +5,9 @@ import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.color.item.ItemColors; import net.minecraft.client.main.GameConfig; import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess.RegistryHolder; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.storage.LevelStorageSource; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -67,6 +70,11 @@ public abstract class MinecraftMixin { return levelID; } + @Inject(method="createLevel", at=@At("HEAD")) + private void bclib_initPatchData(String levelID, LevelSettings levelSettings, RegistryHolder registryHolder, WorldGenSettings worldGenSettings, CallbackInfo ci) { + DataFixerAPI.initializeWorldData(this.levelSource, levelID, true); + } + // @Inject(method="doLoadLevel", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, at=@At(value="INVOKE", target="Lnet/minecraft/client/Minecraft;makeServerStem(Lnet/minecraft/core/RegistryAccess$RegistryHolder;Ljava/util/function/Function;Lcom/mojang/datafixers/util/Function4;ZLnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;)Lnet/minecraft/client/Minecraft$ServerStem;")) // private void bclib_onCallFixer( diff --git a/src/main/java/ru/bclib/mixin/common/MainMixin.java b/src/main/java/ru/bclib/mixin/common/MainMixin.java index bb39c129..142aada1 100644 --- a/src/main/java/ru/bclib/mixin/common/MainMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MainMixin.java @@ -11,7 +11,7 @@ import ru.bclib.api.datafixer.DataFixerAPI; abstract public class MainMixin { @ModifyArg(method="main", at=@At(value="INVOKE", target="Lnet/minecraft/server/MinecraftServer;convertFromRegionFormatIfNeeded(Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;)V")) private static LevelStorageSource.LevelStorageAccess bclib_callServerFix(LevelStorageSource.LevelStorageAccess session){ - DataFixerAPI.fixData(session, false, (didFix)->{}); + DataFixerAPI.fixData(session, false, (didFix)->{/* not called when showUI==false */}); return session; } } From eda626fe108acb2307be0f2a70e3cf82b5be08bd Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Mon, 26 Jul 2021 21:36:34 +0200 Subject: [PATCH 0124/1033] Doc update --- src/main/java/ru/bclib/api/WorldDataAPI.java | 9 +++++++++ src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index 616791fd..78bbd980 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -6,6 +6,7 @@ import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; import ru.bclib.BCLib; import ru.bclib.api.datafixer.DataFixerAPI; @@ -14,7 +15,15 @@ import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.Consumer; +/** + * Mod-specifix data-storage for a world. + * + * This class provides the ability for mod to store persistent data inside a world. The Storage for the world is + * currently initialized as part of the {@link DataFixerAPI} in {@link DataFixerAPI#fixData(LevelStorageAccess, boolean, Consumer)} + * or {@link DataFixerAPI#initializeWorldData(File, boolean)} + */ public class WorldDataAPI { private static final Map TAGS = Maps.newHashMap(); private static final List MODS = Lists.newArrayList(); diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 269096b3..6f995919 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -119,6 +119,10 @@ public class DataFixerAPI { } /** * Initializes the DataStorage for this world. If the world is new, the patch registry is initialized to the + * current versions of the plugins. + *

    + * This implementation will create a new {@link LevelStorageAccess} and call {@link #initializeWorldData(File, boolean)} + * using the provided root path. * @param levelSource The SourceStorage for this Minecraft instance, You can get this using * {@code Minecraft.getInstance().getLevelSource()} * @param levelID The ID of the Level you want to patch From 30b7c8043a3435a8a72740449ca3f78645015d78 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 28 Jul 2021 23:28:42 +0200 Subject: [PATCH 0125/1033] First network test --- .../ru/bclib/api/dataexchange/Connector.java | 19 +++ .../api/dataexchange/ConnectorClientside.java | 59 ++++++++++ .../api/dataexchange/ConnectorServerside.java | 64 ++++++++++ .../api/dataexchange/DataExchangeAPI.java | 69 +++++++++++ .../bclib/api/dataexchange/DataHandler.java | 111 ++++++++++++++++++ .../dataexchange/DataHandlerDescriptor.java | 20 ++++ .../bclib/api/dataexchange/TestHandler.java | 33 ++++++ .../java/ru/bclib/client/BCLibClient.java | 4 + .../java/ru/bclib/server/BCLibServer.java | 3 + 9 files changed, 382 insertions(+) create mode 100644 src/main/java/ru/bclib/api/dataexchange/Connector.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/DataHandler.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/TestHandler.java diff --git a/src/main/java/ru/bclib/api/dataexchange/Connector.java b/src/main/java/ru/bclib/api/dataexchange/Connector.java new file mode 100644 index 00000000..683c845e --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/Connector.java @@ -0,0 +1,19 @@ +package ru.bclib.api.dataexchange; + +import java.util.HashSet; +import java.util.Set; + +abstract class Connector { + protected final DataExchangeAPI api; + protected final Set descriptors; + + Connector(DataExchangeAPI api) { + this.api = api; + descriptors = new HashSet<>(); + } + public abstract boolean onClient(); + + public void addDescriptor(DataHandlerDescriptor desc){ + this.descriptors.add(desc); + } +} diff --git a/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java new file mode 100644 index 00000000..aba569a7 --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java @@ -0,0 +1,59 @@ +package ru.bclib.api.dataexchange; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.FriendlyByteBuf; +import ru.bclib.BCLib; + +@Environment(EnvType.CLIENT) +class ConnectorClientside extends Connector { + private Minecraft client; + ConnectorClientside(DataExchangeAPI api) { + super(api); + this.client = null; + } + + + @Override + public boolean onClient() { + return true; + } + + protected void onPlayInit(ClientPacketListener handler, Minecraft client){ + if (this.client!=null && this.client != client){ + BCLib.LOGGER.warning("Client changed!"); + } + this.client = client; + for(DataHandlerDescriptor desc : descriptors){ + ClientPlayNetworking.registerReceiver(desc.identifier, (_client, _handler, _buf, _responseSender)->{ + receiveFromServer(desc, _client, _handler, _buf, _responseSender); + }); + } + } + + void onPlayReady(ClientPacketListener handler, PacketSender sender, Minecraft client){ + + } + + void onPlayDisconnect(ClientPacketListener handler, Minecraft client){ + for(DataHandlerDescriptor desc : descriptors) { + ClientPlayNetworking.unregisterReceiver(desc.identifier); + } + } + + void receiveFromServer(DataHandlerDescriptor desc, Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender responseSender){ + DataHandler h = desc.instancer.get(); + h.receiveFromServer(client, handler, buf, responseSender); + } + + void sendToServer(DataHandler h){ + if (client==null){ + throw new RuntimeException("[internal error] Client not initialized yet!"); + } + h.sendToServer(this.client); + } +} diff --git a/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java new file mode 100644 index 00000000..39ce6253 --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java @@ -0,0 +1,64 @@ +package ru.bclib.api.dataexchange; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import ru.bclib.BCLib; + +@Environment(EnvType.SERVER) +class ConnectorServerside extends Connector { + private MinecraftServer server; + ConnectorServerside(DataExchangeAPI api) { + super(api); + server = null; + } + + @Override + public boolean onClient() { + return false; + } + + protected void onPlayInit(ServerGamePacketListenerImpl handler, MinecraftServer server){ + if (this.server!=null && this.server != server){ + BCLib.LOGGER.warning("Server changed!"); + } + this.server = server; + for(DataHandlerDescriptor desc : descriptors){ + ServerPlayNetworking.registerReceiver(handler, desc.identifier, (_server, _player, _handler, _buf, _responseSender) -> { + receiveFromClient(desc, _server, _player, _handler, _buf, _responseSender); + }); + } + } + + void onPlayReady(ServerGamePacketListenerImpl handler, PacketSender sender, MinecraftServer server){ + for(DataHandlerDescriptor desc : descriptors){ + if (desc.sendOnJoin){ + DataHandler h = desc.instancer.get(); + h.sendToClient(server, handler.player); + } + } + } + + void onPlayDisconnect(ServerGamePacketListenerImpl handler, MinecraftServer server){ + for(DataHandlerDescriptor desc : descriptors){ + ServerPlayNetworking.unregisterReceiver(handler, desc.identifier); + } + } + + void receiveFromClient(DataHandlerDescriptor desc, MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender){ + DataHandler h = desc.instancer.get(); + h.receiveFromClient(server, player, handler, buf, responseSender); + } + + void sendToClient(DataHandler h){ + if (server==null){ + throw new RuntimeException("[internal error] Server not initialized yet!"); + } + h.sendToClient(this.server); + } +} diff --git a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java new file mode 100644 index 00000000..1d88fa26 --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java @@ -0,0 +1,69 @@ +package ru.bclib.api.dataexchange; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; +import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; + +public class DataExchangeAPI { + private static DataExchangeAPI instance; + private final ConnectorServerside server; + private final ConnectorClientside client; + + public static DataExchangeAPI getInstance(){ + return instance; + } + + private static DataExchangeAPI getOrCreateInstance(boolean isClient){ + if (instance==null){ + instance = new DataExchangeAPI(isClient); + } + return instance; + } + + private DataExchangeAPI(boolean isClient){ + if (isClient){ + client = new ConnectorClientside(this); + server = null; + + ClientPlayConnectionEvents.INIT.register(client::onPlayInit); + ClientPlayConnectionEvents.JOIN.register(client::onPlayReady); + ClientPlayConnectionEvents.DISCONNECT.register(client::onPlayDisconnect); + } else { + client = null; + server = new ConnectorServerside(this); + + ServerPlayConnectionEvents.INIT.register(server::onPlayInit); + ServerPlayConnectionEvents.JOIN.register(server::onPlayReady); + ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); + } + } + + + @Environment(EnvType.CLIENT) + public static void registerClientsideHandler(DataHandlerDescriptor desc){ + DataExchangeAPI api = DataExchangeAPI.getOrCreateInstance(true); + if (api.client == null){ + throw new RuntimeException("[Internal Error] DataExchangeAPI was already created as a Server"); + } + api.client.addDescriptor(desc); + } + + @Environment(EnvType.SERVER) + public static void registerServersideHandler(DataHandlerDescriptor desc){ + DataExchangeAPI api = DataExchangeAPI.getOrCreateInstance(false); + if (api.server == null){ + throw new RuntimeException("[Internal Error] DataExchangeAPI was already created as a Client"); + } + api.server.addDescriptor(desc); + } + + public static void send(DataHandler h){ + if (h.getOriginatesOnServer()){ + DataExchangeAPI.getInstance().server.sendToClient(h); + } else { + DataExchangeAPI.getInstance().client.sendToServer(h); + } + } + +} diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java new file mode 100644 index 00000000..1200c15c --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java @@ -0,0 +1,111 @@ +package ru.bclib.api.dataexchange; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.fabric.api.networking.v1.PlayerLookup; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.jetbrains.annotations.NotNull; + +public abstract class DataHandler { + private final boolean originatesOnServer; + @NotNull + private final ResourceLocation identifier; + + protected DataHandler(ResourceLocation identifier, boolean originatesOnServer){ + this.originatesOnServer = originatesOnServer; + this.identifier = identifier; + } + + final public boolean getOriginatesOnServer(){ + return originatesOnServer; + } + + final public ResourceLocation getIdentifier(){ + return identifier; + } + + @Environment(EnvType.CLIENT) + void receiveFromServer(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender responseSender){ + deserializeFromIncomingData(buf, responseSender, false); + client.execute(() -> runOnClient(client)); + } + + @Environment(EnvType.SERVER) + void receiveFromClient(MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender){ + deserializeFromIncomingData(buf, responseSender, true); + server.execute(() -> runOnServer(server)); + } + + protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient){ + } + + @Environment(EnvType.CLIENT) + protected void runOnClient(Minecraft client){ + + } + + @Environment(EnvType.SERVER) + protected void runOnServer(MinecraftServer server){ + + } + + protected void serializeData(FriendlyByteBuf buf) { + + } + + @Environment(EnvType.SERVER) + void sendToClient(MinecraftServer server){ + FriendlyByteBuf buf = PacketByteBufs.create(); + serializeData(buf); + + for (ServerPlayer player : PlayerLookup.all(server)) { + ServerPlayNetworking.send(player, this.identifier, buf); + } + } + + @Environment(EnvType.SERVER) + void sendToClient(MinecraftServer server, ServerPlayer player){ + FriendlyByteBuf buf = PacketByteBufs.create(); + serializeData(buf); + ServerPlayNetworking.send(player, this.identifier, buf); + } + + @Environment(EnvType.CLIENT) + void sendToServer(Minecraft client){ + FriendlyByteBuf buf = PacketByteBufs.create(); + serializeData(buf); + ClientPlayNetworking.send(identifier, buf); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DataHandler that = (DataHandler) o; + return originatesOnServer == that.originatesOnServer && identifier.equals(that.identifier); + } + + @Override + public int hashCode() { + int hash = identifier.hashCode(); + if (originatesOnServer) hash |= 0x80000000; + else hash &=0x7FFFFFFF; + + return hash; + } + + @Override + public String toString() { + return "DataHandler{" + "originatesOnServer=" + originatesOnServer + ", identifier=" + identifier + '}'; + } +} diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java b/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java new file mode 100644 index 00000000..9ca5077f --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java @@ -0,0 +1,20 @@ +package ru.bclib.api.dataexchange; + +import net.minecraft.resources.ResourceLocation; + +import java.util.function.Supplier; + +public class DataHandlerDescriptor { + public DataHandlerDescriptor(ResourceLocation identifier, Supplier instancer){ + this(identifier, instancer, false); + } + public DataHandlerDescriptor(ResourceLocation identifier, Supplier instancer, boolean sendOnJoin){ + this.instancer = instancer; + this.identifier = identifier; + this.sendOnJoin = sendOnJoin; + } + + public final boolean sendOnJoin; + public final ResourceLocation identifier; + public final Supplier instancer; +} diff --git a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java new file mode 100644 index 00000000..b805a299 --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java @@ -0,0 +1,33 @@ +package ru.bclib.api.dataexchange; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import ru.bclib.BCLib; + +public class TestHandler extends DataHandler{ + public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "__test"), TestHandler::new, true); + + public TestHandler() { + super(DESCRIPTOR.identifier, true); + } + + @Override + protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient) { + BCLib.LOGGER.info("PROCESSING INCOMING TEST-DATA fromClient="+fromClient); + } + + @Override + @Environment(EnvType.CLIENT) + protected void runOnClient(Minecraft client) { + BCLib.LOGGER.info("RUNNING INCOMING TEST-DATA ON CLIENT"); + } + + @Override + protected void serializeData(FriendlyByteBuf buf) { + BCLib.LOGGER.info("BUILDING OUTGOING TEST-DATA ON SERVER"); + } +} diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 7b338cfa..27bd5f66 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -3,6 +3,8 @@ package ru.bclib.client; import net.fabricmc.api.ClientModInitializer; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; +import ru.bclib.api.dataexchange.DataExchangeAPI; +import ru.bclib.api.dataexchange.TestHandler; import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @@ -10,6 +12,8 @@ public class BCLibClient implements ClientModInitializer { public void onInitializeClient() { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); + DataExchangeAPI.registerClientsideHandler(TestHandler.DESCRIPTOR); + PostInitAPI.postInit(true); } } diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index e1ba1107..9568a169 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -3,11 +3,14 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; +import ru.bclib.api.dataexchange.*; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); + DataExchangeAPI.registerServersideHandler(TestHandler.DESCRIPTOR); + PostInitAPI.postInit(false); } } From 7632c4e498e4b5af97ace04f396d08b4f4f3dc44 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Wed, 28 Jul 2021 23:52:18 +0200 Subject: [PATCH 0126/1033] Send first test-message --- src/main/java/ru/bclib/api/dataexchange/TestHandler.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java index b805a299..27fc621b 100644 --- a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java @@ -8,6 +8,8 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import ru.bclib.BCLib; +import java.nio.charset.StandardCharsets; + public class TestHandler extends DataHandler{ public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "__test"), TestHandler::new, true); @@ -17,7 +19,9 @@ public class TestHandler extends DataHandler{ @Override protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient) { - BCLib.LOGGER.info("PROCESSING INCOMING TEST-DATA fromClient="+fromClient); + int length = buf.readInt(); + CharSequence text = buf.readCharSequence(length, StandardCharsets.UTF_8); + BCLib.LOGGER.info("PROCESSING INCOMING TEST-DATA fromClient="+fromClient+": "+text); } @Override @@ -28,6 +32,9 @@ public class TestHandler extends DataHandler{ @Override protected void serializeData(FriendlyByteBuf buf) { + CharSequence text = "Welcome from BCLib"; + buf.writeInt(text.length()); + buf.writeCharSequence(text, StandardCharsets.UTF_8); BCLib.LOGGER.info("BUILDING OUTGOING TEST-DATA ON SERVER"); } } From 2260d547dc2f928bee8fc52791e0848294ea2f7a Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 29 Jul 2021 10:01:02 +0200 Subject: [PATCH 0127/1033] changes to run on non dedicated servers as well --- src/main/java/ru/bclib/BCLib.java | 3 + .../ru/bclib/api/dataexchange/Connector.java | 7 +- .../api/dataexchange/ConnectorClientside.java | 19 +++-- .../api/dataexchange/ConnectorServerside.java | 21 +++-- .../api/dataexchange/DataExchangeAPI.java | 78 ++++++++++--------- .../bclib/api/dataexchange/DataHandler.java | 4 - .../dataexchange/DataHandlerDescriptor.java | 17 ++-- .../bclib/api/dataexchange/TestHandler.java | 2 +- .../java/ru/bclib/client/BCLibClient.java | 3 +- .../mixin/common/MinecraftServerMixin.java | 15 +++- .../java/ru/bclib/server/BCLibServer.java | 2 +- 11 files changed, 99 insertions(+), 72 deletions(-) diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index d3174cae..6eb2634c 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -6,6 +6,8 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resources.ResourceLocation; import ru.bclib.api.TagAPI; import ru.bclib.api.WorldDataAPI; +import ru.bclib.api.dataexchange.DataExchangeAPI; +import ru.bclib.api.dataexchange.TestHandler; import ru.bclib.config.Configs; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; @@ -26,6 +28,7 @@ public class BCLib implements ModInitializer { CraftingRecipes.init(); WorldDataAPI.registerModCache(MOD_ID); Configs.save(); + DataExchangeAPI.registerDescriptor(TestHandler.DESCRIPTOR); } public static boolean isDevEnvironment() { diff --git a/src/main/java/ru/bclib/api/dataexchange/Connector.java b/src/main/java/ru/bclib/api/dataexchange/Connector.java index 683c845e..55a046a0 100644 --- a/src/main/java/ru/bclib/api/dataexchange/Connector.java +++ b/src/main/java/ru/bclib/api/dataexchange/Connector.java @@ -1,19 +1,16 @@ package ru.bclib.api.dataexchange; -import java.util.HashSet; import java.util.Set; abstract class Connector { protected final DataExchangeAPI api; - protected final Set descriptors; Connector(DataExchangeAPI api) { this.api = api; - descriptors = new HashSet<>(); } public abstract boolean onClient(); - public void addDescriptor(DataHandlerDescriptor desc){ - this.descriptors.add(desc); + protected Set getDescriptors(){ + return api.descriptors; } } diff --git a/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java index aba569a7..2e34765f 100644 --- a/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java +++ b/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java @@ -28,25 +28,32 @@ class ConnectorClientside extends Connector { BCLib.LOGGER.warning("Client changed!"); } this.client = client; - for(DataHandlerDescriptor desc : descriptors){ - ClientPlayNetworking.registerReceiver(desc.identifier, (_client, _handler, _buf, _responseSender)->{ + for(DataHandlerDescriptor desc : getDescriptors()){ + ClientPlayNetworking.registerReceiver(desc.IDENTIFIER, (_client, _handler, _buf, _responseSender)->{ receiveFromServer(desc, _client, _handler, _buf, _responseSender); }); } } void onPlayReady(ClientPacketListener handler, PacketSender sender, Minecraft client){ - + for(DataHandlerDescriptor desc : getDescriptors()){ + if (desc.sendOnJoin){ + DataHandler h = desc.JOIN_INSTANCE.get(); + if (!h.getOriginatesOnServer()) { + h.sendToServer(client); + } + } + } } void onPlayDisconnect(ClientPacketListener handler, Minecraft client){ - for(DataHandlerDescriptor desc : descriptors) { - ClientPlayNetworking.unregisterReceiver(desc.identifier); + for(DataHandlerDescriptor desc : getDescriptors()) { + ClientPlayNetworking.unregisterReceiver(desc.IDENTIFIER); } } void receiveFromServer(DataHandlerDescriptor desc, Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender responseSender){ - DataHandler h = desc.instancer.get(); + DataHandler h = desc.INSTANCE.get(); h.receiveFromServer(client, handler, buf, responseSender); } diff --git a/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java index 39ce6253..b5d7e920 100644 --- a/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java +++ b/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java @@ -1,7 +1,5 @@ package ru.bclib.api.dataexchange; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.network.FriendlyByteBuf; @@ -10,7 +8,6 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import ru.bclib.BCLib; -@Environment(EnvType.SERVER) class ConnectorServerside extends Connector { private MinecraftServer server; ConnectorServerside(DataExchangeAPI api) { @@ -28,30 +25,32 @@ class ConnectorServerside extends Connector { BCLib.LOGGER.warning("Server changed!"); } this.server = server; - for(DataHandlerDescriptor desc : descriptors){ - ServerPlayNetworking.registerReceiver(handler, desc.identifier, (_server, _player, _handler, _buf, _responseSender) -> { + for(DataHandlerDescriptor desc : getDescriptors()){ + ServerPlayNetworking.registerReceiver(handler, desc.IDENTIFIER, (_server, _player, _handler, _buf, _responseSender) -> { receiveFromClient(desc, _server, _player, _handler, _buf, _responseSender); }); } } void onPlayReady(ServerGamePacketListenerImpl handler, PacketSender sender, MinecraftServer server){ - for(DataHandlerDescriptor desc : descriptors){ + for(DataHandlerDescriptor desc : getDescriptors()){ if (desc.sendOnJoin){ - DataHandler h = desc.instancer.get(); - h.sendToClient(server, handler.player); + DataHandler h = desc.JOIN_INSTANCE.get(); + if (h.getOriginatesOnServer()) { + h.sendToClient(server, handler.player); + } } } } void onPlayDisconnect(ServerGamePacketListenerImpl handler, MinecraftServer server){ - for(DataHandlerDescriptor desc : descriptors){ - ServerPlayNetworking.unregisterReceiver(handler, desc.identifier); + for(DataHandlerDescriptor desc : getDescriptors()){ + ServerPlayNetworking.unregisterReceiver(handler, desc.IDENTIFIER); } } void receiveFromClient(DataHandlerDescriptor desc, MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender){ - DataHandler h = desc.instancer.get(); + DataHandler h = desc.INSTANCE.get(); h.receiveFromClient(server, player, handler, buf, responseSender); } diff --git a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java index 1d88fa26..375103b0 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java @@ -5,57 +5,62 @@ import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import java.util.HashSet; +import java.util.Set; + public class DataExchangeAPI { private static DataExchangeAPI instance; - private final ConnectorServerside server; - private final ConnectorClientside client; + private ConnectorServerside server; + private ConnectorClientside client; + protected final Set descriptors; + + + private DataExchangeAPI(){ + descriptors = new HashSet<>(); + } public static DataExchangeAPI getInstance(){ - return instance; - } - - private static DataExchangeAPI getOrCreateInstance(boolean isClient){ if (instance==null){ - instance = new DataExchangeAPI(isClient); + instance = new DataExchangeAPI(); } return instance; } - private DataExchangeAPI(boolean isClient){ - if (isClient){ - client = new ConnectorClientside(this); - server = null; - - ClientPlayConnectionEvents.INIT.register(client::onPlayInit); - ClientPlayConnectionEvents.JOIN.register(client::onPlayReady); - ClientPlayConnectionEvents.DISCONNECT.register(client::onPlayDisconnect); - } else { - client = null; - server = new ConnectorServerside(this); - - ServerPlayConnectionEvents.INIT.register(server::onPlayInit); - ServerPlayConnectionEvents.JOIN.register(server::onPlayReady); - ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); - } + @Environment(EnvType.CLIENT) + private void initClientside(){ + if (client!=null) return; + client = new ConnectorClientside(this); + + ClientPlayConnectionEvents.INIT.register(client::onPlayInit); + ClientPlayConnectionEvents.JOIN.register(client::onPlayReady); + ClientPlayConnectionEvents.DISCONNECT.register(client::onPlayDisconnect); + } + + private void initServerSide(){ + if (server!=null) return; + server = new ConnectorServerside(this); + + ServerPlayConnectionEvents.INIT.register(server::onPlayInit); + ServerPlayConnectionEvents.JOIN.register(server::onPlayReady); + ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); + } + + public static void registerDescriptor(DataHandlerDescriptor desc){ + DataExchangeAPI api = DataExchangeAPI.getInstance(); + api.descriptors.add(desc); } @Environment(EnvType.CLIENT) - public static void registerClientsideHandler(DataHandlerDescriptor desc){ - DataExchangeAPI api = DataExchangeAPI.getOrCreateInstance(true); - if (api.client == null){ - throw new RuntimeException("[Internal Error] DataExchangeAPI was already created as a Server"); - } - api.client.addDescriptor(desc); + public static void prepareClientside(){ + DataExchangeAPI api = DataExchangeAPI.getInstance(); + api.initClientside(); + } - @Environment(EnvType.SERVER) - public static void registerServersideHandler(DataHandlerDescriptor desc){ - DataExchangeAPI api = DataExchangeAPI.getOrCreateInstance(false); - if (api.server == null){ - throw new RuntimeException("[Internal Error] DataExchangeAPI was already created as a Client"); - } - api.server.addDescriptor(desc); + public static void prepareServerside(){ + DataExchangeAPI api = DataExchangeAPI.getInstance(); + api.initServerSide(); } public static void send(DataHandler h){ @@ -66,4 +71,5 @@ public class DataExchangeAPI { } } + } diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java index 1200c15c..ece8b021 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java @@ -40,7 +40,6 @@ public abstract class DataHandler { client.execute(() -> runOnClient(client)); } - @Environment(EnvType.SERVER) void receiveFromClient(MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender){ deserializeFromIncomingData(buf, responseSender, true); server.execute(() -> runOnServer(server)); @@ -54,7 +53,6 @@ public abstract class DataHandler { } - @Environment(EnvType.SERVER) protected void runOnServer(MinecraftServer server){ } @@ -63,7 +61,6 @@ public abstract class DataHandler { } - @Environment(EnvType.SERVER) void sendToClient(MinecraftServer server){ FriendlyByteBuf buf = PacketByteBufs.create(); serializeData(buf); @@ -73,7 +70,6 @@ public abstract class DataHandler { } } - @Environment(EnvType.SERVER) void sendToClient(MinecraftServer server, ServerPlayer player){ FriendlyByteBuf buf = PacketByteBufs.create(); serializeData(buf); diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java b/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java index 9ca5077f..585a3725 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java @@ -6,15 +6,22 @@ import java.util.function.Supplier; public class DataHandlerDescriptor { public DataHandlerDescriptor(ResourceLocation identifier, Supplier instancer){ - this(identifier, instancer, false); + this(identifier, instancer, instancer, false); } + public DataHandlerDescriptor(ResourceLocation identifier, Supplier instancer, boolean sendOnJoin){ - this.instancer = instancer; - this.identifier = identifier; + this(identifier, instancer, instancer, sendOnJoin); + } + public DataHandlerDescriptor(ResourceLocation identifier, Supplier receiv_instancer, Supplier join_instancer, boolean sendOnJoin){ + this.INSTANCE = receiv_instancer; + this.JOIN_INSTANCE = join_instancer; + this.IDENTIFIER = identifier; + this.sendOnJoin = sendOnJoin; } public final boolean sendOnJoin; - public final ResourceLocation identifier; - public final Supplier instancer; + public final ResourceLocation IDENTIFIER; + public final Supplier INSTANCE; + public final Supplier JOIN_INSTANCE; } diff --git a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java index 27fc621b..d55612ad 100644 --- a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java @@ -14,7 +14,7 @@ public class TestHandler extends DataHandler{ public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "__test"), TestHandler::new, true); public TestHandler() { - super(DESCRIPTOR.identifier, true); + super(DESCRIPTOR.IDENTIFIER, true); } @Override diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index 27bd5f66..ff803130 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -4,7 +4,6 @@ import net.fabricmc.api.ClientModInitializer; import ru.bclib.api.ModIntegrationAPI; import ru.bclib.api.PostInitAPI; import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.TestHandler; import ru.bclib.registry.BaseBlockEntityRenders; public class BCLibClient implements ClientModInitializer { @@ -12,7 +11,7 @@ public class BCLibClient implements ClientModInitializer { public void onInitializeClient() { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); - DataExchangeAPI.registerClientsideHandler(TestHandler.DESCRIPTOR); + DataExchangeAPI.prepareClientside(); PostInitAPI.postInit(true); } diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index 0fea24a6..203da109 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -1,12 +1,20 @@ package ru.bclib.mixin.common; +import com.mojang.authlib.GameProfileRepository; +import com.mojang.authlib.minecraft.MinecraftSessionService; +import com.mojang.datafixers.DataFixer; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.core.RegistryAccess.RegistryHolder; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerResources; import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.progress.ChunkProgressListenerFactory; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.players.GameProfileCache; import net.minecraft.world.level.Level; import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; import net.minecraft.world.level.storage.WorldData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -16,8 +24,10 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; +import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.recipes.BCLRecipeManager; +import java.net.Proxy; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -34,7 +44,10 @@ public class MinecraftServerMixin { @Final @Shadow protected WorldData worldData; - + @Inject(method = "*", at = @At("TAIL")) + private void bclib_onServerInit(Thread thread, RegistryHolder registryHolder, LevelStorageAccess levelStorageAccess, WorldData worldData, PackRepository packRepository, Proxy proxy, DataFixer dataFixer, ServerResources serverResources, MinecraftSessionService minecraftSessionService, GameProfileRepository gameProfileRepository, GameProfileCache gameProfileCache, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci){ + DataExchangeAPI.prepareServerside(); + } @Inject(method="convertFromRegionFormatIfNeeded", at = @At("HEAD")) private static void bclib_applyPatches(LevelStorageSource.LevelStorageAccess session, CallbackInfo ci){ diff --git a/src/main/java/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index 9568a169..d4011c97 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -9,7 +9,7 @@ public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); - DataExchangeAPI.registerServersideHandler(TestHandler.DESCRIPTOR); + DataExchangeAPI.prepareServerside(); PostInitAPI.postInit(false); } From b74f680191ef253dec1df0f9212d5e4b99402f3d Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 29 Jul 2021 10:57:58 +0200 Subject: [PATCH 0128/1033] Added HelloServer handler --- src/main/java/ru/bclib/BCLib.java | 4 +- .../api/dataexchange/DataExchangeAPI.java | 28 +++++++++- .../bclib/api/dataexchange/TestHandler.java | 40 ------------- .../api/dataexchange/handler/HelloServer.java | 56 +++++++++++++++++++ 4 files changed, 85 insertions(+), 43 deletions(-) delete mode 100644 src/main/java/ru/bclib/api/dataexchange/TestHandler.java create mode 100644 src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index 6eb2634c..15f4b841 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -7,7 +7,7 @@ import net.minecraft.resources.ResourceLocation; import ru.bclib.api.TagAPI; import ru.bclib.api.WorldDataAPI; import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.TestHandler; +import ru.bclib.api.dataexchange.handler.HelloServer; import ru.bclib.config.Configs; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; @@ -28,7 +28,7 @@ public class BCLib implements ModInitializer { CraftingRecipes.init(); WorldDataAPI.registerModCache(MOD_ID); Configs.save(); - DataExchangeAPI.registerDescriptor(TestHandler.DESCRIPTOR); + DataExchangeAPI.registerDescriptor(HelloServer.DESCRIPTOR); } public static boolean isDevEnvironment() { diff --git a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java index 375103b0..3796160a 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java @@ -4,6 +4,7 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; +import net.minecraft.network.FriendlyByteBuf; import java.util.HashSet; import java.util.Set; @@ -19,7 +20,7 @@ public class DataExchangeAPI { descriptors = new HashSet<>(); } - public static DataExchangeAPI getInstance(){ + static DataExchangeAPI getInstance(){ if (instance==null){ instance = new DataExchangeAPI(); } @@ -45,12 +46,21 @@ public class DataExchangeAPI { ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); } + /** + * Add a new Descriptor for a DataHandler. + * @param desc The Descriptor you want to add. + */ public static void registerDescriptor(DataHandlerDescriptor desc){ DataExchangeAPI api = DataExchangeAPI.getInstance(); api.descriptors.add(desc); } + /** + * Initializes all datastructures that need to exist in the client component. + *

    + * This is automatically called by BCLib. You can register {@link DataHandler}-Objects before this Method is called + */ @Environment(EnvType.CLIENT) public static void prepareClientside(){ DataExchangeAPI api = DataExchangeAPI.getInstance(); @@ -58,11 +68,27 @@ public class DataExchangeAPI { } + /** + * Initializes all datastructures that need to exist in the server component. + *

    + * This is automatically called by BCLib. You can register {@link DataHandler}-Objects before this Method is called + */ public static void prepareServerside(){ DataExchangeAPI api = DataExchangeAPI.getInstance(); api.initServerSide(); } + + /** + * Sends the Handler. + *

    + * Depending on what the result of {@link DataHandler#getOriginatesOnServer()}, the Data is sent from the server + * to the client (if {@code true}) or the other way around. + *

    + * The method {@link DataHandler#serializeData(FriendlyByteBuf)} is called just before the data is sent. You should + * use this method to add the Data you need to the communication. + * @param h The Data that you want to send + */ public static void send(DataHandler h){ if (h.getOriginatesOnServer()){ DataExchangeAPI.getInstance().server.sendToClient(h); diff --git a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java b/src/main/java/ru/bclib/api/dataexchange/TestHandler.java deleted file mode 100644 index d55612ad..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/TestHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import ru.bclib.BCLib; - -import java.nio.charset.StandardCharsets; - -public class TestHandler extends DataHandler{ - public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "__test"), TestHandler::new, true); - - public TestHandler() { - super(DESCRIPTOR.IDENTIFIER, true); - } - - @Override - protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient) { - int length = buf.readInt(); - CharSequence text = buf.readCharSequence(length, StandardCharsets.UTF_8); - BCLib.LOGGER.info("PROCESSING INCOMING TEST-DATA fromClient="+fromClient+": "+text); - } - - @Override - @Environment(EnvType.CLIENT) - protected void runOnClient(Minecraft client) { - BCLib.LOGGER.info("RUNNING INCOMING TEST-DATA ON CLIENT"); - } - - @Override - protected void serializeData(FriendlyByteBuf buf) { - CharSequence text = "Welcome from BCLib"; - buf.writeInt(text.length()); - buf.writeCharSequence(text, StandardCharsets.UTF_8); - BCLib.LOGGER.info("BUILDING OUTGOING TEST-DATA ON SERVER"); - } -} diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java b/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java new file mode 100644 index 00000000..571de6d5 --- /dev/null +++ b/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java @@ -0,0 +1,56 @@ +package ru.bclib.api.dataexchange.handler; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import ru.bclib.BCLib; +import ru.bclib.api.dataexchange.DataHandler; +import ru.bclib.api.dataexchange.DataHandlerDescriptor; +import ru.bclib.api.datafixer.DataFixerAPI; + +import java.util.Optional; + +public class HelloServer extends DataHandler { + public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "hello_server"), HelloServer::new, true); + + public HelloServer() { + super(DESCRIPTOR.IDENTIFIER, false); + } + + public static String getModVersion(String modID){ + Optional optional = FabricLoader.getInstance().getModContainer(modID); + if (optional.isPresent()) { + ModContainer modContainer = optional.get(); + return modContainer.getMetadata().getVersion().toString(); + } + return "0.0.0"; + } + + protected static String getBCLibVersion(){ + return getModVersion(BCLib.MOD_ID); + } + + @Override + protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient) { + String bclibVersion = DataFixerAPI.getModVersion(buf.readInt()); + String localBclibVersion = getBCLibVersion(); + + BCLib.LOGGER.info("Hello Server received from BCLib. (server="+localBclibVersion+", client="+bclibVersion+")"); + } + + @Override + @Environment(EnvType.CLIENT) + protected void runOnClient(Minecraft client) { + + } + + @Override + protected void serializeData(FriendlyByteBuf buf) { + buf.writeInt(DataFixerAPI.getModVersion(getBCLibVersion())); + } +} From 56bbc9346037bc83feaa9b042b6c8d2e696764a3 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 29 Jul 2021 11:29:29 +0200 Subject: [PATCH 0129/1033] Reverted wrong additions to WoodenMaterial --- .../WoodenComplexMaterial.java | 31 ++++++------------- 1 file changed, 9 insertions(+), 22 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index a4d9abe4..44766676 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -1,6 +1,5 @@ package ru.bclib.complexmaterials; -import com.google.common.collect.Lists; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; @@ -36,14 +35,9 @@ import ru.bclib.blocks.BaseWoodenButtonBlock; import ru.bclib.blocks.StripableBarkBlock; import ru.bclib.blocks.WoodenPressurePlateBlock; import ru.bclib.complexmaterials.entry.BlockEntry; -import ru.bclib.complexmaterials.entry.ItemEntry; import ru.bclib.complexmaterials.entry.RecipeEntry; -import ru.bclib.config.PathConfig; import ru.bclib.recipes.GridRecipe; -import java.util.Arrays; -import java.util.List; - public class WoodenComplexMaterial extends ComplexMaterial { public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); @@ -97,14 +91,8 @@ public class WoodenComplexMaterial extends ComplexMaterial { @Override protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - initDefault(blockSettings, itemSettings, new String[0]); - } - - final protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings, String[] excludedSuffixes) { Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); Tag.Named tagItemLog = getItemTag(TAG_LOGS); - List excl = Arrays.asList(excludedSuffixes); - addBlockEntry( new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { @@ -181,17 +169,16 @@ public class WoodenComplexMaterial extends ComplexMaterial { return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); })); - if (!excl.contains(BLOCK_BOOKSHELF)) { - addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { - return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - } - if (!excl.contains(BLOCK_COMPOSTER)) { - addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { - return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); - })); - } + addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { + return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); + + + + addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { + return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); + })); } @Override From 6b3957d04a92507a797f07b37e4f733ffddc29bb Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 29 Jul 2021 11:56:19 +0200 Subject: [PATCH 0130/1033] Fixed Shulker Recipe --- .../java/ru/bclib/complexmaterials/WoodenComplexMaterial.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 44766676..f3ba9e5a 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -374,7 +374,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .build(); })); addRecipeEntry(new RecipeEntry("shulker", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) + GridRecipe.make(id, Blocks.SHULKER_BOX) .checkConfig(config) .setShape("S", "#", "S") .addMaterial('S', Items.SHULKER_SHELL) From dca77a58aebf748a2cfb57e9e79ab44e9dfad060 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Thu, 29 Jul 2021 12:10:55 +0200 Subject: [PATCH 0131/1033] separated different initStages --- .../WoodenComplexMaterial.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index f3ba9e5a..8e24cc0c 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -91,6 +91,12 @@ public class WoodenComplexMaterial extends ComplexMaterial { @Override protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + initBase(blockSettings, itemSettings); + initStorage(blockSettings, itemSettings); + initDecorations(blockSettings, itemSettings); + } + + protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); Tag.Named tagItemLog = getItemTag(TAG_LOGS); @@ -152,9 +158,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { return new BaseDoorBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS).setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); - addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { - return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); + addBlockEntry(new BlockEntry(BLOCK_LADDER, (complexMaterial, settings) -> { return new BaseLadderBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.CLIMBABLE)); @@ -162,20 +166,27 @@ public class WoodenComplexMaterial extends ComplexMaterial { return new BaseSignBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(BlockTags.SIGNS).setItemTags(ItemTags.SIGNS)); + + } + + protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { return new BaseChestBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); })); - + } + + protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ + addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { + return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); + }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - - - + addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); })); From d33187d20425b274e6eacbcde8ff340c88e90637 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 10:17:53 +0200 Subject: [PATCH 0132/1033] added `receipeGroupPrefix` otherwise everything will have the end-group --- .../complexmaterials/ComplexMaterial.java | 4 ++- .../WoodenComplexMaterial.java | 34 +++++++++---------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index b5fceada..88d5621c 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -38,10 +38,12 @@ public abstract class ComplexMaterial { protected final String baseName; protected final String modID; + protected final String receipGroupPrefix; - public ComplexMaterial(String modID, String baseName) { + public ComplexMaterial(String modID, String baseName, String receipGroupPrefix) { this.baseName = baseName; this.modID = modID; + this.receipGroupPrefix = receipGroupPrefix; MATERIALS.add(this); } diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 8e24cc0c..cf7f2f9a 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -67,8 +67,8 @@ public class WoodenComplexMaterial extends ComplexMaterial { public final MaterialColor planksColor; public final MaterialColor woodColor; - public WoodenComplexMaterial(String modID, String baseName, MaterialColor woodColor, MaterialColor planksColor) { - super(modID, baseName); + public WoodenComplexMaterial(String modID, String baseName, String receipGroupPrefix, MaterialColor woodColor, MaterialColor planksColor) { + super(modID, baseName, receipGroupPrefix); this.planksColor = planksColor; this.woodColor = woodColor; } @@ -217,7 +217,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setOutputCount(4) .setList("#") .addMaterial('#', log, bark, log_stripped, bark_stripped) - .setGroup("end_planks") + .setGroup(receipGroupPrefix +"_planks") .build(); })); addRecipeEntry(new RecipeEntry("stairs", (material, config, id) -> { @@ -226,7 +226,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setOutputCount(4) .setShape("# ", "## ", "###") .addMaterial('#', planks) - .setGroup("end_planks_stairs") + .setGroup(receipGroupPrefix +"_planks_stairs") .build(); })); addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { @@ -235,7 +235,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setOutputCount(6) .setShape("###") .addMaterial('#', planks) - .setGroup("end_planks_slabs") + .setGroup(receipGroupPrefix +"_planks_slabs") .build(); })); addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { @@ -245,7 +245,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("#I#", "#I#") .addMaterial('#', planks) .addMaterial('I', Items.STICK) - .setGroup("end_planks_fences") + .setGroup(receipGroupPrefix +"_planks_fences") .build(); })); addRecipeEntry(new RecipeEntry("gate", (material, config, id) -> { @@ -254,7 +254,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("I#I", "I#I") .addMaterial('#', planks) .addMaterial('I', Items.STICK) - .setGroup("end_planks_gates") + .setGroup(receipGroupPrefix +"_planks_gates") .build(); })); addRecipeEntry(new RecipeEntry("button", (material, config, id) -> { @@ -262,7 +262,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .checkConfig(config) .setList("#") .addMaterial('#', planks) - .setGroup("end_planks_buttons") + .setGroup(receipGroupPrefix +"_planks_buttons") .build(); })); addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { @@ -270,7 +270,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .checkConfig(config) .setShape("##") .addMaterial('#', planks) - .setGroup("end_planks_plates") + .setGroup(receipGroupPrefix +"_planks_plates") .build(); })); addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { @@ -279,7 +279,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setOutputCount(2) .setShape("###", "###") .addMaterial('#', planks) - .setGroup("end_trapdoors") + .setGroup(receipGroupPrefix +"_trapdoors") .build(); })); addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { @@ -288,7 +288,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setOutputCount(3) .setShape("##", "##", "##") .addMaterial('#', planks) - .setGroup("end_doors") + .setGroup(receipGroupPrefix +"_doors") .build(); })); addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { @@ -296,7 +296,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .checkConfig(config) .setShape("##", "##") .addMaterial('#', planks) - .setGroup("end_tables") + .setGroup(receipGroupPrefix +"_tables") .build(); })); addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { @@ -306,7 +306,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("I I", "I#I", "I I") .addMaterial('#', planks) .addMaterial('I', Items.STICK) - .setGroup("end_ladders") + .setGroup(receipGroupPrefix +"_ladders") .build(); })); addRecipeEntry(new RecipeEntry("sign", (material, config, id) -> { @@ -316,7 +316,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("###", "###", " I ") .addMaterial('#', planks) .addMaterial('I', Items.STICK) - .setGroup("end_signs") + .setGroup(receipGroupPrefix +"_signs") .build(); })); addRecipeEntry(new RecipeEntry("chest", (material, config, id) -> { @@ -324,7 +324,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .checkConfig(config) .setShape("###", "# #", "###") .addMaterial('#', planks) - .setGroup("end_chests") + .setGroup(receipGroupPrefix +"_chests") .build(); })); addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { @@ -333,7 +333,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("#S#", "# #", "#S#") .addMaterial('#', planks) .addMaterial('S', getBlock(BLOCK_SLAB)) - .setGroup("end_barrels") + .setGroup(receipGroupPrefix +"_barrels") .build(); })); addRecipeEntry(new RecipeEntry("bookshelf", (material, config, id) -> { @@ -342,7 +342,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { .setShape("###", "PPP", "###") .addMaterial('#', planks) .addMaterial('P', Items.BOOK) - .setGroup("end_bookshelves") + .setGroup(receipGroupPrefix +"_bookshelves") .build(); })); addRecipeEntry(new RecipeEntry("bark", (material, config, id) -> { From 2f1a4e9518b6032422353768b298549ee1071f20 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 10:18:31 +0200 Subject: [PATCH 0133/1033] seperated `initDefault` into three stages. Allows easier cosumization of wood materials --- .../ru/bclib/complexmaterials/WoodenComplexMaterial.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index cf7f2f9a..53b7ba7d 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -96,7 +96,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { initDecorations(blockSettings, itemSettings); } - protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { + final protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); Tag.Named tagItemLog = getItemTag(TAG_LOGS); @@ -169,7 +169,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { } - protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ + final protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { return new BaseChestBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_CHEST).setItemTags(TagAPI.ITEM_CHEST)); @@ -178,7 +178,7 @@ public class WoodenComplexMaterial extends ComplexMaterial { })); } - protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ + final protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings){ addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); }).setBlockTags(TagAPI.BLOCK_WORKBENCHES).setItemTags(TagAPI.ITEM_WORKBENCHES)); From fdcb5ad03a35086c44366340041f0063eb47b93a Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 30 Jul 2021 14:41:04 +0300 Subject: [PATCH 0134/1033] Model loading changes --- .../bclib/interfaces/BlockModelProvider.java | 1 + .../bclib/mixin/client/ModelBakeryMixin.java | 150 ++++++++---------- 2 files changed, 67 insertions(+), 84 deletions(-) diff --git a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java index 26ba723c..5b4a6a86 100644 --- a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java +++ b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java @@ -1,5 +1,6 @@ package ru.bclib.interfaces; +import com.google.common.collect.Maps; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index 065c2b0c..16326ea7 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -1,121 +1,103 @@ package ru.bclib.mixin.client; +import com.google.common.collect.Maps; +import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.renderer.block.model.multipart.MultiPart; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.item.Items; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import ru.bclib.BCLib; import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.ItemModelProvider; -import java.util.List; import java.util.Map; -import java.util.Optional; @Mixin(ModelBakery.class) public abstract class ModelBakeryMixin { @Final @Shadow - private ResourceManager resourceManager; + private Map unbakedCache; @Final @Shadow - private Map unbakedCache; + private Map topLevelModels; - @Shadow - protected abstract void cacheAndQueueDependencies(ResourceLocation resourceLocation, UnbakedModel unbakedModel); + //private Map cache = Maps.newHashMap(); + //private Map topLevel = Maps.newHashMap(); - @Inject(method = "loadModel", at = @At("HEAD"), cancellable = true) - private void bclib_loadModels(ResourceLocation resourceLocation, CallbackInfo info) { - if (resourceLocation instanceof ModelResourceLocation) { - String modId = resourceLocation.getNamespace(); - String path = resourceLocation.getPath(); - ResourceLocation clearLoc = new ResourceLocation(modId, path); - ModelResourceLocation modelId = (ModelResourceLocation) resourceLocation; - if ("inventory".equals(modelId.getVariant())) { - ResourceLocation itemLoc = new ResourceLocation(modId, "item/" + path); - ResourceLocation itemModelLoc = new ResourceLocation(modId, "models/" + itemLoc.getPath() + ".json"); - if (!resourceManager.hasResource(itemModelLoc)) { - Item item = Registry.ITEM.get(clearLoc); - ItemModelProvider modelProvider = null; - if (item instanceof ItemModelProvider) { - modelProvider = (ItemModelProvider) item; - } - else if (item instanceof BlockItem) { - Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof ItemModelProvider) { - modelProvider = (ItemModelProvider) block; - } - } - if (modelProvider != null) { - BlockModel model = modelProvider.getItemModel(clearLoc); - if (model != null) { - model.name = itemLoc.toString(); - cacheAndQueueDependencies(modelId, model); - unbakedCache.put(itemLoc, model); - } - else { - BCLib.LOGGER.warning("Error loading model: {}", itemLoc); - } - info.cancel(); + @Inject( + method = "*", + at = @At( + value = "INVOKE_STRING", + target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", + args = "ldc=static_definitions", + shift = Shift.BEFORE + ) + ) + private void bclib_initCustomModels(ResourceManager resourceManager, BlockColors blockColors, ProfilerFiller profiler, int mipmap, CallbackInfo info) { + Map cache = Maps.newHashMap(); + Map topLevel = Maps.newHashMap(); + + Registry.BLOCK.forEach(block -> { + if (block instanceof BlockModelProvider) { + ResourceLocation blockID = Registry.BLOCK.getKey(block); + ResourceLocation storageID = new ResourceLocation(blockID.getNamespace(), "blockstates/" + blockID.getPath() + ".json"); + BlockModelProvider provider = (BlockModelProvider) block; + + if (!resourceManager.hasResource(storageID)) { + BlockState defaultState = block.defaultBlockState(); + ResourceLocation defaultStateID = BlockModelShaper.stateToModelLocation(blockID, defaultState); + + UnbakedModel defaultModel = provider.getModelVariant(defaultStateID, defaultState, cache); + cache.put(blockID, defaultModel); + topLevel.put(blockID, defaultModel); + + block.getStateDefinition().getPossibleStates().forEach(blockState -> { + ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, blockState); + BlockModel model = provider.getBlockModel(stateID, blockState); + cache.put(stateID, model != null ? model : defaultModel); + }); + } + + if (Registry.ITEM.get(blockID) != Items.AIR) { + storageID = new ResourceLocation(blockID.getNamespace(), "models/item/" + blockID.getPath() + ".json"); + if (!resourceManager.hasResource(storageID)) { + ResourceLocation itemID = new ModelResourceLocation(blockID.getNamespace(), blockID.getPath(), "inventory"); + BlockModel model = provider.getItemModel(itemID); + cache.put(itemID, model); + topLevel.put(itemID, model); } } } - else { - ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); - if (!resourceManager.hasResource(stateLoc)) { - Block block = Registry.BLOCK.get(clearLoc); - if (block instanceof BlockModelProvider) { - List possibleStates = block.getStateDefinition().getPossibleStates(); - Optional possibleState = possibleStates.stream() - .filter(state -> modelId.equals( - BlockModelShaper.stateToModelLocation( - clearLoc, - state - ))) - .findFirst(); - if (possibleState.isPresent()) { - UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant( - modelId, - possibleState.get(), - unbakedCache - ); - if (modelVariant != null) { - if (modelVariant instanceof MultiPart) { - possibleStates.forEach(state -> { - ResourceLocation stateId = BlockModelShaper.stateToModelLocation( - clearLoc, - state - ); - cacheAndQueueDependencies(stateId, modelVariant); - }); - } - else { - cacheAndQueueDependencies(modelId, modelVariant); - } - } - else { - BCLib.LOGGER.warning("Error loading variant: {}", modelId); - } - info.cancel(); - } - } + }); + + Registry.ITEM.forEach(item -> { + if (item instanceof ItemModelProvider) { + ResourceLocation registryID = Registry.ITEM.getKey(item); + ResourceLocation storageID = new ResourceLocation(registryID.getNamespace(), "models/item/" + registryID.getPath() + ".json"); + if (!resourceManager.hasResource(storageID)) { + ResourceLocation itemID = new ModelResourceLocation(registryID.getNamespace(), registryID.getPath(), "inventory"); + ItemModelProvider provider = (ItemModelProvider) item; + BlockModel model = provider.getItemModel(registryID); + cache.put(itemID, model); + topLevel.put(itemID, model); } } - } + }); + + topLevelModels.putAll(topLevel); + unbakedCache.putAll(cache); } } From 2e624956aa6e548310ba42871af5e5f807bd7c6c Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 13:49:12 +0200 Subject: [PATCH 0135/1033] Reenable FixerAPI --- src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index 6f995919..d5c879fc 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -242,9 +242,6 @@ public class DataFixerAPI { } private static void runDataFixes(File dir, MigrationProfile profile, ProgressListener progress) { - System.out.println("RUNNING fixes"); - if (dir!= null) return; - State state = new State(); List regions = getAllRegions(dir, null); From 37348ccb0e9850de7f1dbe6f91246b0d51677050 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 14:49:14 +0200 Subject: [PATCH 0136/1033] enable replacement of predefined types --- .../ru/bclib/complexmaterials/ComplexMaterial.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 88d5621c..b4a3f633 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -250,6 +250,20 @@ public abstract class ComplexMaterial { defaultBlockEntries.add(entry); } + /** + * Replaces or Adds a default {@link BlockEntry} to this {@link ComplexMaterial}. Used to initiate blocks later. + *

    + * If this {@link ComplexMaterial} does already contain an entry for the {@link ResourceLocation}, the entry will + * be removed first. + * @param entry {@link BlockEntry} + */ + protected void replaceOrAddBlockEntry(BlockEntry entry) { + int pos = defaultBlockEntries.indexOf(entry); + if (pos>=0) defaultBlockEntries.remove(entry); + + addBlockEntry(entry); + } + /** * Adds a default {@link ItemEntry} to this {@link ComplexMaterial}. Used to initiate items later. * @param entry {@link ItemEntry} From 0e2f876cd4a415650f89b0a2c336224362e0b4b9 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 14:52:33 +0200 Subject: [PATCH 0137/1033] add `equals` and `hashCode` to `ComplexMaterialEntry` --- .../entry/ComplexMaterialEntry.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java index 3a1cf5fa..d2158e7f 100644 --- a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java +++ b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java @@ -1,8 +1,12 @@ package ru.bclib.complexmaterials.entry; import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; public abstract class ComplexMaterialEntry { + @NotNull private final String suffix; protected ComplexMaterialEntry(String suffix) { @@ -20,4 +24,17 @@ public abstract class ComplexMaterialEntry { public String getSuffix() { return suffix; } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ComplexMaterialEntry that = (ComplexMaterialEntry) o; + return suffix.equals(that.suffix); + } + + @Override + public int hashCode() { + return Objects.hash(suffix); + } } From 032b4187bd342fc04cf25cb27653a9fbea9318a3 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 15:02:06 +0200 Subject: [PATCH 0138/1033] Replaced string with constant value --- .../java/ru/bclib/complexmaterials/WoodenComplexMaterial.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 53b7ba7d..97a54004 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -117,14 +117,14 @@ public class WoodenComplexMaterial extends ComplexMaterial { addBlockEntry( new BlockEntry(BLOCK_LOG, (complexMaterial, settings) -> { - return new BaseStripableLogBlock(woodColor, getBlock("stripped_log")); + return new BaseStripableLogBlock(woodColor, getBlock(BLOCK_STRIPPED_LOG)); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) ); addBlockEntry( new BlockEntry(BLOCK_BARK, (complexMaterial, settings) -> { - return new StripableBarkBlock(woodColor, getBlock("stripped_bark")); + return new StripableBarkBlock(woodColor, getBlock(BLOCK_STRIPPED_BARK)); }) .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) From a53c503c4e9fbaa51e168bcf72afd43bc66af130 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Fri, 30 Jul 2021 17:30:19 +0200 Subject: [PATCH 0139/1033] List all mod versions from server and client --- src/main/java/ru/bclib/api/WorldDataAPI.java | 4 ++ .../api/dataexchange/DataExchangeAPI.java | 20 ++++++++++ .../bclib/api/dataexchange/DataHandler.java | 23 +++++++++++ .../api/dataexchange/handler/HelloServer.java | 40 ++++++++++++++++--- 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index 78bbd980..477807b7 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -8,6 +8,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; import ru.bclib.BCLib; +import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.api.datafixer.DataFixerAPI; import java.io.File; @@ -62,11 +63,14 @@ public class WorldDataAPI { /** * Register mod cache, world cache is located in world data folder. + *

    + * Will also register the Mod for the {@link DataExchangeAPI} using {@link DataExchangeAPI#registerMod(String)} * * @param modID - {@link String} modID. */ public static void registerModCache(String modID) { MODS.add(modID); + DataExchangeAPI.registerMod(modID); } /** diff --git a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java index 3796160a..73cac348 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java @@ -1,5 +1,6 @@ package ru.bclib.api.dataexchange; +import com.google.common.collect.Lists; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; @@ -7,9 +8,11 @@ import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.minecraft.network.FriendlyByteBuf; import java.util.HashSet; +import java.util.List; import java.util.Set; public class DataExchangeAPI { + private final static List MODS = Lists.newArrayList(); private static DataExchangeAPI instance; private ConnectorServerside server; private ConnectorClientside client; @@ -46,6 +49,23 @@ public class DataExchangeAPI { ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); } + /** + * Register a mod to participate in the DataExchange. + * + * @param modID - {@link String} modID. + */ + public static void registerMod(String modID) { + MODS.add(modID); + } + + /** + * Returns the IDs of all registered Mods. + * @return List of modIDs + */ + public static List registeredMods(){ + return MODS; + } + /** * Add a new Descriptor for a DataHandler. * @param desc The Descriptor you want to add. diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java index ece8b021..0005ced8 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java @@ -1,5 +1,7 @@ package ru.bclib.api.dataexchange; +import io.netty.buffer.ByteBufUtil; +import io.netty.util.CharsetUtil; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; @@ -16,6 +18,8 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.jetbrains.annotations.NotNull; +import java.nio.charset.StandardCharsets; + public abstract class DataHandler { private final boolean originatesOnServer; @NotNull @@ -104,4 +108,23 @@ public abstract class DataHandler { public String toString() { return "DataHandler{" + "originatesOnServer=" + originatesOnServer + ", identifier=" + identifier + '}'; } + + /** + * Write a String to a buffer (Convenience Method) + * @param buf The buffer to write to + * @param s The String you want to write + */ + public static void writeString(FriendlyByteBuf buf, String s){ + buf.writeByteArray(s.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Read a string from a buffer (Convenience Method) + * @param buf Thea buffer to read from + * @return The received String + */ + public static String readString(FriendlyByteBuf buf){ + byte[] data = buf.readByteArray(); + return new String(data, StandardCharsets.UTF_8); + } } diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java b/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java index 571de6d5..13b2fe02 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java @@ -1,5 +1,7 @@ package ru.bclib.api.dataexchange.handler; +import io.netty.buffer.ByteBufUtil; +import io.netty.util.CharsetUtil; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.networking.v1.PacketSender; @@ -8,11 +10,18 @@ import net.fabricmc.loader.api.ModContainer; import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; import ru.bclib.BCLib; +import ru.bclib.api.WorldDataAPI; +import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.api.dataexchange.DataHandler; import ru.bclib.api.dataexchange.DataHandlerDescriptor; import ru.bclib.api.datafixer.DataFixerAPI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import java.util.Optional; public class HelloServer extends DataHandler { @@ -35,22 +44,41 @@ public class HelloServer extends DataHandler { return getModVersion(BCLib.MOD_ID); } + String bclibVersion ="0.0.0"; + Map modVersion = new HashMap<>(); @Override protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient) { - String bclibVersion = DataFixerAPI.getModVersion(buf.readInt()); - String localBclibVersion = getBCLibVersion(); + bclibVersion = DataFixerAPI.getModVersion(buf.readInt()); + modVersion = new HashMap<>(); - BCLib.LOGGER.info("Hello Server received from BCLib. (server="+localBclibVersion+", client="+bclibVersion+")"); + int count = buf.readInt(); + for (int i=0; i< count; i++){ + String id = readString(buf); + String version = DataFixerAPI.getModVersion(buf.readInt()); + modVersion.put(id, version); + } } @Override - @Environment(EnvType.CLIENT) - protected void runOnClient(Minecraft client) { - + protected void runOnServer(MinecraftServer server) { + String localBclibVersion = getBCLibVersion(); + BCLib.LOGGER.info("Hello Server received from BCLib. (server="+localBclibVersion+", client="+bclibVersion+")"); + + for (Entry e : modVersion.entrySet()){ + String ver = getModVersion(e.getKey()); + BCLib.LOGGER.info(" - " + e.getKey() + " (server="+ver+", client="+ver+")"); + } } @Override protected void serializeData(FriendlyByteBuf buf) { + final List mods = DataExchangeAPI.registeredMods(); buf.writeInt(DataFixerAPI.getModVersion(getBCLibVersion())); + + buf.writeInt(mods.size()); + for (String modID : mods) { + writeString(buf, modID); + buf.writeInt(DataFixerAPI.getModVersion(getModVersion(modID))); + } } } From 6a1ab89e3900870296fc4f6ce6ed398768b08e1f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 30 Jul 2021 20:44:34 +0300 Subject: [PATCH 0140/1033] Terrain block small fixes --- .../java/ru/bclib/blocks/BaseTerrainBlock.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index cd53cc56..e77d8f9f 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -46,15 +46,16 @@ import java.util.Random; @SuppressWarnings("deprecation") public class BaseTerrainBlock extends BaseBlock { - private final Block baseBlock; private Block pathBlock; public BaseTerrainBlock(Block baseBlock, MaterialColor color) { - super(FabricBlockSettings.copyOf(baseBlock) - .materialColor(color) - .sound(BlockSounds.TERRAIN_SOUND) - .randomTicks()); + super(FabricBlockSettings + .copyOf(baseBlock) + .materialColor(color) + .sound(BlockSounds.TERRAIN_SOUND) + .randomTicks() + ); this.baseBlock = baseBlock; } @@ -93,7 +94,7 @@ public class BaseTerrainBlock extends BaseBlock { @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { if (random.nextInt(16) == 0 && !canStay(state, world, pos)) { - world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); + world.setBlockAndUpdate(pos, getBaseBlock().defaultBlockState()); } } @@ -129,7 +130,7 @@ public class BaseTerrainBlock extends BaseBlock { @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation baseId = Registry.BLOCK.getKey(baseBlock); + ResourceLocation baseId = Registry.BLOCK.getKey(getBaseBlock()); String modId = blockId.getNamespace(); String path = blockId.getPath(); String bottom = baseId.getNamespace() + ":block/" + baseId.getPath(); From b5ebabd824bb0ae403b82729dfd577336aeef201 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 30 Jul 2021 20:45:56 +0300 Subject: [PATCH 0141/1033] Another terrain block small fix --- src/main/java/ru/bclib/blocks/BaseTerrainBlock.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index e77d8f9f..96b77c0e 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -88,7 +88,7 @@ public class BaseTerrainBlock extends BaseBlock { if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Collections.singletonList(new ItemStack(this)); } - return Collections.singletonList(new ItemStack(Blocks.END_STONE)); + return Collections.singletonList(new ItemStack(getBaseBlock())); } @Override From 185da209ce4ee194be2425404d3d3d9bcea6dd3f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 30 Jul 2021 21:11:55 +0300 Subject: [PATCH 0142/1033] Parallel model loading --- .../bclib/mixin/client/ModelBakeryMixin.java | 57 +++++++++++-------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index 16326ea7..48974c90 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -1,5 +1,6 @@ package ru.bclib.mixin.client; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.block.BlockModelShaper; @@ -47,38 +48,44 @@ public abstract class ModelBakeryMixin { ) ) private void bclib_initCustomModels(ResourceManager resourceManager, BlockColors blockColors, ProfilerFiller profiler, int mipmap, CallbackInfo info) { - Map cache = Maps.newHashMap(); - Map topLevel = Maps.newHashMap(); + Map cache = Maps.newConcurrentMap(); + Map topLevel = Maps.newConcurrentMap(); - Registry.BLOCK.forEach(block -> { - if (block instanceof BlockModelProvider) { - ResourceLocation blockID = Registry.BLOCK.getKey(block); - ResourceLocation storageID = new ResourceLocation(blockID.getNamespace(), "blockstates/" + blockID.getPath() + ".json"); - BlockModelProvider provider = (BlockModelProvider) block; + Registry.BLOCK.stream().filter(block -> block instanceof BlockModelProvider).parallel().forEach(block -> { + ResourceLocation blockID = Registry.BLOCK.getKey(block); + ResourceLocation storageID = new ResourceLocation(blockID.getNamespace(), "blockstates/" + blockID.getPath() + ".json"); + BlockModelProvider provider = (BlockModelProvider) block; + + if (!resourceManager.hasResource(storageID)) { + BlockState defaultState = block.defaultBlockState(); + ResourceLocation defaultStateID = BlockModelShaper.stateToModelLocation(blockID, defaultState); - if (!resourceManager.hasResource(storageID)) { - BlockState defaultState = block.defaultBlockState(); - ResourceLocation defaultStateID = BlockModelShaper.stateToModelLocation(blockID, defaultState); - - UnbakedModel defaultModel = provider.getModelVariant(defaultStateID, defaultState, cache); - cache.put(blockID, defaultModel); - topLevel.put(blockID, defaultModel); - - block.getStateDefinition().getPossibleStates().forEach(blockState -> { + UnbakedModel defaultModel = provider.getModelVariant(defaultStateID, defaultState, cache); + cache.put(blockID, defaultModel); + topLevel.put(blockID, defaultModel); + + ImmutableList states = block.getStateDefinition().getPossibleStates(); + if (states.size() == 1) { + ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, block.defaultBlockState()); + cache.put(stateID, defaultModel); + topLevel.put(stateID, defaultModel); + } + else { + states.forEach(blockState -> { ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, blockState); BlockModel model = provider.getBlockModel(stateID, blockState); cache.put(stateID, model != null ? model : defaultModel); }); } - - if (Registry.ITEM.get(blockID) != Items.AIR) { - storageID = new ResourceLocation(blockID.getNamespace(), "models/item/" + blockID.getPath() + ".json"); - if (!resourceManager.hasResource(storageID)) { - ResourceLocation itemID = new ModelResourceLocation(blockID.getNamespace(), blockID.getPath(), "inventory"); - BlockModel model = provider.getItemModel(itemID); - cache.put(itemID, model); - topLevel.put(itemID, model); - } + } + + if (Registry.ITEM.get(blockID) != Items.AIR) { + storageID = new ResourceLocation(blockID.getNamespace(), "models/item/" + blockID.getPath() + ".json"); + if (!resourceManager.hasResource(storageID)) { + ResourceLocation itemID = new ModelResourceLocation(blockID.getNamespace(), blockID.getPath(), "inventory"); + BlockModel model = provider.getItemModel(itemID); + cache.put(itemID, model); + topLevel.put(itemID, model); } } }); From 05b89607a591b69eb792a307d129e267410dcb21 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Fri, 30 Jul 2021 21:13:05 +0300 Subject: [PATCH 0143/1033] Item parallel model loading --- .../bclib/mixin/client/ModelBakeryMixin.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index 48974c90..f3951497 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -90,17 +90,15 @@ public abstract class ModelBakeryMixin { } }); - Registry.ITEM.forEach(item -> { - if (item instanceof ItemModelProvider) { - ResourceLocation registryID = Registry.ITEM.getKey(item); - ResourceLocation storageID = new ResourceLocation(registryID.getNamespace(), "models/item/" + registryID.getPath() + ".json"); - if (!resourceManager.hasResource(storageID)) { - ResourceLocation itemID = new ModelResourceLocation(registryID.getNamespace(), registryID.getPath(), "inventory"); - ItemModelProvider provider = (ItemModelProvider) item; - BlockModel model = provider.getItemModel(registryID); - cache.put(itemID, model); - topLevel.put(itemID, model); - } + Registry.ITEM.stream().filter(item -> item instanceof ItemModelProvider).parallel().forEach(item -> { + ResourceLocation registryID = Registry.ITEM.getKey(item); + ResourceLocation storageID = new ResourceLocation(registryID.getNamespace(), "models/item/" + registryID.getPath() + ".json"); + if (!resourceManager.hasResource(storageID)) { + ResourceLocation itemID = new ModelResourceLocation(registryID.getNamespace(), registryID.getPath(), "inventory"); + ItemModelProvider provider = (ItemModelProvider) item; + BlockModel model = provider.getItemModel(registryID); + cache.put(itemID, model); + topLevel.put(itemID, model); } }); From 24ce3fa4e863a137d29ed6ed3d083ffd3841cf8f Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 31 Jul 2021 09:22:21 +0300 Subject: [PATCH 0144/1033] CTM compat fix --- .../bclib/interfaces/BlockModelProvider.java | 1 - .../bclib/mixin/client/ModelBakeryMixin.java | 19 ++++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java index 5b4a6a86..3b6f0f71 100644 --- a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java +++ b/src/main/java/ru/bclib/interfaces/BlockModelProvider.java @@ -41,7 +41,6 @@ public interface BlockModelProvider extends ItemModelProvider { } else { BCLib.LOGGER.warning("Error loading model: {}", modelId); - modelCache.put(modelId, modelCache.get(MISSING_MODEL_LOCATION)); } } } diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index f3951497..b8e4c123 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -25,6 +25,7 @@ import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.ItemModelProvider; import java.util.Map; +import java.util.Set; @Mixin(ModelBakery.class) public abstract class ModelBakeryMixin { @@ -34,20 +35,22 @@ public abstract class ModelBakeryMixin { @Final @Shadow private Map topLevelModels; - - //private Map cache = Maps.newHashMap(); - //private Map topLevel = Maps.newHashMap(); + @Final + @Shadow + private Set loadingStack; @Inject( method = "*", at = @At( value = "INVOKE_STRING", - target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", - args = "ldc=static_definitions", + target = "Lnet/minecraft/util/profiling/ProfilerFiller;push(Ljava/lang/String;)V", + args = "ldc=missing_model", shift = Shift.BEFORE ) ) private void bclib_initCustomModels(ResourceManager resourceManager, BlockColors blockColors, ProfilerFiller profiler, int mipmap, CallbackInfo info) { + System.out.println("Cache size 1: " + unbakedCache.size()); + Map cache = Maps.newConcurrentMap(); Map topLevel = Maps.newConcurrentMap(); @@ -102,6 +105,12 @@ public abstract class ModelBakeryMixin { } }); + System.out.println("Cache size 2: " + unbakedCache.size()); + + cache.values().forEach(model -> { + loadingStack.addAll(model.getDependencies()); + }); + topLevelModels.putAll(topLevel); unbakedCache.putAll(cache); } From 49e93e43098e699dd81f46a191d6801baa353aa5 Mon Sep 17 00:00:00 2001 From: paulevsGitch Date: Sat, 31 Jul 2021 09:22:50 +0300 Subject: [PATCH 0145/1033] Remove debug info --- src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index b8e4c123..70b6f824 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -49,8 +49,6 @@ public abstract class ModelBakeryMixin { ) ) private void bclib_initCustomModels(ResourceManager resourceManager, BlockColors blockColors, ProfilerFiller profiler, int mipmap, CallbackInfo info) { - System.out.println("Cache size 1: " + unbakedCache.size()); - Map cache = Maps.newConcurrentMap(); Map topLevel = Maps.newConcurrentMap(); @@ -105,8 +103,6 @@ public abstract class ModelBakeryMixin { } }); - System.out.println("Cache size 2: " + unbakedCache.size()); - cache.values().forEach(model -> { loadingStack.addAll(model.getDependencies()); }); From 165c6e5b2217f50a4afd8fa34290c34010ebf29c Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Sat, 31 Jul 2021 09:19:46 +0200 Subject: [PATCH 0146/1033] Fixed crash when server initializes a new world --- src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java index d5c879fc..0866064c 100644 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java @@ -105,9 +105,9 @@ public class DataFixerAPI { */ public static boolean fixData(LevelStorageSource.LevelStorageAccess levelStorageAccess, boolean showUI, Consumer onResume){ File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(); - + File levelDat = levelStorageAccess.getLevelPath(LevelResource.LEVEL_DATA_FILE).toFile(); boolean newWorld = false; - if (!levelPath.exists()) { + if (!levelDat.exists()) { BCLib.LOGGER.info("Creating a new World, no fixes needed"); newWorld = true; } From c621b0525e6e2a79edf7237b8152759451c43aff Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Sat, 31 Jul 2021 10:32:09 +0200 Subject: [PATCH 0147/1033] Hello message initiated on Server --- .../bclib/api/dataexchange/DataHandler.java | 17 ++++------- .../{HelloServer.java => HelloClient.java} | 28 ++++++++++++------- 2 files changed, 24 insertions(+), 21 deletions(-) rename src/main/java/ru/bclib/api/dataexchange/handler/{HelloServer.java => HelloClient.java} (73%) diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java index 0005ced8..f4a360b9 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java @@ -40,24 +40,19 @@ public abstract class DataHandler { @Environment(EnvType.CLIENT) void receiveFromServer(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender responseSender){ - deserializeFromIncomingData(buf, responseSender, false); - client.execute(() -> runOnClient(client)); + deserializeFromIncomingData(buf, responseSender, true); + client.execute(() -> runOnGameThread(client, null, true)); } void receiveFromClient(MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender){ - deserializeFromIncomingData(buf, responseSender, true); - server.execute(() -> runOnServer(server)); + deserializeFromIncomingData(buf, responseSender, false); + server.execute(() -> runOnGameThread(null, server, false)); } - protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean fromClient){ + protected void deserializeFromIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean isClient){ } - @Environment(EnvType.CLIENT) - protected void runOnClient(Minecraft client){ - - } - - protected void runOnServer(MinecraftServer server){ + protected void runOnGameThread(Minecraft client, MinecraftServer server, boolean isClient){ } diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java b/src/main/java/ru/bclib/api/dataexchange/handler/HelloClient.java similarity index 73% rename from src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java rename to src/main/java/ru/bclib/api/dataexchange/handler/HelloClient.java index 13b2fe02..96c272d9 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/HelloServer.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/HelloClient.java @@ -1,7 +1,5 @@ package ru.bclib.api.dataexchange.handler; -import io.netty.buffer.ByteBufUtil; -import io.netty.util.CharsetUtil; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.networking.v1.PacketSender; @@ -12,7 +10,6 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import ru.bclib.BCLib; -import ru.bclib.api.WorldDataAPI; import ru.bclib.api.dataexchange.DataExchangeAPI; import ru.bclib.api.dataexchange.DataHandler; import ru.bclib.api.dataexchange.DataHandlerDescriptor; @@ -24,11 +21,11 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Optional; -public class HelloServer extends DataHandler { - public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "hello_server"), HelloServer::new, true); +public class HelloClient extends DataHandler { + public static DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, "hello_client"), HelloClient::new, true); - public HelloServer() { - super(DESCRIPTOR.IDENTIFIER, false); + public HelloClient() { + super(DESCRIPTOR.IDENTIFIER, true); } public static String getModVersion(String modID){ @@ -60,13 +57,18 @@ public class HelloServer extends DataHandler { } @Override - protected void runOnServer(MinecraftServer server) { + protected void runOnGameThread(Minecraft client, MinecraftServer server, boolean isClient) { String localBclibVersion = getBCLibVersion(); - BCLib.LOGGER.info("Hello Server received from BCLib. (server="+localBclibVersion+", client="+bclibVersion+")"); + BCLib.LOGGER.info("Hello Client received from BCLib. (client="+localBclibVersion+", server="+bclibVersion+")"); + + if (DataFixerAPI.getModVersion(localBclibVersion) == DataFixerAPI.getModVersion(bclibVersion)){ + showBCLibError(client); + return; + } for (Entry e : modVersion.entrySet()){ String ver = getModVersion(e.getKey()); - BCLib.LOGGER.info(" - " + e.getKey() + " (server="+ver+", client="+ver+")"); + BCLib.LOGGER.info(" - " + e.getKey() + " (client="+ver+", server="+ver+")"); } } @@ -81,4 +83,10 @@ public class HelloServer extends DataHandler { buf.writeInt(DataFixerAPI.getModVersion(getModVersion(modID))); } } + + @Environment(EnvType.CLIENT) + protected void showBCLibError(Minecraft client){ + BCLib.LOGGER.error("BCLib differs on client and server. Stopping."); + client.stop(); + } } From 114574bff36bfb16ca37ee5b88c5c7849f652c16 Mon Sep 17 00:00:00 2001 From: Frank Bauer Date: Sat, 31 Jul 2021 10:32:23 +0200 Subject: [PATCH 0148/1033] Added class to help with simple GridLayouts --- src/main/java/ru/bclib/gui/GridLayout.java | 122 ++++++++++++++++++ .../bclib/gui/screens/ConfirmFixScreen.java | 74 +++-------- 2 files changed, 140 insertions(+), 56 deletions(-) create mode 100644 src/main/java/ru/bclib/gui/GridLayout.java diff --git a/src/main/java/ru/bclib/gui/GridLayout.java b/src/main/java/ru/bclib/gui/GridLayout.java new file mode 100644 index 00000000..bc4b2976 --- /dev/null +++ b/src/main/java/ru/bclib/gui/GridLayout.java @@ -0,0 +1,122 @@ +package ru.bclib.gui; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.Button.OnPress; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; + +public class GridLayout { + class LablePos { + final MultiLineLabel label; + final int top; + + LablePos(MultiLineLabel label, int top){ + this.label = label; + this.top = top; + } + } + + class ButtonPos { + final int height; + final int width; + final float alpha; + final Component component; + final Button.OnPress onPress; + + ButtonPos(float alpha, int width, int height, Component component, OnPress onPress) { + this.height = height; + this.width = width; + this.alpha = alpha; + this.component = component; + this.onPress = onPress; + } + } + public final int width; + @NotNull + private final Font font; + private final Consumer