diff --git a/src/main/java/com/simibubi/create/AllBlockPartials.java b/src/main/java/com/simibubi/create/AllBlockPartials.java index d6a27e9d0..102fc4412 100644 --- a/src/main/java/com/simibubi/create/AllBlockPartials.java +++ b/src/main/java/com/simibubi/create/AllBlockPartials.java @@ -1,38 +1,20 @@ package com.simibubi.create; -import static net.minecraft.state.properties.BlockStateProperties.FACING; -import static net.minecraft.state.properties.BlockStateProperties.HORIZONTAL_FACING; - -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.function.Supplier; -import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.content.contraptions.fluids.FluidTransportBehaviour.AttachmentTypes; -import com.simibubi.create.content.contraptions.processing.burner.BlazeBurnerBlock.HeatLevel; -import com.simibubi.create.foundation.render.SuperByteBuffer; -import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; -import com.simibubi.create.foundation.render.backend.instancing.RenderMaterial; -import com.simibubi.create.foundation.utility.AngleHelper; +import com.simibubi.create.content.contraptions.fluids.FluidTransportBehaviour; +import com.simibubi.create.content.contraptions.processing.burner.BlazeBurnerBlock; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Iterate; import com.simibubi.create.foundation.utility.Lang; -import com.simibubi.create.foundation.utility.MatrixStacker; -import net.minecraft.block.BlockState; -import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.client.event.ModelBakeEvent; -import net.minecraftforge.client.event.ModelRegistryEvent; -import net.minecraftforge.client.model.ModelLoader; public class AllBlockPartials { - private static final List all = new ArrayList<>(); - - public static final AllBlockPartials SCHEMATICANNON_CONNECTOR = get("schematicannon/connector"), + public static final PartialModel SCHEMATICANNON_CONNECTOR = get("schematicannon/connector"), SCHEMATICANNON_PIPE = get("schematicannon/pipe"), SHAFTLESS_COGWHEEL = get("cogwheel_shaftless"), SHAFT_HALF = get("shaft_half"), @@ -123,124 +105,40 @@ public class AllBlockPartials { ; - public static final Map> PIPE_ATTACHMENTS = map(); - public static final Map BLAZES = map(); + public static final Map> PIPE_ATTACHMENTS = new HashMap<>(); + public static final Map BLAZES = new HashMap<>(); static { populateMaps(); } - ; - - private ResourceLocation modelLocation; - private IBakedModel bakedModel; - - private AllBlockPartials() {} - - private static void populateMaps() { - for (AttachmentTypes type : AttachmentTypes.values()) { + static void populateMaps() { + for (FluidTransportBehaviour.AttachmentTypes type : FluidTransportBehaviour.AttachmentTypes.values()) { if (!type.hasModel()) continue; - Map map = map(); + Map map = new HashMap<>(); for (Direction d : Iterate.directions) { String asId = Lang.asId(type.name()); map.put(d, get("fluid_pipe/" + asId + "/" + Lang.asId(d.getString()))); } PIPE_ATTACHMENTS.put(type, map); } - for (HeatLevel heat : HeatLevel.values()) { - if (heat == HeatLevel.NONE) + for (BlazeBurnerBlock.HeatLevel heat : BlazeBurnerBlock.HeatLevel.values()) { + if (heat == BlazeBurnerBlock.HeatLevel.NONE) continue; BLAZES.put(heat, get("blaze_burner/blaze/" + heat.getString())); } } - private static Map map() { - return new HashMap<>(); + private static PartialModel getEntity(String path) { + return new PartialModel(new ResourceLocation(Create.ID, "entity/" + path)); } - private static AllBlockPartials getEntity(String path) { - AllBlockPartials partials = new AllBlockPartials(); - partials.modelLocation = new ResourceLocation(Create.ID, "entity/" + path); - all.add(partials); - return partials; + private static PartialModel get(String path) { + return new PartialModel(new ResourceLocation(Create.ID, "block/" + path)); } - private static AllBlockPartials get(String path) { - AllBlockPartials partials = new AllBlockPartials(); - partials.modelLocation = new ResourceLocation(Create.ID, "block/" + path); - all.add(partials); - return partials; + public static void clientInit() { + // init static fields } - - public static void onModelRegistry(ModelRegistryEvent event) { - for (AllBlockPartials partial : all) - ModelLoader.addSpecialModel(partial.modelLocation); - } - - public static void onModelBake(ModelBakeEvent event) { - Map modelRegistry = event.getModelRegistry(); - for (AllBlockPartials partial : all) - partial.bakedModel = modelRegistry.get(partial.modelLocation); - } - - public IBakedModel get() { - return bakedModel; - } - - public SuperByteBuffer renderOn(BlockState referenceState) { - return CreateClient.bufferCache.renderPartial(this, referenceState); - } - - public SuperByteBuffer renderOnDirectionalSouth(BlockState referenceState) { - Direction facing = referenceState.get(FACING); - return renderOnDirectionalSouth(referenceState, facing); - } - - public SuperByteBuffer renderOnDirectional(BlockState referenceState) { - Direction facing = referenceState.get(FACING); - return renderOnDirectional(referenceState, facing); - } - - public SuperByteBuffer renderOnHorizontal(BlockState referenceState) { - Direction facing = referenceState.get(HORIZONTAL_FACING); - return renderOnDirectionalSouth(referenceState, facing); - } - - public SuperByteBuffer renderOnDirectionalSouth(BlockState referenceState, Direction facing) { - MatrixStack ms = new MatrixStack(); - // TODO 1.15 find a way to cache this model matrix computation - MatrixStacker.of(ms) - .centre() - .rotateY(AngleHelper.horizontalAngle(facing)) - .rotateX(AngleHelper.verticalAngle(facing)) - .unCentre(); - return CreateClient.bufferCache.renderDirectionalPartial(this, referenceState, facing, ms); - } - - public SuperByteBuffer renderOnDirectional(BlockState referenceState, Direction facing) { - MatrixStack ms = new MatrixStack(); - // TODO 1.15 find a way to cache this model matrix computation - MatrixStacker.of(ms) - .centre() - .rotateY(AngleHelper.horizontalAngle(facing)) - .rotateX(facing == Direction.UP ? 0 : facing == Direction.DOWN ? 180 : 90) - .unCentre(); - return CreateClient.bufferCache.renderDirectionalPartial(this, referenceState, facing, ms); - } - - public > M getModel(RenderMaterial mat, BlockState referenceState, - Direction facing) { - Supplier ms = () -> { - MatrixStack stack = new MatrixStack(); - MatrixStacker.of(stack) - .centre() - .rotateY(AngleHelper.horizontalAngle(facing)) - .rotateX(AngleHelper.verticalAngle(facing)) - .unCentre(); - return stack; - }; - return mat.getModel(this, referenceState, facing, ms); - } - } diff --git a/src/main/java/com/simibubi/create/CreateClient.java b/src/main/java/com/simibubi/create/CreateClient.java index 103166ff1..2940b484d 100644 --- a/src/main/java/com/simibubi/create/CreateClient.java +++ b/src/main/java/com/simibubi/create/CreateClient.java @@ -27,6 +27,7 @@ import com.simibubi.create.foundation.render.KineticRenderer; import com.simibubi.create.foundation.render.SuperByteBufferCache; import com.simibubi.create.foundation.render.backend.Backend; import com.simibubi.create.foundation.render.backend.OptifineHandler; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; import com.simibubi.create.foundation.utility.WorldAttached; import com.simibubi.create.foundation.utility.ghost.GhostBlocks; @@ -115,6 +116,8 @@ public class CreateClient { .getResourceManager(); if (resourceManager instanceof IReloadableResourceManager) ((IReloadableResourceManager) resourceManager).addReloadListener(new ResourceReloadHandler()); + + AllBlockPartials.clientInit(); } public static void onTextureStitch(TextureStitchEvent.Pre event) { @@ -128,7 +131,7 @@ public class CreateClient { public static void onModelBake(ModelBakeEvent event) { Map modelRegistry = event.getModelRegistry(); - AllBlockPartials.onModelBake(event); + PartialModel.onModelBake(event); getCustomBlockModels() .foreach((block, modelFunc) -> swapModels(modelRegistry, getAllBlockStateModelLocations(block), modelFunc)); @@ -141,7 +144,7 @@ public class CreateClient { } public static void onModelRegistry(ModelRegistryEvent event) { - AllBlockPartials.onModelRegistry(event); + PartialModel.onModelRegistry(event); getCustomRenderedItems().foreach((item, modelFunc) -> modelFunc.apply(null) .getModelLocations() diff --git a/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java b/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java index 207baa023..2f03d2056 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/ProcessingViaFanCategory.java @@ -28,7 +28,7 @@ public abstract class ProcessingViaFanCategory> extends Cre public ProcessingViaFanCategory(IDrawable icon) { this(177, icon); } - + protected ProcessingViaFanCategory(int width, IDrawable icon) { super(icon, emptyBackground(width, 71)); } diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedBlazeBurner.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedBlazeBurner.java index 8ec5983de..920ab0bf3 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedBlazeBurner.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedBlazeBurner.java @@ -5,6 +5,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.contraptions.processing.burner.BlazeBurnerBlock.HeatLevel; import com.simibubi.create.foundation.gui.GuiGameElement; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import mezz.jei.api.gui.drawable.IDrawable; import net.minecraft.util.math.vector.Vector3f; @@ -30,7 +31,7 @@ public class AnimatedBlazeBurner implements IDrawable { .scale(scale) .render(matrixStack); - AllBlockPartials blaze = AllBlockPartials.BLAZES.get(heatLevel); + PartialModel blaze = AllBlockPartials.BLAZES.get(heatLevel); GuiGameElement.of(blaze) .atLocal(1, 1.65, 1) .rotate(0, 180, 0) diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java index ef9e662ce..fb0e5a880 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedKinetics.java @@ -2,6 +2,7 @@ package com.simibubi.create.compat.jei.category.animations; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.AllBlocks; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.AnimationTickHolder; import mezz.jei.api.gui.drawable.IDrawable; @@ -14,15 +15,15 @@ public abstract class AnimatedKinetics implements IDrawable { public static float getCurrentAngle() { return ((AnimationTickHolder.getRenderTime()) * 4f) % 360; } - + protected BlockState shaft(Axis axis) { return AllBlocks.SHAFT.getDefaultState().with(BlockStateProperties.AXIS, axis); } - - protected AllBlockPartials cogwheel() { + + protected PartialModel cogwheel() { return AllBlockPartials.SHAFTLESS_COGWHEEL; } - + @Override public int getWidth() { return 50; diff --git a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedMillstone.java b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedMillstone.java index 80bc6a479..8e98eb372 100644 --- a/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedMillstone.java +++ b/src/main/java/com/simibubi/create/compat/jei/category/animations/AnimatedMillstone.java @@ -20,7 +20,7 @@ public class AnimatedMillstone extends AnimatedKinetics { .rotateBlock(22.5, getCurrentAngle() * 2, 0) .scale(scale) .render(matrixStack); - + GuiGameElement.of(AllBlocks.MILLSTONE.getDefaultState()) .rotateBlock(22.5, 22.5, 0) .scale(scale) diff --git a/src/main/java/com/simibubi/create/content/contraptions/base/HalfShaftInstance.java b/src/main/java/com/simibubi/create/content/contraptions/base/HalfShaftInstance.java index 4b834f520..6d3664988 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/base/HalfShaftInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/base/HalfShaftInstance.java @@ -14,9 +14,9 @@ public class HalfShaftInstance extends SingleRotatingInstance { @Override protected InstancedModel getModel() { - Direction dir = getShaftDirection(); - return AllBlockPartials.SHAFT_HALF.getModel(getRotatingMaterial(), blockState, dir); - } + Direction dir = getShaftDirection(); + return getRotatingMaterial().getModel(AllBlockPartials.SHAFT_HALF, blockState, dir); + } protected Direction getShaftDirection() { return blockState.get(BlockStateProperties.FACING); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillInstance.java index ad6b2ce47..7d1bdd735 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillInstance.java @@ -10,6 +10,7 @@ import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; import net.minecraft.block.BlockState; +import net.minecraft.util.Direction; public class DrillInstance extends SingleRotatingInstance { @@ -20,6 +21,7 @@ public class DrillInstance extends SingleRotatingInstance { @Override protected InstancedModel getModel() { BlockState referenceState = tile.getBlockState(); - return AllBlockPartials.DRILL_HEAD.getModel(getRotatingMaterial(), referenceState, referenceState.get(FACING)); + Direction facing = referenceState.get(FACING); + return getRotatingMaterial().getModel(AllBlockPartials.DRILL_HEAD, referenceState, facing); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillRenderer.java index 38f940dab..3734c3509 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/actors/DrillRenderer.java @@ -5,6 +5,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.components.structureMovement.MovementContext; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.utility.AngleHelper; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -25,22 +26,18 @@ public class DrillRenderer extends KineticTileEntityRenderer { @Override protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { - return AllBlockPartials.DRILL_HEAD.renderOnDirectionalSouth(te.getBlockState()); - } - - protected static SuperByteBuffer getRotatingModel(BlockState state) { - return AllBlockPartials.DRILL_HEAD.renderOnDirectionalSouth(state); + return PartialBufferer.getFacing(AllBlockPartials.DRILL_HEAD, te.getBlockState()); } public static void renderInContraption(MovementContext context, MatrixStack ms, MatrixStack msLocal, IRenderTypeBuffer buffer) { - MatrixStack[] matrixStacks = new MatrixStack[] { ms, msLocal }; + MatrixStack[] matrixStacks = new MatrixStack[]{ms, msLocal}; BlockState state = context.state; - SuperByteBuffer superBuffer = AllBlockPartials.DRILL_HEAD.renderOn(state); + SuperByteBuffer superBuffer = PartialBufferer.get(AllBlockPartials.DRILL_HEAD, state); Direction facing = state.get(DrillBlock.FACING); - + float speed = (float) (context.contraption.stalled - || !VecHelper.isVecPointingTowards(context.relativeMotion, facing + || !VecHelper.isVecPointingTowards(context.relativeMotion, facing .getOpposite()) ? context.getAnimationSpeed() : 0); float time = AnimationTickHolder.getRenderTime() / 20; float angle = (float) (((time * speed) % 360)); @@ -52,11 +49,11 @@ public class DrillRenderer extends KineticTileEntityRenderer { .rotateX(AngleHelper.verticalAngle(facing)) .rotateZ(angle) .unCentre(); - + superBuffer .light(msLocal.peek() .getModel()) .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/actors/HarvesterRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/actors/HarvesterRenderer.java index 5b50202e3..44cf29765 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/actors/HarvesterRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/actors/HarvesterRenderer.java @@ -6,6 +6,7 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.components.structureMovement.MovementContext; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionRenderDispatcher; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; @@ -31,28 +32,28 @@ public class HarvesterRenderer extends SafeTileEntityRenderer getTileEntityClass() { return HandCrankTileEntity.class; } - + @Override public boolean allowsMovement(BlockState state, IBlockReader reader, BlockPos pos, PathType type) { return false; diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankInstance.java index 34751963a..843882dce 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankInstance.java @@ -1,9 +1,9 @@ package com.simibubi.create.content.contraptions.components.crank; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.SingleRotatingInstance; import com.simibubi.create.foundation.render.backend.core.ModelData; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.IDynamicInstance; import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; @@ -22,21 +22,22 @@ public class HandCrankInstance extends SingleRotatingInstance implements IDynami public HandCrankInstance(InstancedTileRenderer modelManager, HandCrankTileEntity tile) { super(modelManager, tile); - this.tile = tile; + this.tile = tile; - Block block = blockState.getBlock(); - AllBlockPartials renderedHandle = null; - if (block instanceof HandCrankBlock) - renderedHandle = ((HandCrankBlock) block).getRenderedHandle(); - if (renderedHandle == null) - return; + Block block = blockState.getBlock(); + PartialModel renderedHandle = null; + if (block instanceof HandCrankBlock) + renderedHandle = ((HandCrankBlock) block).getRenderedHandle(); + if (renderedHandle == null) + return; - facing = blockState.get(BlockStateProperties.FACING); - InstancedModel model = renderedHandle.getModel(getTransformMaterial(), blockState, facing.getOpposite()); - crank = model.createInstance(); + facing = blockState.get(BlockStateProperties.FACING); + Direction opposite = facing.getOpposite(); + InstancedModel model = getTransformMaterial().getModel(renderedHandle, blockState, opposite); + crank = model.createInstance(); - rotateCrank(); - } + rotateCrank(); + } @Override public void beginFrame() { diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankRenderer.java index 11442df9e..7db258093 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/crank/HandCrankRenderer.java @@ -3,11 +3,12 @@ package com.simibubi.create.content.contraptions.components.crank; import static net.minecraft.state.properties.BlockStateProperties.FACING; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import net.minecraft.block.Block; import net.minecraft.block.BlockState; @@ -31,17 +32,17 @@ public class HandCrankRenderer extends KineticTileEntityRenderer { BlockState state = te.getBlockState(); Block block = state.getBlock(); - AllBlockPartials renderedHandle = null; + PartialModel renderedHandle = null; if (block instanceof HandCrankBlock) renderedHandle = ((HandCrankBlock) block).getRenderedHandle(); if (renderedHandle == null) return; Direction facing = state.get(FACING); - SuperByteBuffer handle = renderedHandle.renderOnDirectionalSouth(state, facing.getOpposite()); + SuperByteBuffer handle = PartialBufferer.getFacing(renderedHandle, state, facing.getOpposite()); HandCrankTileEntity crank = (HandCrankTileEntity) te; kineticRotationTransform(handle, te, facing.getAxis(), - (crank.independentAngle + partialTicks * crank.chasingVelocity) / 360, light); + (crank.independentAngle + partialTicks * crank.chasingVelocity) / 360, light); handle.renderInto(ms, buffer.getBuffer(RenderType.getSolid())); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/crank/ValveHandleBlock.java b/src/main/java/com/simibubi/create/content/contraptions/components/crank/ValveHandleBlock.java index bca18a69a..e9e8c32d7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/crank/ValveHandleBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/crank/ValveHandleBlock.java @@ -2,8 +2,8 @@ package com.simibubi.create.content.contraptions.components.crank; import javax.annotation.ParametersAreNonnullByDefault; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.AllBlocks; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.DyeHelper; import net.minecraft.block.BlockState; @@ -68,7 +68,7 @@ public class ValveHandleBlock extends HandCrankBlock { @Override @OnlyIn(Dist.CLIENT) - public AllBlockPartials getRenderedHandle() { + public PartialModel getRenderedHandle() { return null; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerActorInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerActorInstance.java index a62bf37d8..e91bc8a0d 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerActorInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerActorInstance.java @@ -14,6 +14,7 @@ import com.simibubi.create.content.contraptions.components.structureMovement.ren import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionKineticRenderer; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionProgram; import com.simibubi.create.foundation.render.backend.core.ModelData; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; import com.simibubi.create.foundation.render.backend.instancing.RenderMaterial; import com.simibubi.create.foundation.utility.AngleHelper; @@ -48,7 +49,7 @@ public class DeployerActorInstance extends ActorInstance { BlockState state = context.state; DeployerTileEntity.Mode mode = NBTHelper.readEnum(context.tileData, "Mode", DeployerTileEntity.Mode.class); - AllBlockPartials handPose = DeployerRenderer.getHandPose(mode); + PartialModel handPose = DeployerRenderer.getHandPose(mode); stationaryTimer = context.data.contains("StationaryTimer"); facing = state.get(FACING); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerInstance.java index 3ffd3339b..31b1d7665 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerInstance.java @@ -7,6 +7,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.relays.encased.ShaftInstance; import com.simibubi.create.foundation.render.backend.core.OrientedData; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.IDynamicInstance; import com.simibubi.create.foundation.render.backend.instancing.ITickableInstance; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; @@ -31,7 +32,7 @@ public class DeployerInstance extends ShaftInstance implements IDynamicInstance, protected OrientedData hand; - AllBlockPartials currentHand; + PartialModel currentHand; float progress; private boolean newHand = false; @@ -89,7 +90,7 @@ public class DeployerInstance extends ShaftInstance implements IDynamicInstance, } private boolean updateHandPose() { - AllBlockPartials handPose = tile.getHandPose(); + PartialModel handPose = tile.getHandPose(); if (currentHand == handPose) return false; currentHand = handPose; diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerRenderer.java index d9dd683c6..0261f9651 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerRenderer.java @@ -11,8 +11,10 @@ import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.components.deployer.DeployerTileEntity.Mode; import com.simibubi.create.content.contraptions.components.structureMovement.MovementContext; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionRenderDispatcher; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.behaviour.filtering.FilteringRenderer; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; @@ -117,14 +119,13 @@ public class DeployerRenderer extends SafeTileEntityRenderer BlockPos pos = te.getPos(); Vector3d offset = getHandOffset(te, partialTicks, blockState); - SuperByteBuffer pole = AllBlockPartials.DEPLOYER_POLE.renderOn(blockState); - SuperByteBuffer hand = te.getHandPose() - .renderOn(blockState); + SuperByteBuffer pole = PartialBufferer.get(AllBlockPartials.DEPLOYER_POLE, blockState); + SuperByteBuffer hand = PartialBufferer.get(te.getHandPose(), blockState); transform(te.getWorld(), pole.translate(offset.x, offset.y, offset.z), blockState, pos, true).renderInto(ms, - vb); + vb); transform(te.getWorld(), hand.translate(offset.x, offset.y, offset.z), blockState, pos, false).renderInto(ms, - vb); + vb); } protected Vector3d getHandOffset(DeployerTileEntity te, float partialTicks, BlockState blockState) { @@ -155,16 +156,16 @@ public class DeployerRenderer extends SafeTileEntityRenderer public static void renderInContraption(MovementContext context, MatrixStack ms, MatrixStack msLocal, IRenderTypeBuffer buffer) { - MatrixStack[] matrixStacks = new MatrixStack[] { ms, msLocal }; + MatrixStack[] matrixStacks = new MatrixStack[]{ms, msLocal}; IVertexBuilder builder = buffer.getBuffer(RenderType.getSolid()); BlockState blockState = context.state; BlockPos pos = BlockPos.ZERO; Mode mode = NBTHelper.readEnum(context.tileData, "Mode", Mode.class); World world = context.world; - AllBlockPartials handPose = getHandPose(mode); + PartialModel handPose = getHandPose(mode); - SuperByteBuffer pole = AllBlockPartials.DEPLOYER_POLE.renderOn(blockState); - SuperByteBuffer hand = handPose.renderOn(blockState); + SuperByteBuffer pole = PartialBufferer.get(AllBlockPartials.DEPLOYER_POLE, blockState); + SuperByteBuffer hand = PartialBufferer.get(handPose, blockState); pole = transform(world, pole, blockState, pos, true); hand = transform(world, hand, blockState, pos, false); @@ -192,7 +193,7 @@ public class DeployerRenderer extends SafeTileEntityRenderer .renderInto(ms, builder); } - static AllBlockPartials getHandPose(DeployerTileEntity.Mode mode) { + static PartialModel getHandPose(DeployerTileEntity.Mode mode) { return mode == DeployerTileEntity.Mode.PUNCH ? AllBlockPartials.DEPLOYER_HAND_PUNCHING : AllBlockPartials.DEPLOYER_HAND_POINTING; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerTileEntity.java b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerTileEntity.java index 8705330ba..c1e5493a1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerTileEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/deployer/DeployerTileEntity.java @@ -11,6 +11,7 @@ import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.curiosities.tools.SandPaperItem; import com.simibubi.create.foundation.advancement.AllTriggers; import com.simibubi.create.foundation.item.TooltipHelper; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.TileEntityBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.filtering.FilteringBehaviour; import com.simibubi.create.foundation.utility.NBTHelper; @@ -113,7 +114,7 @@ public class DeployerTileEntity extends KineticTileEntity { @Override public void tick() { super.tick(); - + if (getSpeed() == 0) return; if (!world.isRemote && player != null && player.blockBreakingProgress != null) { @@ -331,7 +332,7 @@ public class DeployerTileEntity extends KineticTileEntity { private IItemHandlerModifiable createHandler() { return new DeployerItemHandler(this); } - + public void redstoneUpdate() { if (world.isRemote) return; @@ -342,7 +343,7 @@ public class DeployerTileEntity extends KineticTileEntity { sendData(); } - public AllBlockPartials getHandPose() { + public PartialModel getHandPose() { return mode == Mode.PUNCH ? AllBlockPartials.DEPLOYER_HAND_PUNCHING : heldItem.isEmpty() ? AllBlockPartials.DEPLOYER_HAND_POINTING : AllBlockPartials.DEPLOYER_HAND_HOLDING; } @@ -395,7 +396,7 @@ public class DeployerTileEntity extends KineticTileEntity { float progress = 0; int timerSpeed = getTimerSpeed(); - AllBlockPartials handPose = getHandPose(); + PartialModel handPose = getHandPose(); if (state == State.EXPANDING) progress = 1 - (timer - partialTicks * timerSpeed) / 1000f; diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/fan/EncasedFanRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/fan/EncasedFanRenderer.java index cb469d615..6491d16e3 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/fan/EncasedFanRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/fan/EncasedFanRenderer.java @@ -7,6 +7,7 @@ import com.mojang.blaze3d.vertex.IVertexBuilder; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -30,17 +31,17 @@ public class EncasedFanRenderer extends KineticTileEntityRenderer { if (FastRenderDispatcher.available(te.getWorld())) return; Direction direction = te.getBlockState() - .get(FACING); + .get(FACING); IVertexBuilder vb = buffer.getBuffer(RenderType.getCutoutMipped()); int lightBehind = WorldRenderer.getLightmapCoordinates(te.getWorld(), te.getPos().offset(direction.getOpposite())); int lightInFront = WorldRenderer.getLightmapCoordinates(te.getWorld(), te.getPos().offset(direction)); - + SuperByteBuffer shaftHalf = - AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(te.getBlockState(), direction.getOpposite()); + PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, te.getBlockState(), direction.getOpposite()); SuperByteBuffer fanInner = - AllBlockPartials.ENCASED_FAN_INNER.renderOnDirectionalSouth(te.getBlockState(), direction.getOpposite()); - + PartialBufferer.getFacing(AllBlockPartials.ENCASED_FAN_INNER, te.getBlockState(), direction.getOpposite()); + float time = AnimationTickHolder.getRenderTime(te.getWorld()); float speed = te.getSpeed() * 5; if (speed > 0) diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/fan/FanInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/fan/FanInstance.java index 05e921f0a..2feec9410 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/fan/FanInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/fan/FanInstance.java @@ -19,17 +19,17 @@ public class FanInstance extends KineticTileInstance { private final Direction opposite; public FanInstance(InstancedTileRenderer modelManager, EncasedFanTileEntity tile) { - super(modelManager, tile); + super(modelManager, tile); - direction = blockState.get(FACING); + direction = blockState.get(FACING); - opposite = direction.getOpposite(); - shaft = AllBlockPartials.SHAFT_HALF.getModel(getRotatingMaterial(), blockState, opposite).createInstance(); - fan = AllBlockPartials.ENCASED_FAN_INNER.getModel(getRotatingMaterial(), blockState, opposite).createInstance(); + opposite = direction.getOpposite(); + shaft = getRotatingMaterial().getModel(AllBlockPartials.SHAFT_HALF, blockState, opposite).createInstance(); + fan = getRotatingMaterial().getModel(AllBlockPartials.ENCASED_FAN_INNER, blockState, opposite).createInstance(); - setup(shaft); - setup(fan, getFanSpeed()); - } + setup(shaft); + setup(fan, getFanSpeed()); + } private float getFanSpeed() { float speed = tile.getSpeed() * 5; diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlyWheelInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlyWheelInstance.java index d01c2633f..219adb6d1 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlyWheelInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlyWheelInstance.java @@ -46,24 +46,24 @@ public class FlyWheelInstance extends KineticTileInstance im protected float lastAngle = Float.NaN; public FlyWheelInstance(InstancedTileRenderer modelManager, FlywheelTileEntity tile) { - super(modelManager, tile); + super(modelManager, tile); - facing = blockState.get(HORIZONTAL_FACING); + facing = blockState.get(HORIZONTAL_FACING); - shaft = setup(shaftModel().createInstance()); + shaft = setup(shaftModel().createInstance()); - BlockState referenceState = blockState.rotate(Rotation.CLOCKWISE_90); - wheel = AllBlockPartials.FLYWHEEL.getModel(getTransformMaterial(), referenceState, referenceState.get(HORIZONTAL_FACING)).createInstance(); + BlockState referenceState = blockState.rotate(Rotation.CLOCKWISE_90); + wheel = getTransformMaterial().getModel(AllBlockPartials.FLYWHEEL, referenceState, referenceState.get(HORIZONTAL_FACING)).createInstance(); - connection = FlywheelBlock.getConnection(blockState); - if (connection != null) { - connectedLeft = blockState.get(FlywheelBlock.CONNECTION) == FlywheelBlock.ConnectionState.LEFT; + connection = FlywheelBlock.getConnection(blockState); + if (connection != null) { + connectedLeft = blockState.get(FlywheelBlock.CONNECTION) == FlywheelBlock.ConnectionState.LEFT; - boolean flipAngle = connection.getAxis() == Direction.Axis.X ^ connection.getAxisDirection() == Direction.AxisDirection.NEGATIVE; + boolean flipAngle = connection.getAxis() == Direction.Axis.X ^ connection.getAxisDirection() == Direction.AxisDirection.NEGATIVE; - connectorAngleMult = flipAngle ? -1 : 1; + connectorAngleMult = flipAngle ? -1 : 1; - RenderMaterial> mat = getTransformMaterial(); + RenderMaterial> mat = getTransformMaterial(); upperRotating = mat.getModel(AllBlockPartials.FLYWHEEL_UPPER_ROTATING, blockState).createInstance(); lowerRotating = mat.getModel(AllBlockPartials.FLYWHEEL_LOWER_ROTATING, blockState).createInstance(); @@ -159,8 +159,9 @@ public class FlyWheelInstance extends KineticTileInstance im } protected InstancedModel shaftModel() { - return AllBlockPartials.SHAFT_HALF.getModel(getRotatingMaterial(), blockState, facing.getOpposite()); - } + Direction opposite = facing.getOpposite(); + return getRotatingMaterial().getModel(AllBlockPartials.SHAFT_HALF, blockState, opposite); + } protected void transformConnector(MatrixStacker ms, boolean upper, boolean rotating, float angle, boolean flip) { float shift = upper ? 1 / 4f : -1 / 8f; diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelRenderer.java index 03434b9e9..bf3b46295 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/FlywheelRenderer.java @@ -8,6 +8,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.components.flywheel.FlywheelBlock.ConnectionState; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AngleHelper; @@ -17,6 +18,7 @@ import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; +import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.util.Direction; import net.minecraft.util.Direction.Axis; import net.minecraft.util.Direction.AxisDirection; @@ -54,33 +56,39 @@ public class FlywheelRenderer extends KineticTileEntityRenderer { boolean flip = blockState.get(FlywheelBlock.CONNECTION) == ConnectionState.LEFT; transformConnector( - rotateToFacing(AllBlockPartials.FLYWHEEL_UPPER_ROTATING.renderOn(blockState), connection), true, true, - rotation, flip).light(light) + rotateToFacing(PartialBufferer.get(AllBlockPartials.FLYWHEEL_UPPER_ROTATING, blockState), connection), true, true, + rotation, flip).light(light) .renderInto(ms, vb); transformConnector( - rotateToFacing(AllBlockPartials.FLYWHEEL_LOWER_ROTATING.renderOn(blockState), connection), false, true, - rotation, flip).light(light) + rotateToFacing(PartialBufferer.get(AllBlockPartials.FLYWHEEL_LOWER_ROTATING, blockState), connection), false, true, + rotation, flip).light(light) .renderInto(ms, vb); - - transformConnector(rotateToFacing(AllBlockPartials.FLYWHEEL_UPPER_SLIDING.renderOn(blockState), connection), - true, false, rotation, flip).light(light) + + transformConnector(rotateToFacing(PartialBufferer.get(AllBlockPartials.FLYWHEEL_UPPER_SLIDING, blockState), connection), + true, false, rotation, flip).light(light) .renderInto(ms, vb); - transformConnector(rotateToFacing(AllBlockPartials.FLYWHEEL_LOWER_SLIDING.renderOn(blockState), connection), - false, false, rotation, flip).light(light) + transformConnector(rotateToFacing(PartialBufferer.get(AllBlockPartials.FLYWHEEL_LOWER_SLIDING, blockState), connection), + false, false, rotation, flip).light(light) .renderInto(ms, vb); } - SuperByteBuffer wheel = AllBlockPartials.FLYWHEEL.renderOnHorizontal(blockState.rotate(Rotation.CLOCKWISE_90)); + renderFlywheel(te, ms, light, blockState, angle, vb); + } + + private void renderFlywheel(KineticTileEntity te, MatrixStack ms, int light, BlockState blockState, float angle, IVertexBuilder vb) { + BlockState referenceState = blockState.rotate(Rotation.CLOCKWISE_90); + Direction facing = referenceState.get(BlockStateProperties.HORIZONTAL_FACING); + SuperByteBuffer wheel = PartialBufferer.getFacing(AllBlockPartials.FLYWHEEL, referenceState, facing); kineticRotationTransform(wheel, te, blockState.get(HORIZONTAL_FACING) - .getAxis(), AngleHelper.rad(angle), light); + .getAxis(), AngleHelper.rad(angle), light); wheel.renderInto(ms, vb); } @Override protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { - return AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(te.getBlockState(), te.getBlockState() - .get(HORIZONTAL_FACING) - .getOpposite()); + return PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, te.getBlockState(), te.getBlockState() + .get(BlockStateProperties.HORIZONTAL_FACING) + .getOpposite()); } protected SuperByteBuffer transformConnector(SuperByteBuffer buffer, boolean upper, boolean rotating, float angle, diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineBlock.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineBlock.java index 268aa65cc..f3d07cf66 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineBlock.java @@ -2,8 +2,8 @@ package com.simibubi.create.content.contraptions.components.flywheel.engine; import javax.annotation.Nullable; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.wrench.IWrenchable; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Iterate; import net.minecraft.block.Block; @@ -37,12 +37,12 @@ public abstract class EngineBlock extends HorizontalBlock implements IWrenchable public boolean hasTileEntity(BlockState state) { return true; } - + @Override public ActionResultType onWrenched(BlockState state, ItemUseContext context) { return ActionResultType.FAIL; } - + @Override public abstract TileEntity createTileEntity(BlockState state, IBlockReader world); @@ -88,14 +88,14 @@ public abstract class EngineBlock extends HorizontalBlock implements IWrenchable return true; } - + public static BlockPos getBaseBlockPos(BlockState state, BlockPos pos) { return pos.offset(state.get(HORIZONTAL_FACING).getOpposite()); } @Nullable @OnlyIn(Dist.CLIENT) - public abstract AllBlockPartials getFrameModel(); + public abstract PartialModel getFrameModel(); protected abstract boolean isValidBaseBlock(BlockState baseBlock, IBlockReader world, BlockPos pos); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineInstance.java index a88cbbd1a..3f76914d0 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineInstance.java @@ -1,8 +1,8 @@ package com.simibubi.create.content.contraptions.components.flywheel.engine; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.foundation.render.backend.core.ModelData; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; import com.simibubi.create.foundation.render.backend.instancing.TileEntityInstance; import com.simibubi.create.foundation.utility.AngleHelper; @@ -25,7 +25,7 @@ public class EngineInstance extends TileEntityInstance { return; EngineBlock engineBlock = (EngineBlock) block; - AllBlockPartials frame = engineBlock.getFrameModel(); + PartialModel frame = engineBlock.getFrameModel(); Direction facing = blockState.get(BlockStateProperties.HORIZONTAL_FACING); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineRenderer.java index 597895c48..42be5bedf 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/EngineRenderer.java @@ -1,8 +1,9 @@ package com.simibubi.create.content.contraptions.components.flywheel.engine; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; @@ -29,16 +30,16 @@ public class EngineRenderer extends SafeTileEntityRe .getBlock(); if (block instanceof EngineBlock) { EngineBlock engineBlock = (EngineBlock) block; - AllBlockPartials frame = engineBlock.getFrameModel(); + PartialModel frame = engineBlock.getFrameModel(); if (frame != null) { Direction facing = te.getBlockState() - .get(EngineBlock.HORIZONTAL_FACING); + .get(EngineBlock.HORIZONTAL_FACING); float angle = AngleHelper.rad(AngleHelper.horizontalAngle(facing)); - frame.renderOn(te.getBlockState()) - .rotateCentered(Direction.UP, angle) - .translate(0, 0, -1) - .light(WorldRenderer.getLightmapCoordinates(te.getWorld(), te.getBlockState(), te.getPos())) - .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); + PartialBufferer.get(frame, te.getBlockState()) + .rotateCentered(Direction.UP, angle) + .translate(0, 0, -1) + .light(WorldRenderer.getLightmapCoordinates(te.getWorld(), te.getBlockState(), te.getPos())) + .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); } } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/FurnaceEngineBlock.java b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/FurnaceEngineBlock.java index 85a84e172..e50508ad0 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/FurnaceEngineBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/flywheel/engine/FurnaceEngineBlock.java @@ -5,6 +5,7 @@ import com.simibubi.create.AllBlocks; import com.simibubi.create.AllShapes; import com.simibubi.create.AllTileEntities; import com.simibubi.create.foundation.block.ITE; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.worldWrappers.WrappedWorld; import net.minecraft.block.AbstractFurnaceBlock; @@ -41,7 +42,7 @@ public class FurnaceEngineBlock extends EngineBlock implements ITE getModel() { if (blockState.get(FACING).getAxis().isHorizontal()) { BlockState referenceState = blockState.rotate(tile.getWorld(), tile.getPos(), Rotation.CLOCKWISE_180); - return AllBlockPartials.SHAFT_HALF.getModel(getRotatingMaterial(), referenceState, referenceState.get(FACING)); + Direction facing = referenceState.get(FACING); + return getRotatingMaterial().getModel(AllBlockPartials.SHAFT_HALF, referenceState, facing); } else { return getRotatingMaterial().getModel(shaft()); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/saw/SawRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/saw/SawRenderer.java index 473879dba..5ab9a2960 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/saw/SawRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/saw/SawRenderer.java @@ -9,8 +9,10 @@ import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.components.structureMovement.MovementContext; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionRenderDispatcher; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.behaviour.filtering.FilteringRenderer; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; @@ -53,7 +55,7 @@ public class SawRenderer extends SafeTileEntityRenderer { protected void renderBlade(SawTileEntity te, MatrixStack ms, IRenderTypeBuffer buffer, int light) { BlockState blockState = te.getBlockState(); SuperByteBuffer superBuffer; - AllBlockPartials partial; + PartialModel partial; float speed = te.getSpeed(); ms.push(); @@ -77,13 +79,13 @@ public class SawRenderer extends SafeTileEntityRenderer { if (!blockState.get(SawBlock.AXIS_ALONG_FIRST_COORDINATE)) MatrixStacker.of(ms) - .centre() - .rotateY(90) - .unCentre(); + .centre() + .rotateY(90) + .unCentre(); } - superBuffer = partial.renderOnDirectionalSouth(blockState); + superBuffer = PartialBufferer.getFacing(partial, blockState); superBuffer.light(light) - .renderInto(ms, buffer.getBuffer(RenderType.getCutoutMipped())); + .renderInto(ms, buffer.getBuffer(RenderType.getCutoutMipped())); ms.pop(); } @@ -140,7 +142,7 @@ public class SawRenderer extends SafeTileEntityRenderer { protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { BlockState state = te.getBlockState(); if (state.get(FACING).getAxis().isHorizontal()) - return AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(state.rotate(te.getWorld(), te.getPos(), Rotation.CLOCKWISE_180)); + return PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, state.rotate(te.getWorld(), te.getPos(), Rotation.CLOCKWISE_180)); return CreateClient.bufferCache.renderBlockIn(KineticTileEntityRenderer.KINETIC_TILE, getRenderedBlockState(te)); } @@ -171,14 +173,14 @@ public class SawRenderer extends SafeTileEntityRenderer { if (SawBlock.isHorizontal(state)) { if (shouldAnimate) - superBuffer = AllBlockPartials.SAW_BLADE_HORIZONTAL_ACTIVE.renderOn(state); + superBuffer = PartialBufferer.get(AllBlockPartials.SAW_BLADE_HORIZONTAL_ACTIVE, state); else - superBuffer = AllBlockPartials.SAW_BLADE_HORIZONTAL_INACTIVE.renderOn(state); + superBuffer = PartialBufferer.get(AllBlockPartials.SAW_BLADE_HORIZONTAL_INACTIVE, state); } else { if (shouldAnimate) - superBuffer = AllBlockPartials.SAW_BLADE_VERTICAL_ACTIVE.renderOn(state); + superBuffer = PartialBufferer.get(AllBlockPartials.SAW_BLADE_VERTICAL_ACTIVE, state); else - superBuffer = AllBlockPartials.SAW_BLADE_VERTICAL_INACTIVE.renderOn(state); + superBuffer = PartialBufferer.get(AllBlockPartials.SAW_BLADE_VERTICAL_INACTIVE, state); } for (MatrixStack m : matrixStacks) { diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingInstance.java index a4ce86d26..f3c46d7d6 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingInstance.java @@ -4,6 +4,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.BackHalfShaftInstance; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.foundation.render.backend.core.OrientedData; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.instancing.IDynamicInstance; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; import com.simibubi.create.foundation.utility.AngleHelper; @@ -31,7 +32,7 @@ public class BearingInstance e blockOrientation = getBlockStateOrientation(facing); - AllBlockPartials top = + PartialModel top = bearing.isWoodenTop() ? AllBlockPartials.BEARING_TOP_WOODEN : AllBlockPartials.BEARING_TOP; topInstance = getOrientedMaterial().getModel(top, blockState).createInstance(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingRenderer.java index 6a81320bd..cf6f59b7c 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/BearingRenderer.java @@ -4,8 +4,10 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.AngleHelper; import net.minecraft.client.renderer.IRenderTypeBuffer; @@ -30,27 +32,27 @@ public class BearingRenderer extends KineticTileEntityRenderer { IBearingTileEntity bearingTe = (IBearingTileEntity) te; final Direction facing = te.getBlockState() - .get(BlockStateProperties.FACING); - AllBlockPartials top = - bearingTe.isWoodenTop() ? AllBlockPartials.BEARING_TOP_WOODEN : AllBlockPartials.BEARING_TOP; - SuperByteBuffer superBuffer = top.renderOn(te.getBlockState()); + .get(BlockStateProperties.FACING); + PartialModel top = + bearingTe.isWoodenTop() ? AllBlockPartials.BEARING_TOP_WOODEN : AllBlockPartials.BEARING_TOP; + SuperByteBuffer superBuffer = PartialBufferer.get(top, te.getBlockState()); float interpolatedAngle = bearingTe.getInterpolatedAngle(partialTicks - 1); kineticRotationTransform(superBuffer, te, facing.getAxis(), (float) (interpolatedAngle / 180 * Math.PI), light); if (facing.getAxis() - .isHorizontal()) + .isHorizontal()) superBuffer.rotateCentered(Direction.UP, - AngleHelper.rad(AngleHelper.horizontalAngle(facing.getOpposite()))); + AngleHelper.rad(AngleHelper.horizontalAngle(facing.getOpposite()))); superBuffer.rotateCentered(Direction.EAST, AngleHelper.rad(-90 - AngleHelper.verticalAngle(facing))); superBuffer.renderInto(ms, buffer.getBuffer(RenderType.getSolid())); } @Override protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { - return AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(te.getBlockState(), te.getBlockState() - .get(BearingBlock.FACING) - .getOpposite()); + return PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, te.getBlockState(), te.getBlockState() + .get(BearingBlock.FACING) + .getOpposite()); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/StabilizedBearingMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/StabilizedBearingMovementBehaviour.java index 4db44925a..9d776cb3a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/StabilizedBearingMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/bearing/StabilizedBearingMovementBehaviour.java @@ -12,8 +12,10 @@ import com.simibubi.create.content.contraptions.components.structureMovement.Ori import com.simibubi.create.content.contraptions.components.structureMovement.render.ActorInstance; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionKineticRenderer; import com.simibubi.create.content.contraptions.components.structureMovement.render.ContraptionRenderDispatcher; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.AnimationTickHolder; import net.minecraft.client.renderer.IRenderTypeBuffer; @@ -34,8 +36,8 @@ public class StabilizedBearingMovementBehaviour extends MovementBehaviour { if (FastRenderDispatcher.available()) return; Direction facing = context.state.get(BlockStateProperties.FACING); - AllBlockPartials top = AllBlockPartials.BEARING_TOP; - SuperByteBuffer superBuffer = top.renderOn(context.state); + PartialModel top = AllBlockPartials.BEARING_TOP; + SuperByteBuffer superBuffer = PartialBufferer.get(top, context.state); float renderPartialTicks = AnimationTickHolder.getPartialTicks(); // rotate to match blockstate diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/chassis/StickerRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/chassis/StickerRenderer.java index 83679ee68..1abccec33 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/chassis/StickerRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/chassis/StickerRenderer.java @@ -2,6 +2,7 @@ package com.simibubi.create.content.contraptions.components.structureMovement.ch import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; @@ -28,7 +29,7 @@ public class StickerRenderer extends SafeTileEntityRenderer { if (FastRenderDispatcher.available(te.getWorld())) return; BlockState state = te.getBlockState(); - SuperByteBuffer head = AllBlockPartials.STICKER_HEAD.renderOn(state); + SuperByteBuffer head = PartialBufferer.get(AllBlockPartials.STICKER_HEAD, state); float offset = te.piston.getValue(AnimationTickHolder.getPartialTicks(te.getWorld())); if (te.getWorld() != Minecraft.getInstance().world && !te.isVirtual()) @@ -36,9 +37,9 @@ public class StickerRenderer extends SafeTileEntityRenderer { Direction facing = state.get(StickerBlock.FACING); head.matrixStacker() - .nudge(te.hashCode()) - .centre() - .rotateY(AngleHelper.horizontalAngle(facing)) + .nudge(te.hashCode()) + .centre() + .rotateY(AngleHelper.horizontalAngle(facing)) .rotateX(AngleHelper.verticalAngle(facing) + 90) .unCentre() .translate(0, (offset * offset) * 4 / 16f, 0); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/gantry/GantryCarriageRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/gantry/GantryCarriageRenderer.java index 8faa4f599..72152ff04 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/gantry/GantryCarriageRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/gantry/GantryCarriageRenderer.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AngleHelper; @@ -54,16 +55,16 @@ public class GantryCarriageRenderer extends KineticTileEntityRenderer { if (facing == Direction.NORTH || facing == Direction.EAST) angleForTe *= -1; - SuperByteBuffer cogs = AllBlockPartials.GANTRY_COGS.renderOn(state); + SuperByteBuffer cogs = PartialBufferer.get(AllBlockPartials.GANTRY_COGS, state); cogs.matrixStacker() - .centre() - .rotateY(AngleHelper.horizontalAngle(facing)) - .rotateX(facing == Direction.UP ? 0 : facing == Direction.DOWN ? 180 : 90) - .rotateY(alongFirst ^ facing.getAxis() == Axis.Z ? 90 : 0) - .translate(0, -9 / 16f, 0) - .multiply(Vector3f.POSITIVE_X.getRadialQuaternion(-angleForTe)) - .translate(0, 9 / 16f, 0) - .unCentre(); + .centre() + .rotateY(AngleHelper.horizontalAngle(facing)) + .rotateX(facing == Direction.UP ? 0 : facing == Direction.DOWN ? 180 : 90) + .rotateY(alongFirst ^ facing.getAxis() == Axis.Z ? 90 : 0) + .translate(0, -9 / 16f, 0) + .multiply(Vector3f.POSITIVE_X.getRadialQuaternion(-angleForTe)) + .translate(0, 9 / 16f, 0) + .unCentre(); cogs.light(light) .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/AbstractPulleyRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/AbstractPulleyRenderer.java index f707114df..481b065d0 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/AbstractPulleyRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/AbstractPulleyRenderer.java @@ -2,12 +2,13 @@ package com.simibubi.create.content.contraptions.components.structureMovement.pu import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.IRotate; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.AngleHelper; import net.minecraft.block.BlockState; @@ -24,11 +25,11 @@ import net.minecraft.world.World; public abstract class AbstractPulleyRenderer extends KineticTileEntityRenderer { - private AllBlockPartials halfRope; - private AllBlockPartials halfMagnet; + private PartialModel halfRope; + private PartialModel halfMagnet; - public AbstractPulleyRenderer(TileEntityRendererDispatcher dispatcher, AllBlockPartials halfRope, - AllBlockPartials halfMagnet) { + public AbstractPulleyRenderer(TileEntityRendererDispatcher dispatcher, PartialModel halfRope, + PartialModel halfMagnet) { super(dispatcher); this.halfRope = halfRope; this.halfMagnet = halfMagnet; @@ -50,16 +51,16 @@ public abstract class AbstractPulleyRenderer extends KineticTileEntityRenderer { boolean running = isRunning(te); Axis rotationAxis = ((IRotate) te.getBlockState() - .getBlock()).getRotationAxis(te.getBlockState()); + .getBlock()).getRotationAxis(te.getBlockState()); kineticRotationTransform(getRotatedCoil(te), te, rotationAxis, AngleHelper.rad(offset * 180), light) - .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); + .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); World world = te.getWorld(); BlockState blockState = te.getBlockState(); BlockPos pos = te.getPos(); - SuperByteBuffer halfMagnet = this.halfMagnet.renderOn(blockState); - SuperByteBuffer halfRope = this.halfRope.renderOn(blockState); + SuperByteBuffer halfMagnet = PartialBufferer.get(this.halfMagnet, blockState); + SuperByteBuffer halfRope = PartialBufferer.get(this.halfRope, blockState); SuperByteBuffer magnet = renderMagnet(te); SuperByteBuffer rope = renderRope(te); @@ -89,7 +90,7 @@ public abstract class AbstractPulleyRenderer extends KineticTileEntityRenderer { protected abstract Axis getShaftAxis(KineticTileEntity te); - protected abstract AllBlockPartials getCoil(); + protected abstract PartialModel getCoil(); protected abstract SuperByteBuffer renderRope(KineticTileEntity te); @@ -106,8 +107,7 @@ public abstract class AbstractPulleyRenderer extends KineticTileEntityRenderer { protected SuperByteBuffer getRotatedCoil(KineticTileEntity te) { BlockState blockState = te.getBlockState(); - return getCoil().renderOnDirectionalSouth(blockState, - Direction.getFacingFromAxis(AxisDirection.POSITIVE, getShaftAxis(te))); + return PartialBufferer.getFacing(getCoil(), blockState, Direction.getFacingFromAxis(AxisDirection.POSITIVE, getShaftAxis(te))); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/HosePulleyInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/HosePulleyInstance.java index 8003596b2..a1adb0e43 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/HosePulleyInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/HosePulleyInstance.java @@ -28,7 +28,7 @@ public class HosePulleyInstance extends AbstractPulleyInstance { } protected InstancedModel getCoilModel() { - return AllBlockPartials.HOSE_COIL.getModel(getOrientedMaterial(), blockState, rotatingAbout); + return getOrientedMaterial().getModel(AllBlockPartials.HOSE_COIL, blockState, rotatingAbout); } protected InstancedModel getHalfRopeModel() { diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/PulleyRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/PulleyRenderer.java index 740302722..4db922553 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/PulleyRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/PulleyRenderer.java @@ -6,6 +6,7 @@ import com.simibubi.create.CreateClient; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.components.structureMovement.AbstractContraptionEntity; import com.simibubi.create.foundation.render.SuperByteBuffer; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.util.Direction.Axis; @@ -24,7 +25,7 @@ public class PulleyRenderer extends AbstractPulleyRenderer { } @Override - protected AllBlockPartials getCoil() { + protected PartialModel getCoil() { return AllBlockPartials.ROPE_COIL; } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/RopePulleyInstance.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/RopePulleyInstance.java index 8eb8388e4..a3bf2dd82 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/RopePulleyInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/pulley/RopePulleyInstance.java @@ -29,7 +29,7 @@ public class RopePulleyInstance extends AbstractPulleyInstance { } protected InstancedModel getCoilModel() { - return AllBlockPartials.ROPE_COIL.getModel(getOrientedMaterial(), blockState, rotatingAbout); + return getOrientedMaterial().getModel(AllBlockPartials.ROPE_COIL, blockState, rotatingAbout); } protected InstancedModel getHalfRopeModel() { diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/render/ContraptionRenderDispatcher.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/render/ContraptionRenderDispatcher.java index 2674f778a..83c39757f 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/render/ContraptionRenderDispatcher.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/render/ContraptionRenderDispatcher.java @@ -44,7 +44,6 @@ import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Matrix4f; -import net.minecraft.world.IBlockDisplayReader; import net.minecraft.world.LightType; import net.minecraft.world.World; import net.minecraft.world.gen.feature.template.Template; @@ -52,57 +51,27 @@ import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.model.data.EmptyModelData; public class ContraptionRenderDispatcher { - public static final Int2ObjectMap renderers = new Int2ObjectOpenHashMap<>(); - public static final Compartment> CONTRAPTION = new Compartment<>(); - protected static PlacementSimulationWorld renderWorld; + public static final Int2ObjectMap renderers = new Int2ObjectOpenHashMap<>(); + public static final Compartment> CONTRAPTION = new Compartment<>(); + protected static PlacementSimulationWorld renderWorld; - public static void notifyLightPacket(IBlockDisplayReader world, int chunkX, int chunkZ) { - for (RenderedContraption renderer : renderers.values()) { - renderer.getLighter().lightVolume.notifyLightPacket(world, chunkX, chunkZ); - } - } + public static void tick() { + if (Minecraft.getInstance().isGamePaused()) return; - public static void renderTileEntities(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, - IRenderTypeBuffer buffer) { - PlacementSimulationWorld renderWorld = null; - if (Backend.canUseVBOs()) { - RenderedContraption renderer = getRenderer(world, c); + for (RenderedContraption contraption : renderers.values()) { + contraption.getLighter().tick(contraption); - renderWorld = renderer.renderWorld; - } - TileEntityRenderHelper.renderTileEntities(world, renderWorld, c.specialRenderedTileEntities, ms, msLocal, buffer); + contraption.kinetics.tick(); + } + } - } + public static void beginFrame(ActiveRenderInfo info, double camX, double camY, double camZ) { + for (RenderedContraption renderer : renderers.values()) { + renderer.beginFrame(info, camX, camY, camZ); + } + } - public static void tick() { - if (Minecraft.getInstance().isGamePaused()) return; - - for (RenderedContraption contraption : renderers.values()) { - contraption.getLighter().tick(contraption); - - contraption.kinetics.tick(); - } - } - - private static RenderedContraption getRenderer(World world, Contraption c) { - int entityId = c.entity.getEntityId(); - RenderedContraption contraption = renderers.get(entityId); - - if (contraption == null) { - contraption = new RenderedContraption(world, c); - renderers.put(entityId, contraption); - } - - return contraption; - } - - public static void beginFrame(ActiveRenderInfo info, double camX, double camY, double camZ) { - for (RenderedContraption renderer : renderers.values()) { - renderer.beginFrame(info, camX, camY, camZ); - } - } - - public static void renderLayer(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ) { + public static void renderLayer(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ) { removeDeadContraptions(); if (renderers.isEmpty()) return; @@ -121,79 +90,110 @@ public class ContraptionRenderDispatcher { if (Backend.canUseInstancing()) { for (RenderedContraption renderer : renderers.values()) { - renderer.kinetics.render(layer, viewProjection, camX, camY, camZ, renderer::setup); - renderer.teardown(); - } - } + renderer.kinetics.render(layer, viewProjection, camX, camY, camZ, renderer::setup); + renderer.teardown(); + } + } - layer.endDrawing(); - GL11.glDisable(GL13.GL_TEXTURE_3D); - GL13.glActiveTexture(GL40.GL_TEXTURE0); - } + layer.endDrawing(); + GL11.glDisable(GL13.GL_TEXTURE_3D); + GL13.glActiveTexture(GL40.GL_TEXTURE0); + } - public static void removeDeadContraptions() { - renderers.values().removeIf(renderer -> { - if (renderer.isDead()) { - renderer.invalidate(); - return true; - } - return false; - }); - } + private static RenderedContraption getRenderer(World world, Contraption c) { + int entityId = c.entity.getEntityId(); + RenderedContraption contraption = renderers.get(entityId); - public static void invalidateAll() { - for (RenderedContraption renderer : renderers.values()) { - renderer.invalidate(); - } + if (contraption == null) { + contraption = new RenderedContraption(world, c); + renderers.put(entityId, contraption); + } - renderers.clear(); - } + return contraption; + } - public static void render(AbstractContraptionEntity entity, MatrixStack ms, IRenderTypeBuffer buffers, - MatrixStack msLocal, Contraption contraption) { - if (Backend.canUseVBOs()) { - ContraptionRenderDispatcher.renderDynamic(entity.world, contraption, ms, msLocal, buffers); - } else { - ContraptionRenderDispatcher.renderDynamic(entity.world, contraption, ms, msLocal, buffers); - ContraptionRenderDispatcher.renderStructure(entity.world, contraption, ms, msLocal, buffers); - } - } + public static void render(AbstractContraptionEntity entity, MatrixStack ms, IRenderTypeBuffer buffers, + MatrixStack msLocal, Contraption contraption) { + if (Backend.canUseVBOs() && Backend.isFlywheelWorld(entity.world)) { + ContraptionRenderDispatcher.renderDynamic(entity.world, contraption, ms, msLocal, buffers); + } else { + ContraptionRenderDispatcher.renderDynamic(entity.world, contraption, ms, msLocal, buffers); + ContraptionRenderDispatcher.renderStructure(entity.world, contraption, ms, msLocal, buffers); + } + } - public static void renderDynamic(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, - IRenderTypeBuffer buffer) { - renderTileEntities(world, c, ms, msLocal, buffer); - if (buffer instanceof IRenderTypeBuffer.Impl) - ((IRenderTypeBuffer.Impl) buffer).draw(); - renderActors(world, c, ms, msLocal, buffer); - } + public static void renderStructure(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, + IRenderTypeBuffer buffer) { + SuperByteBufferCache bufferCache = CreateClient.bufferCache; + List blockLayers = RenderType.getBlockLayers(); - public static void renderStructure(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, - IRenderTypeBuffer buffer) { - SuperByteBufferCache bufferCache = CreateClient.bufferCache; - List blockLayers = RenderType.getBlockLayers(); + buffer.getBuffer(RenderType.getSolid()); + for (int i = 0; i < blockLayers.size(); i++) { + RenderType layer = blockLayers.get(i); + Pair key = Pair.of(c, i); + SuperByteBuffer contraptionBuffer = bufferCache.get(CONTRAPTION, key, () -> buildStructureBuffer(c, layer)); + if (contraptionBuffer.isEmpty()) + continue; + Matrix4f model = msLocal.peek() + .getModel(); + contraptionBuffer.light(model) + .renderInto(ms, buffer.getBuffer(layer)); + } + } - buffer.getBuffer(RenderType.getSolid()); - for (int i = 0; i < blockLayers.size(); i++) { - RenderType layer = blockLayers.get(i); - Pair key = Pair.of(c, i); - SuperByteBuffer contraptionBuffer = bufferCache.get(CONTRAPTION, key, () -> buildStructureBuffer(c, layer)); - if (contraptionBuffer.isEmpty()) - continue; - Matrix4f model = msLocal.peek() - .getModel(); - contraptionBuffer.light(model) - .renderInto(ms, buffer.getBuffer(layer)); - } - } + public static void renderDynamic(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, + IRenderTypeBuffer buffer) { + renderTileEntities(world, c, ms, msLocal, buffer); + if (buffer instanceof IRenderTypeBuffer.Impl) + ((IRenderTypeBuffer.Impl) buffer).draw(); + renderActors(world, c, ms, msLocal, buffer); + } - private static SuperByteBuffer buildStructureBuffer(Contraption c, RenderType layer) { - BufferBuilder builder = buildStructure(c, layer); - return new SuperByteBuffer(builder); - } + public static void renderTileEntities(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, + IRenderTypeBuffer buffer) { + PlacementSimulationWorld renderWorld = null; + if (Backend.canUseVBOs() && Backend.isFlywheelWorld(world)) { + RenderedContraption renderer = getRenderer(world, c); - public static BufferBuilder buildStructure(Contraption c, RenderType layer) { - if (renderWorld == null || renderWorld.getWorld() != Minecraft.getInstance().world) - renderWorld = new PlacementSimulationWorld(Minecraft.getInstance().world); + renderWorld = renderer.renderWorld; + } + TileEntityRenderHelper.renderTileEntities(world, renderWorld, c.specialRenderedTileEntities, ms, msLocal, buffer); + + } + + protected static void renderActors(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, + IRenderTypeBuffer buffer) { + MatrixStack[] matrixStacks = new MatrixStack[]{ms, msLocal}; + for (Pair actor : c.getActors()) { + MovementContext context = actor.getRight(); + if (context == null) + continue; + if (context.world == null) + context.world = world; + Template.BlockInfo blockInfo = actor.getLeft(); + for (MatrixStack m : matrixStacks) { + m.push(); + MatrixStacker.of(m) + .translate(blockInfo.pos); + } + + MovementBehaviour movementBehaviour = AllMovementBehaviours.of(blockInfo.state); + if (movementBehaviour != null) + movementBehaviour.renderInContraption(context, ms, msLocal, buffer); + + for (MatrixStack m : matrixStacks) + m.pop(); + } + } + + private static SuperByteBuffer buildStructureBuffer(Contraption c, RenderType layer) { + BufferBuilder builder = buildStructure(c, layer); + return new SuperByteBuffer(builder); + } + + public static BufferBuilder buildStructure(Contraption c, RenderType layer) { + if (renderWorld == null || renderWorld.getWorld() != Minecraft.getInstance().world) + renderWorld = new PlacementSimulationWorld(Minecraft.getInstance().world); ForgeHooksClient.setRenderLayer(layer); MatrixStack ms = new MatrixStack(); @@ -232,31 +232,6 @@ public class ContraptionRenderDispatcher { return builder; } - protected static void renderActors(World world, Contraption c, MatrixStack ms, MatrixStack msLocal, - IRenderTypeBuffer buffer) { - MatrixStack[] matrixStacks = new MatrixStack[] { ms, msLocal }; - for (Pair actor : c.getActors()) { - MovementContext context = actor.getRight(); - if (context == null) - continue; - if (context.world == null) - context.world = world; - Template.BlockInfo blockInfo = actor.getLeft(); - for (MatrixStack m : matrixStacks) { - m.push(); - MatrixStacker.of(m) - .translate(blockInfo.pos); - } - - MovementBehaviour movementBehaviour = AllMovementBehaviours.of(blockInfo.state); - if (movementBehaviour != null) - movementBehaviour.renderInContraption(context, ms, msLocal, buffer); - - for (MatrixStack m : matrixStacks) - m.pop(); - } - } - public static int getLight(World world, float lx, float ly, float lz) { BlockPos.Mutable pos = new BlockPos.Mutable(); float sky = 0, block = 0; @@ -292,14 +267,32 @@ public class ContraptionRenderDispatcher { return packedLight; } - public static int getLightOnContraption(MovementContext context) { - int entityId = context.contraption.entity.getEntityId(); + public static int getLightOnContraption(MovementContext context) { + int entityId = context.contraption.entity.getEntityId(); - RenderedContraption renderedContraption = renderers.get(entityId); - if (renderedContraption != null) { - return renderedContraption.renderWorld.getLightLevel(LightType.BLOCK, context.localPos); - } else { - return -1; - } - } + RenderedContraption renderedContraption = renderers.get(entityId); + if (renderedContraption != null) { + return renderedContraption.renderWorld.getLightLevel(LightType.BLOCK, context.localPos); + } else { + return -1; + } + } + + public static void invalidateAll() { + for (RenderedContraption renderer : renderers.values()) { + renderer.invalidate(); + } + + renderers.clear(); + } + + public static void removeDeadContraptions() { + renderers.values().removeIf(renderer -> { + if (renderer.isDead()) { + renderer.invalidate(); + return true; + } + return false; + }); + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/train/CouplingRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/train/CouplingRenderer.java index 9b5544c1b..0a6edeb8d 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/train/CouplingRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/train/CouplingRenderer.java @@ -8,6 +8,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.CreateClient; import com.simibubi.create.content.contraptions.KineticDebugger; import com.simibubi.create.content.contraptions.components.structureMovement.train.capability.MinecartController; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.utility.AnimationTickHolder; import com.simibubi.create.foundation.utility.ColorHelper; @@ -36,7 +37,7 @@ public class CouplingRenderer { c -> { if (c.getFirst().hasContraptionCoupling(true)) return; - CouplingRenderer.renderCoupling(ms, buffer, c.map(MinecartController::cart)); + CouplingRenderer.renderCoupling(ms, buffer, c.map(MinecartController::cart)); }); } @@ -47,37 +48,37 @@ public class CouplingRenderer { public static void renderCoupling(MatrixStack ms, IRenderTypeBuffer buffer, Couple carts) { ClientWorld world = Minecraft.getInstance().world; - + if (carts.getFirst() == null || carts.getSecond() == null) return; - + Couple lightValues = carts.map(c -> WorldRenderer.getLightmapCoordinates(world, new BlockPos(c.getBoundingBox() .getCenter()))); Vector3d center = carts.getFirst() - .getPositionVec() - .add(carts.getSecond() - .getPositionVec()) - .scale(.5f); + .getPositionVec() + .add(carts.getSecond() + .getPositionVec()) + .scale(.5f); Couple transforms = carts.map(c -> getSuitableCartEndpoint(c, center)); BlockState renderState = Blocks.AIR.getDefaultState(); IVertexBuilder builder = buffer.getBuffer(RenderType.getSolid()); - SuperByteBuffer attachment = AllBlockPartials.COUPLING_ATTACHMENT.renderOn(renderState); - SuperByteBuffer ring = AllBlockPartials.COUPLING_RING.renderOn(renderState); - SuperByteBuffer connector = AllBlockPartials.COUPLING_CONNECTOR.renderOn(renderState); + SuperByteBuffer attachment = PartialBufferer.get(AllBlockPartials.COUPLING_ATTACHMENT, renderState); + SuperByteBuffer ring = PartialBufferer.get(AllBlockPartials.COUPLING_RING, renderState); + SuperByteBuffer connector = PartialBufferer.get(AllBlockPartials.COUPLING_CONNECTOR, renderState); Vector3d zero = Vector3d.ZERO; Vector3d firstEndpoint = transforms.getFirst() - .apply(zero); + .apply(zero); Vector3d secondEndpoint = transforms.getSecond() - .apply(zero); + .apply(zero); Vector3d endPointDiff = secondEndpoint.subtract(firstEndpoint); double connectorYaw = -Math.atan2(endPointDiff.z, endPointDiff.x) * 180.0D / Math.PI; double connectorPitch = Math.atan2(endPointDiff.y, endPointDiff.mul(1, 0, 1) - .length()) * 180 / Math.PI; + .length()) * 180 / Math.PI; MatrixStacker msr = MatrixStacker.of(ms); carts.forEachWithContext((cart, isFirst) -> { diff --git a/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpCogInstance.java b/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpCogInstance.java index 202a93992..470b5ab4e 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpCogInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpCogInstance.java @@ -10,6 +10,7 @@ import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRenderer; import net.minecraft.block.BlockState; +import net.minecraft.util.Direction; public class PumpCogInstance extends SingleRotatingInstance { @@ -19,7 +20,8 @@ public class PumpCogInstance extends SingleRotatingInstance { @Override protected InstancedModel getModel() { - BlockState referenceState = tile.getBlockState(); - return AllBlockPartials.MECHANICAL_PUMP_COG.getModel(getRotatingMaterial(), referenceState, referenceState.get(FACING)); - } + BlockState referenceState = tile.getBlockState(); + Direction facing = referenceState.get(FACING); + return getRotatingMaterial().getModel(AllBlockPartials.MECHANICAL_PUMP_COG, referenceState, facing); + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpRenderer.java index d8dd29f3d..8ecc077a4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/fluids/PumpRenderer.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.utility.AngleHelper; import com.simibubi.create.foundation.utility.MatrixStacker; @@ -34,17 +35,17 @@ public class PumpRenderer extends KineticTileEntityRenderer { float angle = MathHelper.lerp(pump.arrowDirection.getValue(partialTicks), 0, 90) - 90; for (float yRot : new float[] { 0, 90 }) { ms.push(); - SuperByteBuffer arrow = AllBlockPartials.MECHANICAL_PUMP_ARROW.renderOn(blockState); + SuperByteBuffer arrow = PartialBufferer.get(AllBlockPartials.MECHANICAL_PUMP_ARROW, blockState); Direction direction = blockState.get(PumpBlock.FACING); MatrixStacker.of(ms) - .centre() - .rotateY(AngleHelper.horizontalAngle(direction) + 180) - .rotateX(-AngleHelper.verticalAngle(direction) - 90) - .unCentre() - .translate(rotationOffset) - .rotateY(yRot) - .rotateZ(angle) - .translateBack(rotationOffset); + .centre() + .rotateY(AngleHelper.horizontalAngle(direction) + 180) + .rotateX(-AngleHelper.verticalAngle(direction) - 90) + .unCentre() + .translate(rotationOffset) + .rotateY(yRot) + .rotateZ(angle) + .translateBack(rotationOffset); arrow.light(light).renderInto(ms, buffer.getBuffer(RenderType.getSolid())); ms.pop(); } @@ -52,7 +53,7 @@ public class PumpRenderer extends KineticTileEntityRenderer { @Override protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { - return AllBlockPartials.MECHANICAL_PUMP_COG.renderOnDirectionalSouth(te.getBlockState()); + return PartialBufferer.getFacing(AllBlockPartials.MECHANICAL_PUMP_COG, te.getBlockState()); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java index c0d4091c6..3e1a43506 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/HosePulleyRenderer.java @@ -3,7 +3,9 @@ package com.simibubi.create.content.contraptions.fluids.actors; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.components.structureMovement.pulley.AbstractPulleyRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.util.Direction.Axis; @@ -23,18 +25,18 @@ public class HosePulleyRenderer extends AbstractPulleyRenderer { } @Override - protected AllBlockPartials getCoil() { + protected PartialModel getCoil() { return AllBlockPartials.HOSE_COIL; } @Override protected SuperByteBuffer renderRope(KineticTileEntity te) { - return AllBlockPartials.HOSE.renderOn(te.getBlockState()); + return PartialBufferer.get(AllBlockPartials.HOSE, te.getBlockState()); } @Override protected SuperByteBuffer renderMagnet(KineticTileEntity te) { - return AllBlockPartials.HOSE_MAGNET.renderOn(te.getBlockState()); + return PartialBufferer.get(AllBlockPartials.HOSE_MAGNET, te.getBlockState()); } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/SpoutRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/SpoutRenderer.java index cc4eaa7a4..2cbacbd36 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/SpoutRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/fluids/actors/SpoutRenderer.java @@ -3,6 +3,8 @@ package com.simibubi.create.content.contraptions.fluids.actors; import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.foundation.fluid.FluidRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.behaviour.fluid.SmartFluidTankBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.fluid.SmartFluidTankBehaviour.TankSegment; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; @@ -20,7 +22,7 @@ public class SpoutRenderer extends SafeTileEntityRenderer { super(dispatcher); } - static final AllBlockPartials[] BITS = + static final PartialModel[] BITS = { AllBlockPartials.SPOUT_TOP, AllBlockPartials.SPOUT_MIDDLE, AllBlockPartials.SPOUT_BOTTOM }; @Override @@ -69,10 +71,10 @@ public class SpoutRenderer extends SafeTileEntityRenderer { squeeze = -1; ms.push(); - for (AllBlockPartials bit : BITS) { - bit.renderOn(te.getBlockState()) - .light(light) - .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); + for (PartialModel bit : BITS) { + PartialBufferer.get(bit, te.getBlockState()) + .light(light) + .renderInto(ms, buffer.getBuffer(RenderType.getSolid())); ms.translate(0, -3 * squeeze / 32f, 0); } ms.pop(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/fluids/pipes/FluidValveRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/fluids/pipes/FluidValveRenderer.java index 14439f84a..3d3a02951 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/fluids/pipes/FluidValveRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/fluids/pipes/FluidValveRenderer.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AngleHelper; @@ -31,7 +32,7 @@ public class FluidValveRenderer extends KineticTileEntityRenderer { super.renderSafe(te, partialTicks, ms, buffer, light, overlay); BlockState blockState = te.getBlockState(); - SuperByteBuffer pointer = AllBlockPartials.FLUID_VALVE_POINTER.renderOn(blockState); + SuperByteBuffer pointer = PartialBufferer.get(AllBlockPartials.FLUID_VALVE_POINTER, blockState); Direction facing = blockState.get(FluidValveBlock.FACING); if (!(te instanceof FluidValveTileEntity)) diff --git a/src/main/java/com/simibubi/create/content/contraptions/goggles/GogglesModel.java b/src/main/java/com/simibubi/create/content/contraptions/goggles/GogglesModel.java index 333f65bbd..0702465f7 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/goggles/GogglesModel.java +++ b/src/main/java/com/simibubi/create/content/contraptions/goggles/GogglesModel.java @@ -21,4 +21,4 @@ public class GogglesModel extends WrappedBakedModel { return super.handlePerspective(cameraTransformType, mat); } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/contraptions/processing/burner/BlazeBurnerRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/processing/burner/BlazeBurnerRenderer.java index df11ef484..1d3765ac6 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/processing/burner/BlazeBurnerRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/processing/burner/BlazeBurnerRenderer.java @@ -3,7 +3,9 @@ package com.simibubi.create.content.contraptions.processing.burner; import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.processing.burner.BlazeBurnerBlock.HeatLevel; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -30,11 +32,11 @@ public class BlazeBurnerRenderer extends SafeTileEntityRenderer { DyeColor color = tile.color.orElse(null); for (boolean bottom : Iterate.trueAndFalse) { - AllBlockPartials beltPartial = BeltRenderer.getBeltPartial(diagonal, start, end, bottom); + PartialModel beltPartial = BeltRenderer.getBeltPartial(diagonal, start, end, bottom); SpriteShiftEntry spriteShift = BeltRenderer.getSpriteShiftEntry(color, diagonal, bottom); InstancedModel beltModel = modelManager.getMaterial(KineticRenderMaterials.BELTS).getModel(beltPartial, blockState); diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/belt/BeltRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/relays/belt/BeltRenderer.java index 6b8ace415..4beec3bb0 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/belt/BeltRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/belt/BeltRenderer.java @@ -1,6 +1,7 @@ package com.simibubi.create.content.contraptions.relays.belt; import java.util.Random; +import java.util.function.Supplier; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; @@ -11,9 +12,11 @@ import com.simibubi.create.CreateClient; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.relays.belt.transport.TransportedItemStack; import com.simibubi.create.foundation.block.render.SpriteShiftEntry; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.ShadowRenderHelper; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -93,10 +96,10 @@ public class BeltRenderer extends SafeTileEntityRenderer { for (boolean bottom : Iterate.trueAndFalse) { - AllBlockPartials beltPartial = getBeltPartial(diagonal, start, end, bottom); + PartialModel beltPartial = getBeltPartial(diagonal, start, end, bottom); - SuperByteBuffer beltBuffer = beltPartial.renderOn(blockState) - .light(light); + SuperByteBuffer beltBuffer = PartialBufferer.get(beltPartial, blockState) + .light(light); SpriteShiftEntry spriteShift = getSpriteShiftEntry(color, diagonal, bottom); @@ -127,18 +130,20 @@ public class BeltRenderer extends SafeTileEntityRenderer { } if (te.hasPulley()) { - // TODO 1.15 find a way to cache this model matrix computation - MatrixStack modelTransform = new MatrixStack(); - Direction dir = blockState.get(BeltBlock.HORIZONTAL_FACING).rotateY(); - if (sideways) dir = Direction.UP; - msr = MatrixStacker.of(modelTransform); - msr.centre(); - if (dir.getAxis() == Axis.X) msr.rotateY(90); - if (dir.getAxis() == Axis.Y) msr.rotateX(90); - msr.rotateX(90); - msr.unCentre(); + Direction dir = sideways ? Direction.UP : blockState.get(BeltBlock.HORIZONTAL_FACING).rotateY(); - SuperByteBuffer superBuffer = CreateClient.bufferCache.renderDirectionalPartial(AllBlockPartials.BELT_PULLEY, blockState, dir, modelTransform); + Supplier matrixStackSupplier = () -> { + MatrixStack stack = new MatrixStack(); + MatrixStacker stacker = MatrixStacker.of(stack); + stacker.centre(); + if (dir.getAxis() == Axis.X) stacker.rotateY(90); + if (dir.getAxis() == Axis.Y) stacker.rotateX(90); + stacker.rotateX(90); + stacker.unCentre(); + return stack; + }; + + SuperByteBuffer superBuffer = CreateClient.bufferCache.renderDirectionalPartial(AllBlockPartials.BELT_PULLEY, blockState, dir, matrixStackSupplier); KineticTileEntityRenderer.standardKineticRotationTransform(superBuffer, te, light).renderInto(ms, vb); } } @@ -155,7 +160,7 @@ public class BeltRenderer extends SafeTileEntityRenderer { : bottom ? AllSpriteShifts.BELT_OFFSET : AllSpriteShifts.BELT; } - public static AllBlockPartials getBeltPartial(boolean diagonal, boolean start, boolean end, boolean bottom) { + public static PartialModel getBeltPartial(boolean diagonal, boolean start, boolean end, boolean bottom) { if (diagonal) { if (start) return AllBlockPartials.BELT_DIAGONAL_START; if (end) return AllBlockPartials.BELT_DIAGONAL_END; diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftInstance.java b/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftInstance.java index 92eab7077..f317fd24d 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftInstance.java @@ -30,12 +30,12 @@ public class SplitShaftInstance extends KineticTileInstance half = AllBlockPartials.SHAFT_HALF.getModel(rotatingMaterial, blockState, dir); + InstancedModel half = rotatingMaterial.getModel(AllBlockPartials.SHAFT_HALF, blockState, dir); - float splitSpeed = speed * tile.getRotationSpeedModifier(dir); + float splitSpeed = speed * tile.getRotationSpeedModifier(dir); - keys.add(setup(half.createInstance(), splitSpeed)); - } + keys.add(setup(half.createInstance(), splitSpeed)); + } } @Override diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftRenderer.java index a1cf575af..cac191681 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/encased/SplitShaftRenderer.java @@ -5,6 +5,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.IRotate; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -51,7 +52,7 @@ public class SplitShaftRenderer extends KineticTileEntityRenderer { angle = angle / 180f * (float) Math.PI; SuperByteBuffer superByteBuffer = - AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(te.getBlockState(), direction); + PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, te.getBlockState(), direction); kineticRotationTransform(superByteBuffer, te, axis, angle, light); superByteBuffer.renderInto(ms, buffer.getBuffer(RenderType.getSolid())); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/gauge/GaugeRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/relays/gauge/GaugeRenderer.java index bc89519bb..56c9fb89b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/gauge/GaugeRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/gauge/GaugeRenderer.java @@ -6,8 +6,10 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.contraptions.relays.gauge.GaugeBlock.Type; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Iterate; import net.minecraft.block.BlockState; @@ -25,11 +27,11 @@ public class GaugeRenderer extends KineticTileEntityRenderer { public static GaugeRenderer speed(TileEntityRendererDispatcher dispatcher) { return new GaugeRenderer(dispatcher, Type.SPEED); } - + public static GaugeRenderer stress(TileEntityRendererDispatcher dispatcher) { return new GaugeRenderer(dispatcher, Type.STRESS); } - + protected GaugeRenderer(TileEntityRendererDispatcher dispatcher, GaugeBlock.Type type) { super(dispatcher); this.type = type; @@ -45,17 +47,17 @@ public class GaugeRenderer extends KineticTileEntityRenderer { GaugeTileEntity gaugeTE = (GaugeTileEntity) te; int lightCoords = WorldRenderer.getLightmapCoordinates(te.getWorld(), gaugeState, te.getPos()); + PartialModel partialModel = (type == Type.SPEED ? AllBlockPartials.GAUGE_HEAD_SPEED : AllBlockPartials.GAUGE_HEAD_STRESS); SuperByteBuffer headBuffer = - (type == Type.SPEED ? AllBlockPartials.GAUGE_HEAD_SPEED : AllBlockPartials.GAUGE_HEAD_STRESS) - .renderOn(gaugeState); - SuperByteBuffer dialBuffer = AllBlockPartials.GAUGE_DIAL.renderOn(gaugeState); + PartialBufferer.get(partialModel, gaugeState); + SuperByteBuffer dialBuffer = PartialBufferer.get(AllBlockPartials.GAUGE_DIAL, gaugeState); float dialPivot = 5.75f / 16; float progress = MathHelper.lerp(partialTicks, gaugeTE.prevDialState, gaugeTE.dialState); for (Direction facing : Iterate.directions) { if (!((GaugeBlock) gaugeState.getBlock()).shouldRenderHeadOnFace(te.getWorld(), te.getPos(), gaugeState, - facing)) + facing)) continue; IVertexBuilder vb = buffer.getBuffer(RenderType.getSolid()); diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxInstance.java b/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxInstance.java index 62a2cd6b2..a991802fa 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxInstance.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxInstance.java @@ -36,20 +36,20 @@ public class GearboxInstance extends KineticTileInstance { RenderMaterial> rotatingMaterial = getRotatingMaterial(); for (Direction direction : Iterate.directions) { - final Direction.Axis axis = direction.getAxis(); - if (boxAxis == axis) - continue; + final Direction.Axis axis = direction.getAxis(); + if (boxAxis == axis) + continue; - InstancedModel shaft = AllBlockPartials.SHAFT_HALF.getModel(rotatingMaterial, blockState, direction); + InstancedModel shaft = rotatingMaterial.getModel(AllBlockPartials.SHAFT_HALF, blockState, direction); - RotatingData key = shaft.createInstance(); + RotatingData key = shaft.createInstance(); - key.setRotationAxis(Direction.getFacingFromAxis(Direction.AxisDirection.POSITIVE, axis).getUnitVector()) - .setRotationalSpeed(getSpeed(direction)) - .setRotationOffset(getRotationOffset(axis)).setColor(tile) - .setPosition(getInstancePosition()) - .setBlockLight(blockLight) - .setSkyLight(skyLight); + key.setRotationAxis(Direction.getFacingFromAxis(Direction.AxisDirection.POSITIVE, axis).getUnitVector()) + .setRotationalSpeed(getSpeed(direction)) + .setRotationOffset(getRotationOffset(axis)).setColor(tile) + .setPosition(getInstancePosition()) + .setBlockLight(blockLight) + .setSkyLight(skyLight); keys.put(direction, key); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxRenderer.java b/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxRenderer.java index 45463f007..72c2e09e8 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxRenderer.java +++ b/src/main/java/com/simibubi/create/content/contraptions/relays/gearbox/GearboxRenderer.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -37,7 +38,7 @@ public class GearboxRenderer extends KineticTileEntityRenderer { if (boxAxis == axis) continue; - SuperByteBuffer shaft = AllBlockPartials.SHAFT_HALF.renderOnDirectionalSouth(te.getBlockState(), direction); + SuperByteBuffer shaft = PartialBufferer.getFacing(AllBlockPartials.SHAFT_HALF, te.getBlockState(), direction); float offset = getRotationOffsetForPosition(te, pos, axis); float angle = (time * te.getSpeed() * 3f / 10) % 360; diff --git a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/CrossPlaneMirror.java b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/CrossPlaneMirror.java index ccdd17720..805673bec 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/CrossPlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/CrossPlaneMirror.java @@ -7,6 +7,7 @@ import java.util.Map; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Lang; import com.simibubi.create.foundation.utility.MatrixStacker; @@ -86,7 +87,7 @@ public class CrossPlaneMirror extends SymmetryMirror { } @Override - public AllBlockPartials getModel() { + public PartialModel getModel() { return AllBlockPartials.SYMMETRY_CROSSPLANE; } diff --git a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/EmptyMirror.java b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/EmptyMirror.java index d7cdd00b5..9e953ae5b 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/EmptyMirror.java +++ b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/EmptyMirror.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableList; -import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import net.minecraft.block.BlockState; import net.minecraft.util.IStringSerializable; @@ -17,13 +17,13 @@ public class EmptyMirror extends SymmetryMirror { public static enum Align implements IStringSerializable { None("none"); - + private final String name; private Align(String name) { this.name = name; } @Override public String getString() { return name; } @Override public String toString() { return name; } } - + public EmptyMirror(Vector3d pos) { super(pos); orientation = Align.None; @@ -50,10 +50,10 @@ public class EmptyMirror extends SymmetryMirror { } @Override - public AllBlockPartials getModel() { + public PartialModel getModel() { return null; } - + @Override public List getAlignToolTips() { return ImmutableList.of(); diff --git a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/PlaneMirror.java b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/PlaneMirror.java index 497ecc269..53f8a55c3 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/PlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/PlaneMirror.java @@ -7,6 +7,7 @@ import java.util.Map; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Lang; import com.simibubi.create.foundation.utility.MatrixStacker; @@ -82,7 +83,7 @@ public class PlaneMirror extends SymmetryMirror { } @Override - public AllBlockPartials getModel() { + public PartialModel getModel() { return AllBlockPartials.SYMMETRY_PLANE; } diff --git a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/SymmetryMirror.java b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/SymmetryMirror.java index 33f4f5ff2..02e950e9e 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/SymmetryMirror.java +++ b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/SymmetryMirror.java @@ -6,7 +6,7 @@ import java.util.Map; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Lang; import net.minecraft.block.BlockState; @@ -80,7 +80,7 @@ public abstract class SymmetryMirror { public abstract String typeName(); - public abstract AllBlockPartials getModel(); + public abstract PartialModel getModel(); public void applyModelTransform(MatrixStack ms) {} diff --git a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/TriplePlaneMirror.java b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/TriplePlaneMirror.java index 586b4145b..838d4b366 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/TriplePlaneMirror.java +++ b/src/main/java/com/simibubi/create/content/curiosities/symmetry/mirror/TriplePlaneMirror.java @@ -6,6 +6,7 @@ import java.util.Map; import com.google.common.collect.ImmutableList; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.Lang; import net.minecraft.block.BlockState; @@ -43,7 +44,7 @@ public class TriplePlaneMirror extends SymmetryMirror { } @Override - public AllBlockPartials getModel() { + public PartialModel getModel() { return AllBlockPartials.SYMMETRY_TRIPLEPLANE; } @@ -54,12 +55,12 @@ public class TriplePlaneMirror extends SymmetryMirror { @Override public void setOrientation(int index) { } - + @Override public IStringSerializable getOrientation() { return CrossPlaneMirror.Align.Y; } - + @Override public List getAlignToolTips() { return ImmutableList.of(Lang.translate("orientation.horizontal")); diff --git a/src/main/java/com/simibubi/create/content/curiosities/tools/ExtendoGripRenderHandler.java b/src/main/java/com/simibubi/create/content/curiosities/tools/ExtendoGripRenderHandler.java index 1943ebf4d..847935f56 100644 --- a/src/main/java/com/simibubi/create/content/curiosities/tools/ExtendoGripRenderHandler.java +++ b/src/main/java/com/simibubi/create/content/curiosities/tools/ExtendoGripRenderHandler.java @@ -3,6 +3,7 @@ package com.simibubi.create.content.curiosities.tools; import com.mojang.blaze3d.matrix.MatrixStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.AllItems; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.AnimationTickHolder; import com.simibubi.create.foundation.utility.MatrixStacker; @@ -28,7 +29,7 @@ public class ExtendoGripRenderHandler { public static float mainHandAnimation; public static float lastMainHandAnimation; - public static AllBlockPartials pose = AllBlockPartials.DEPLOYER_HAND_PUNCHING; + public static PartialModel pose = AllBlockPartials.DEPLOYER_HAND_PUNCHING; public static void tick() { lastMainHandAnimation = mainHandAnimation; diff --git a/src/main/java/com/simibubi/create/content/logistics/RedstoneLinkNetworkHandler.java b/src/main/java/com/simibubi/create/content/logistics/RedstoneLinkNetworkHandler.java index 969ea7984..910ef68d1 100644 --- a/src/main/java/com/simibubi/create/content/logistics/RedstoneLinkNetworkHandler.java +++ b/src/main/java/com/simibubi/create/content/logistics/RedstoneLinkNetworkHandler.java @@ -52,7 +52,7 @@ public class RedstoneLinkNetworkHandler { @Override public int hashCode() { - return item.hashCode() ^ color; + return (item.hashCode() * 31) ^ color; } @Override diff --git a/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelInstance.java b/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelInstance.java index 36cf2bbd7..81793455e 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelInstance.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelInstance.java @@ -66,7 +66,7 @@ public class BeltTunnelInstance extends TileEntityInstance tunnelFlaps.put(direction, flaps); }); } - + @Override public boolean shouldReset() { return super.shouldReset() || tunnelFlaps.size() != tile.flaps.size(); diff --git a/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelRenderer.java b/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelRenderer.java index f82be3bb1..49252ec37 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelRenderer.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/belts/tunnel/BeltTunnelRenderer.java @@ -3,6 +3,7 @@ package com.simibubi.create.content.logistics.block.belts.tunnel; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.tileEntity.renderer.SmartTileEntityRenderer; @@ -32,7 +33,7 @@ public class BeltTunnelRenderer extends SmartTileEntityRenderer impleme if (!tile.hasFlap()) return; - AllBlockPartials flapPartial = (blockState.getBlock() instanceof FunnelBlock ? AllBlockPartials.FUNNEL_FLAP + PartialModel flapPartial = (blockState.getBlock() instanceof FunnelBlock ? AllBlockPartials.FUNNEL_FLAP : AllBlockPartials.BELT_FUNNEL_FLAP); InstancedModel model = modelManager.getMaterial(KineticRenderMaterials.FLAPS) .getModel(flapPartial, blockState); diff --git a/src/main/java/com/simibubi/create/content/logistics/block/funnel/FunnelRenderer.java b/src/main/java/com/simibubi/create/content/logistics/block/funnel/FunnelRenderer.java index d54eb5cd0..87d762e51 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/funnel/FunnelRenderer.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/funnel/FunnelRenderer.java @@ -3,8 +3,10 @@ package com.simibubi.create.content.logistics.block.funnel; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.renderer.SmartTileEntityRenderer; import com.simibubi.create.foundation.utility.AngleHelper; import com.simibubi.create.foundation.utility.MatrixStacker; @@ -33,18 +35,19 @@ public class FunnelRenderer extends SmartTileEntityRenderer { BlockState blockState = te.getBlockState(); IVertexBuilder vb = buffer.getBuffer(RenderType.getSolid()); - SuperByteBuffer flapBuffer = (blockState.getBlock() instanceof FunnelBlock ? AllBlockPartials.FUNNEL_FLAP - : AllBlockPartials.BELT_FUNNEL_FLAP).renderOn(blockState); + PartialModel partialModel = (blockState.getBlock() instanceof FunnelBlock ? AllBlockPartials.FUNNEL_FLAP + : AllBlockPartials.BELT_FUNNEL_FLAP); + SuperByteBuffer flapBuffer = PartialBufferer.get(partialModel, blockState); Vector3d pivot = VecHelper.voxelSpace(0, 10, 9.5f); MatrixStacker msr = MatrixStacker.of(ms); float horizontalAngle = AngleHelper.horizontalAngle(FunnelBlock.getFunnelFacing(blockState) - .getOpposite()); + .getOpposite()); float f = te.flap.get(partialTicks); ms.push(); msr.centre() - .rotateY(horizontalAngle) + .rotateY(horizontalAngle) .unCentre(); ms.translate(0, 0, -te.getFlapOffset()); diff --git a/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmInteractionPoint.java b/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmInteractionPoint.java index 50d9a041b..84baeee39 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmInteractionPoint.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmInteractionPoint.java @@ -27,6 +27,7 @@ import com.simibubi.create.content.logistics.block.funnel.FunnelBlock; import com.simibubi.create.content.logistics.block.funnel.FunnelTileEntity; import com.simibubi.create.foundation.advancement.AllTriggers; import com.simibubi.create.foundation.item.SmartInventory; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.tileEntity.TileEntityBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.belt.TransportedItemStackHandlerBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.belt.TransportedItemStackHandlerBehaviour.TransportedResult; @@ -100,7 +101,7 @@ public abstract class ArmInteractionPoint { @OnlyIn(Dist.CLIENT) void transformFlag(MatrixStack stack) {} - AllBlockPartials getFlagType() { + PartialModel getFlagType() { return mode == Mode.TAKE ? AllBlockPartials.FLAG_LONG_OUT : AllBlockPartials.FLAG_LONG_IN; } diff --git a/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmRenderer.java b/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmRenderer.java index 6553f676c..2a9a72ac3 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmRenderer.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/mechanicalArm/ArmRenderer.java @@ -6,6 +6,7 @@ import com.simibubi.create.AllBlockPartials; import com.simibubi.create.content.contraptions.base.KineticTileEntity; import com.simibubi.create.content.contraptions.base.KineticTileEntityRenderer; import com.simibubi.create.content.logistics.block.mechanicalArm.ArmTileEntity.Phase; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.utility.AnimationTickHolder; @@ -66,7 +67,7 @@ public class ArmRenderer extends KineticTileEntityRenderer { float lowerArmAngle = arm.lowerArmAngle.get(pt) - 135; float upperArmAngle = arm.upperArmAngle.get(pt) - 90; float headAngle = arm.headAngle.get(pt); - + boolean rave = arm.phase == Phase.DANCING; float renderTick = AnimationTickHolder.getRenderTime(te.getWorld()) + (te.hashCode() % 64); if (rave) { @@ -104,21 +105,21 @@ public class ArmRenderer extends KineticTileEntityRenderer { } private void renderArm(IVertexBuilder builder, MatrixStack ms, MatrixStack msLocal, MatrixStacker msr, BlockState blockState, int color, float baseAngle, float lowerArmAngle, float upperArmAngle, float headAngle, boolean hasItem, boolean isBlockItem, int light) { - SuperByteBuffer base = AllBlockPartials.ARM_BASE.renderOn(blockState).light(light); - SuperByteBuffer lowerBody = AllBlockPartials.ARM_LOWER_BODY.renderOn(blockState).light(light); - SuperByteBuffer upperBody = AllBlockPartials.ARM_UPPER_BODY.renderOn(blockState).light(light); - SuperByteBuffer head = AllBlockPartials.ARM_HEAD.renderOn(blockState).light(light); - SuperByteBuffer claw = AllBlockPartials.ARM_CLAW_BASE.renderOn(blockState).light(light); - SuperByteBuffer clawGrip = AllBlockPartials.ARM_CLAW_GRIP.renderOn(blockState); + SuperByteBuffer base = PartialBufferer.get(AllBlockPartials.ARM_BASE, blockState).light(light); + SuperByteBuffer lowerBody = PartialBufferer.get(AllBlockPartials.ARM_LOWER_BODY, blockState).light(light); + SuperByteBuffer upperBody = PartialBufferer.get(AllBlockPartials.ARM_UPPER_BODY, blockState).light(light); + SuperByteBuffer head = PartialBufferer.get(AllBlockPartials.ARM_HEAD, blockState).light(light); + SuperByteBuffer claw = PartialBufferer.get(AllBlockPartials.ARM_CLAW_BASE, blockState).light(light); + SuperByteBuffer clawGrip = PartialBufferer.get(AllBlockPartials.ARM_CLAW_GRIP, blockState); transformBase(msr, baseAngle); base.transform(msLocal) - .renderInto(ms, builder); + .renderInto(ms, builder); transformLowerArm(msr, lowerArmAngle); lowerBody.color(color) - .transform(msLocal) - .renderInto(ms, builder); + .transform(msLocal) + .renderInto(ms, builder); transformUpperArm(msr, upperArmAngle); upperBody.color(color) @@ -182,7 +183,7 @@ public class ArmRenderer extends KineticTileEntityRenderer { @Override protected SuperByteBuffer getRotatedModel(KineticTileEntity te) { - return AllBlockPartials.ARM_COG.renderOn(te.getBlockState()); + return PartialBufferer.get(AllBlockPartials.ARM_COG, te.getBlockState()); } } diff --git a/src/main/java/com/simibubi/create/content/logistics/block/redstone/AnalogLeverRenderer.java b/src/main/java/com/simibubi/create/content/logistics/block/redstone/AnalogLeverRenderer.java index cbde2d0e5..329760ede 100644 --- a/src/main/java/com/simibubi/create/content/logistics/block/redstone/AnalogLeverRenderer.java +++ b/src/main/java/com/simibubi/create/content/logistics/block/redstone/AnalogLeverRenderer.java @@ -3,6 +3,7 @@ package com.simibubi.create.content.logistics.block.redstone; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.PartialBufferer; import com.simibubi.create.foundation.render.SuperByteBuffer; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; import com.simibubi.create.foundation.tileEntity.renderer.SafeTileEntityRenderer; @@ -36,20 +37,20 @@ public class AnalogLeverRenderer extends SafeTileEntityRenderer Optional thenTry(Optional first, Optional thenTry) { - if (first.isPresent()) { - return first; - } else { - return thenTry; - } - } - - public static Optional thenTryLazy(Supplier> first, Supplier> thenTry) { - Optional one = first.get(); - if (one.isPresent()) { - return one; - } else { - return thenTry.get(); - } - } -} diff --git a/src/main/java/com/simibubi/create/foundation/gui/GuiGameElement.java b/src/main/java/com/simibubi/create/foundation/gui/GuiGameElement.java index a9b3c24a4..385f1a019 100644 --- a/src/main/java/com/simibubi/create/foundation/gui/GuiGameElement.java +++ b/src/main/java/com/simibubi/create/foundation/gui/GuiGameElement.java @@ -8,8 +8,8 @@ import com.mojang.blaze3d.platform.GlStateManager.DestFactor; import com.mojang.blaze3d.platform.GlStateManager.SourceFactor; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.IVertexBuilder; -import com.simibubi.create.AllBlockPartials; import com.simibubi.create.foundation.fluid.FluidRenderer; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.ColorHelper; import com.simibubi.create.foundation.utility.VecHelper; import com.simibubi.create.foundation.utility.VirtualEmptyModelData; @@ -53,7 +53,7 @@ public class GuiGameElement { return new GuiBlockStateRenderBuilder(state); } - public static GuiRenderBuilder of(AllBlockPartials partial) { + public static GuiRenderBuilder of(PartialModel partial) { return new GuiBlockPartialRenderBuilder(partial); } @@ -251,7 +251,7 @@ public class GuiGameElement { public static class GuiBlockPartialRenderBuilder extends GuiBlockModelRenderBuilder { - public GuiBlockPartialRenderBuilder(AllBlockPartials partial) { + public GuiBlockPartialRenderBuilder(PartialModel partial) { super(partial.get(), null); } diff --git a/src/main/java/com/simibubi/create/foundation/render/Compartment.java b/src/main/java/com/simibubi/create/foundation/render/Compartment.java index 33d1ba678..01087fc22 100644 --- a/src/main/java/com/simibubi/create/foundation/render/Compartment.java +++ b/src/main/java/com/simibubi/create/foundation/render/Compartment.java @@ -2,13 +2,13 @@ package com.simibubi.create.foundation.render; import org.apache.commons.lang3.tuple.Pair; -import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import net.minecraft.block.BlockState; import net.minecraft.util.Direction; public class Compartment { public static final Compartment GENERIC_TILE = new Compartment<>(); - public static final Compartment PARTIAL = new Compartment<>(); - public static final Compartment> DIRECTIONAL_PARTIAL = new Compartment<>(); + public static final Compartment PARTIAL = new Compartment<>(); + public static final Compartment> DIRECTIONAL_PARTIAL = new Compartment<>(); } diff --git a/src/main/java/com/simibubi/create/foundation/render/PartialBufferer.java b/src/main/java/com/simibubi/create/foundation/render/PartialBufferer.java new file mode 100644 index 000000000..4ed176c64 --- /dev/null +++ b/src/main/java/com/simibubi/create/foundation/render/PartialBufferer.java @@ -0,0 +1,43 @@ +package com.simibubi.create.foundation.render; + +import static net.minecraft.state.properties.BlockStateProperties.FACING; + +import java.util.function.Supplier; + +import com.mojang.blaze3d.matrix.MatrixStack; +import com.simibubi.create.CreateClient; +import com.simibubi.create.foundation.render.backend.core.PartialModel; +import com.simibubi.create.foundation.utility.AngleHelper; +import com.simibubi.create.foundation.utility.MatrixStacker; + +import net.minecraft.block.BlockState; +import net.minecraft.util.Direction; + +public class PartialBufferer { + + public static SuperByteBuffer get(PartialModel partial, BlockState referenceState) { + return CreateClient.bufferCache.renderPartial(partial, referenceState); + } + + public static SuperByteBuffer getFacing(PartialModel partial, BlockState referenceState) { + Direction facing = referenceState.get(FACING); + return getFacing(partial, referenceState, facing); + } + + public static SuperByteBuffer getFacing(PartialModel partial, BlockState referenceState, Direction facing) { + return CreateClient.bufferCache.renderDirectionalPartial(partial, referenceState, facing, rotateToFace(facing)); + } + + public static Supplier rotateToFace(Direction facing) { + return () -> { + MatrixStack stack = new MatrixStack(); + MatrixStacker.of(stack) + .centre() + .rotateY(AngleHelper.horizontalAngle(facing)) + .rotateX(AngleHelper.verticalAngle(facing)) + .unCentre(); + return stack; + }; + } + +} diff --git a/src/main/java/com/simibubi/create/foundation/render/SuperByteBufferCache.java b/src/main/java/com/simibubi/create/foundation/render/SuperByteBufferCache.java index 93407bc6b..f5f7d7559 100644 --- a/src/main/java/com/simibubi/create/foundation/render/SuperByteBufferCache.java +++ b/src/main/java/com/simibubi/create/foundation/render/SuperByteBufferCache.java @@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL11; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.utility.VirtualEmptyModelData; import net.minecraft.block.BlockState; @@ -41,26 +41,26 @@ public class SuperByteBufferCache { return getGeneric(toRender, () -> standardBlockRender(toRender)); } - public SuperByteBuffer renderPartial(AllBlockPartials partial, BlockState referenceState) { + public SuperByteBuffer renderPartial(PartialModel partial, BlockState referenceState) { return get(Compartment.PARTIAL, partial, () -> standardModelRender(partial.get(), referenceState)); } - public SuperByteBuffer renderPartial(AllBlockPartials partial, BlockState referenceState, - MatrixStack modelTransform) { + public SuperByteBuffer renderPartial(PartialModel partial, BlockState referenceState, + Supplier modelTransform) { return get(Compartment.PARTIAL, partial, - () -> standardModelRender(partial.get(), referenceState, modelTransform)); + () -> standardModelRender(partial.get(), referenceState, modelTransform.get())); } - public SuperByteBuffer renderDirectionalPartial(AllBlockPartials partial, BlockState referenceState, - Direction dir) { + public SuperByteBuffer renderDirectionalPartial(PartialModel partial, BlockState referenceState, + Direction dir) { return get(Compartment.DIRECTIONAL_PARTIAL, Pair.of(dir, partial), () -> standardModelRender(partial.get(), referenceState)); } - public SuperByteBuffer renderDirectionalPartial(AllBlockPartials partial, BlockState referenceState, Direction dir, - MatrixStack modelTransform) { + public SuperByteBuffer renderDirectionalPartial(PartialModel partial, BlockState referenceState, Direction dir, + Supplier modelTransform) { return get(Compartment.DIRECTIONAL_PARTIAL, Pair.of(dir, partial), - () -> standardModelRender(partial.get(), referenceState, modelTransform)); + () -> standardModelRender(partial.get(), referenceState, modelTransform.get())); } public SuperByteBuffer renderBlockIn(Compartment compartment, BlockState toRender) { diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/BufferedModel.java b/src/main/java/com/simibubi/create/foundation/render/backend/BufferedModel.java index ecd90508a..20c7436f9 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/BufferedModel.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/BufferedModel.java @@ -13,75 +13,75 @@ import net.minecraft.client.renderer.BufferBuilder; public abstract class BufferedModel extends TemplateBuffer { - protected GlBuffer modelVBO; - protected boolean removed; + protected GlBuffer modelVBO; + protected boolean removed; - protected BufferedModel(BufferBuilder buf) { - super(buf); - if (vertexCount > 0) init(); - } + protected BufferedModel(BufferBuilder buf) { + super(buf); + if (vertexCount > 0) init(); + } - protected void init() { + protected void init() { - modelVBO = new GlBuffer(GL20.GL_ARRAY_BUFFER); + modelVBO = new GlBuffer(GL20.GL_ARRAY_BUFFER); - modelVBO.with(vbo -> initModel()); - } + modelVBO.with(vbo -> initModel()); + } - protected void initModel() { - int stride = getModelFormat().getStride(); - int invariantSize = vertexCount * stride; + protected void initModel() { + int stride = getModelFormat().getStride(); + int invariantSize = vertexCount * stride; - // allocate the buffer on the gpu - GL15.glBufferData(GL15.GL_ARRAY_BUFFER, invariantSize, GL15.GL_STATIC_DRAW); + // allocate the buffer on the gpu + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, invariantSize, GL15.GL_STATIC_DRAW); - // mirror it in system memory so we can write to it - modelVBO.map(invariantSize, buffer -> { - for (int i = 0; i < vertexCount; i++) { - copyVertex(buffer, i); - } - }); - } + // mirror it in system memory so we can write to it + modelVBO.map(invariantSize, buffer -> { + for (int i = 0; i < vertexCount; i++) { + copyVertex(buffer, i); + } + }); + } - protected abstract void copyVertex(ByteBuffer to, int index); + protected abstract void copyVertex(ByteBuffer to, int index); - protected abstract VertexFormat getModelFormat(); + protected abstract VertexFormat getModelFormat(); - protected int getTotalShaderAttributeCount() { - return getModelFormat().getShaderAttributeCount(); - } + protected int getTotalShaderAttributeCount() { + return getModelFormat().getShaderAttributeCount(); + } - /** - * Renders this model, checking first if there is anything to render. - */ - public final void render() { - if (vertexCount == 0 || removed) return; + /** + * Renders this model, checking first if there is anything to render. + */ + public final void render() { + if (vertexCount == 0 || removed) return; - doRender(); - } + doRender(); + } - /** - * Set up any state and make the draw calls. - */ - protected abstract void doRender(); + /** + * Set up any state and make the draw calls. + */ + protected abstract void doRender(); - protected void setupAttributes() { - int numAttributes = getTotalShaderAttributeCount(); - for (int i = 0; i <= numAttributes; i++) { - GL20.glEnableVertexAttribArray(i); - } + protected void setupAttributes() { + int numAttributes = getTotalShaderAttributeCount(); + for (int i = 0; i <= numAttributes; i++) { + GL20.glEnableVertexAttribArray(i); + } - getModelFormat().vertexAttribPointers(0); - } + getModelFormat().vertexAttribPointers(0); + } - public final void delete() { - removed = true; - if (vertexCount > 0) { - RenderWork.enqueue(this::deleteInternal); - } - } + public final void delete() { + removed = true; + if (vertexCount > 0) { + RenderWork.enqueue(this::deleteInternal); + } + } - protected void deleteInternal() { - modelVBO.delete(); - } + protected void deleteInternal() { + modelVBO.delete(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/FastRenderDispatcher.java b/src/main/java/com/simibubi/create/foundation/render/backend/FastRenderDispatcher.java index fd516cdd8..ee9fc282f 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/FastRenderDispatcher.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/FastRenderDispatcher.java @@ -17,56 +17,56 @@ import net.minecraft.world.World; public class FastRenderDispatcher { - public static WorldAttached> queuedUpdates = new WorldAttached<>(ConcurrentHashMap::newKeySet); + public static WorldAttached> queuedUpdates = new WorldAttached<>(ConcurrentHashMap::newKeySet); - public static void enqueueUpdate(TileEntity te) { - queuedUpdates.get(te.getWorld()).add(te); - } + public static void enqueueUpdate(TileEntity te) { + queuedUpdates.get(te.getWorld()).add(te); + } - public static void tick() { - Minecraft mc = Minecraft.getInstance(); - ClientWorld world = mc.world; + public static void tick() { + Minecraft mc = Minecraft.getInstance(); + ClientWorld world = mc.world; - KineticRenderer kineticRenderer = CreateClient.kineticRenderer.get(world); + KineticRenderer kineticRenderer = CreateClient.kineticRenderer.get(world); - Entity renderViewEntity = mc.renderViewEntity; - kineticRenderer.tick(renderViewEntity.getX(), renderViewEntity.getY(), renderViewEntity.getZ()); + Entity renderViewEntity = mc.renderViewEntity; + kineticRenderer.tick(renderViewEntity.getX(), renderViewEntity.getY(), renderViewEntity.getZ()); - ConcurrentHashMap.KeySetView map = queuedUpdates.get(world); - map - .forEach(te -> { - map.remove(te); + ConcurrentHashMap.KeySetView map = queuedUpdates.get(world); + map + .forEach(te -> { + map.remove(te); - kineticRenderer.update(te); - }); - } + kineticRenderer.update(te); + }); + } - public static boolean available() { - return Backend.canUseInstancing(); - } + public static boolean available() { + return Backend.canUseInstancing(); + } - public static boolean available(World world) { - return Backend.canUseInstancing() && Backend.isFlywheelWorld(world); - } + public static boolean available(World world) { + return Backend.canUseInstancing() && Backend.isFlywheelWorld(world); + } - public static int getDebugMode() { - return KineticDebugger.isActive() ? 1 : 0; - } + public static int getDebugMode() { + return KineticDebugger.isActive() ? 1 : 0; + } - public static void refresh() { - RenderWork.enqueue(Minecraft.getInstance().worldRenderer::loadRenderers); - } + public static void refresh() { + RenderWork.enqueue(Minecraft.getInstance().worldRenderer::loadRenderers); + } - public static void renderLayer(RenderType layer, Matrix4f viewProjection, double cameraX, double cameraY, double cameraZ) { - if (!Backend.canUseInstancing()) return; + public static void renderLayer(RenderType layer, Matrix4f viewProjection, double cameraX, double cameraY, double cameraZ) { + if (!Backend.canUseInstancing()) return; - ClientWorld world = Minecraft.getInstance().world; - KineticRenderer kineticRenderer = CreateClient.kineticRenderer.get(world); + ClientWorld world = Minecraft.getInstance().world; + KineticRenderer kineticRenderer = CreateClient.kineticRenderer.get(world); - layer.startDrawing(); + layer.startDrawing(); - kineticRenderer.render(layer, viewProjection, cameraX, cameraY, cameraZ); + kineticRenderer.render(layer, viewProjection, cameraX, cameraY, cameraZ); - layer.endDrawing(); - } + layer.endDrawing(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/MaterialTypes.java b/src/main/java/com/simibubi/create/foundation/render/backend/MaterialTypes.java index 66d838f08..e524b295c 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/MaterialTypes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/MaterialTypes.java @@ -5,6 +5,6 @@ import com.simibubi.create.foundation.render.backend.core.OrientedData; import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; public class MaterialTypes { - public static final MaterialType> TRANSFORMED = new MaterialType<>(); - public static final MaterialType> ORIENTED = new MaterialType<>(); + public static final MaterialType> TRANSFORMED = new MaterialType<>(); + public static final MaterialType> ORIENTED = new MaterialType<>(); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/OptifineHandler.java b/src/main/java/com/simibubi/create/foundation/render/backend/OptifineHandler.java index 49b967e7b..58cc82188 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/OptifineHandler.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/OptifineHandler.java @@ -9,77 +9,78 @@ import java.util.Optional; import net.minecraft.client.Minecraft; public class OptifineHandler { - public static final String OPTIFINE_ROOT_PACKAGE = "net.optifine"; - public static final String SHADER_PACKAGE = "net.optifine.shaders"; + public static final String OPTIFINE_ROOT_PACKAGE = "net.optifine"; + public static final String SHADER_PACKAGE = "net.optifine.shaders"; - private static Package optifine; - private static OptifineHandler handler; + private static Package optifine; + private static OptifineHandler handler; - public final boolean usingShaders; + public final boolean usingShaders; - public OptifineHandler(boolean usingShaders) { - this.usingShaders = usingShaders; - } + public OptifineHandler(boolean usingShaders) { + this.usingShaders = usingShaders; + } - /** - * Get information about the current Optifine configuration. - * @return {@link Optional#empty()} if Optifine is not installed. - */ - public static Optional get() { - return Optional.ofNullable(handler); - } + /** + * Get information about the current Optifine configuration. + * + * @return {@link Optional#empty()} if Optifine is not installed. + */ + public static Optional get() { + return Optional.ofNullable(handler); + } - public static boolean optifineInstalled() { - return optifine != null; - } + public static boolean optifineInstalled() { + return optifine != null; + } - public static boolean usingShaders() { - return OptifineHandler.get() - .map(OptifineHandler::isUsingShaders) - .orElse(false); - } + public static boolean usingShaders() { + return OptifineHandler.get() + .map(OptifineHandler::isUsingShaders) + .orElse(false); + } - public static void init() { - optifine = Package.getPackage(OPTIFINE_ROOT_PACKAGE); + public static void init() { + optifine = Package.getPackage(OPTIFINE_ROOT_PACKAGE); - if (optifine == null) { - Backend.log.info("Optifine not detected."); - } else { - Backend.log.info("Optifine detected."); + if (optifine == null) { + Backend.log.info("Optifine not detected."); + } else { + Backend.log.info("Optifine detected."); - refresh(); - } - } + refresh(); + } + } - public static void refresh() { - if (optifine == null) return; + public static void refresh() { + if (optifine == null) return; - File dir = Minecraft.getInstance().gameDir; + File dir = Minecraft.getInstance().gameDir; - File shaderOptions = new File(dir, "optionsshaders.txt"); + File shaderOptions = new File(dir, "optionsshaders.txt"); - boolean shadersOff = true; - try { - BufferedReader reader = new BufferedReader(new FileReader(shaderOptions)); + boolean shadersOff = true; + try { + BufferedReader reader = new BufferedReader(new FileReader(shaderOptions)); - shadersOff = reader.lines() - .anyMatch(it -> { - String line = it.replaceAll("\\s", ""); - if (line.startsWith("shaderPack=")) { - String setting = line.substring("shaderPack=".length()); + shadersOff = reader.lines() + .anyMatch(it -> { + String line = it.replaceAll("\\s", ""); + if (line.startsWith("shaderPack=")) { + String setting = line.substring("shaderPack=".length()); - return setting.equals("OFF") || setting.equals("(internal)"); - } - return false; - }); - } catch (FileNotFoundException e) { - Backend.log.info("No shader config found."); - } + return setting.equals("OFF") || setting.equals("(internal)"); + } + return false; + }); + } catch (FileNotFoundException e) { + Backend.log.info("No shader config found."); + } - handler = new OptifineHandler(!shadersOff); - } + handler = new OptifineHandler(!shadersOff); + } - public boolean isUsingShaders() { - return usingShaders; - } + public boolean isUsingShaders() { + return usingShaders; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/RenderUtil.java b/src/main/java/com/simibubi/create/foundation/render/backend/RenderUtil.java index cba53f805..46c89647d 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/RenderUtil.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/RenderUtil.java @@ -1,7 +1,12 @@ package com.simibubi.create.foundation.render.backend; -import com.mojang.blaze3d.matrix.MatrixStack; +import java.util.function.Supplier; +import com.mojang.blaze3d.matrix.MatrixStack; +import com.simibubi.create.foundation.utility.AngleHelper; +import com.simibubi.create.foundation.utility.MatrixStacker; + +import net.minecraft.util.Direction; import net.minecraft.util.math.vector.Matrix3f; import net.minecraft.util.math.vector.Matrix4f; @@ -79,4 +84,16 @@ public class RenderUtil { model.a33, }; } + + public static Supplier rotateToFace(Direction facing) { + return () -> { + MatrixStack stack = new MatrixStack(); + MatrixStacker.of(stack) + .centre() + .rotateY(AngleHelper.horizontalAngle(facing)) + .rotateX(AngleHelper.verticalAngle(facing)) + .unCentre(); + return stack; + }; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/RenderWork.java b/src/main/java/com/simibubi/create/foundation/render/backend/RenderWork.java index 5a44845f6..b20f1d64e 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/RenderWork.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/RenderWork.java @@ -4,18 +4,18 @@ import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class RenderWork { - private static final Queue runs = new ConcurrentLinkedQueue<>(); + private static final Queue runs = new ConcurrentLinkedQueue<>(); - public static void runAll() { - while (!runs.isEmpty()) { - runs.remove().run(); - } - } + public static void runAll() { + while (!runs.isEmpty()) { + runs.remove().run(); + } + } - /** - * Queue work to be executed at the end of a frame - */ - public static void enqueue(Runnable run) { - runs.add(run); - } + /** + * Queue work to be executed at the end of a frame + */ + public static void enqueue(Runnable run) { + runs.add(run); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoader.java b/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoader.java index 1683c63bf..b58761b3c 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoader.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoader.java @@ -67,7 +67,7 @@ public class ShaderLoader { } } - private void loadShaderSources(IResourceManager manager){ + private void loadShaderSources(IResourceManager manager) { Collection allShaders = manager.getAllResourceLocations(SHADER_DIR, s -> { for (String ext : EXTENSIONS) { if (s.endsWith(ext)) return true; @@ -173,7 +173,7 @@ public class ShaderLoader { try { bytebuffer = readToBuffer(is); int i = bytebuffer.position(); - ((Buffer)bytebuffer).rewind(); + ((Buffer) bytebuffer).rewind(); return MemoryUtil.memASCII(bytebuffer, i); } catch (IOException e) { @@ -190,11 +190,12 @@ public class ShaderLoader { public ByteBuffer readToBuffer(InputStream is) throws IOException { ByteBuffer bytebuffer; if (is instanceof FileInputStream) { - FileInputStream fileinputstream = (FileInputStream)is; + FileInputStream fileinputstream = (FileInputStream) is; FileChannel filechannel = fileinputstream.getChannel(); - bytebuffer = MemoryUtil.memAlloc((int)filechannel.size() + 1); + bytebuffer = MemoryUtil.memAlloc((int) filechannel.size() + 1); - while (filechannel.read(bytebuffer) != -1) { } + while (filechannel.read(bytebuffer) != -1) { + } } else { bytebuffer = MemoryUtil.memAlloc(8192); ReadableByteChannel readablebytechannel = Channels.newChannel(is); diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoadingException.java b/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoadingException.java deleted file mode 100644 index 50b1c916a..000000000 --- a/src/main/java/com/simibubi/create/foundation/render/backend/ShaderLoadingException.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.simibubi.create.foundation.render.backend; - -public class ShaderLoadingException extends RuntimeException { - - public ShaderLoadingException() { - } - - public ShaderLoadingException(String message) { - super(message); - } - - public ShaderLoadingException(String message, Throwable cause) { - super(message, cause); - } - - public ShaderLoadingException(Throwable cause) { - super(cause); - } - - public ShaderLoadingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicData.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicData.java index 2a555ede7..531b2d929 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicData.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicData.java @@ -7,72 +7,72 @@ import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; public class BasicData extends InstanceData implements IFlatLight { - protected byte blockLight; - protected byte skyLight; + protected byte blockLight; + protected byte skyLight; - protected byte r = (byte) 0xFF; - protected byte g = (byte) 0xFF; - protected byte b = (byte) 0xFF; - protected byte a = (byte) 0xFF; + protected byte r = (byte) 0xFF; + protected byte g = (byte) 0xFF; + protected byte b = (byte) 0xFF; + protected byte a = (byte) 0xFF; - public BasicData(InstancedModel owner) { - super(owner); - } + public BasicData(InstancedModel owner) { + super(owner); + } - @Override - public BasicData setBlockLight(int blockLight) { - this.blockLight = (byte) (blockLight << 4); - markDirty(); - return this; - } + @Override + public BasicData setBlockLight(int blockLight) { + this.blockLight = (byte) (blockLight << 4); + markDirty(); + return this; + } - @Override - public BasicData setSkyLight(int skyLight) { - this.skyLight = (byte) (skyLight << 4); - markDirty(); - return this; - } + @Override + public BasicData setSkyLight(int skyLight) { + this.skyLight = (byte) (skyLight << 4); + markDirty(); + return this; + } - public BasicData setColor(int color) { - return setColor(color, false); - } + public BasicData setColor(int color) { + return setColor(color, false); + } - public BasicData setColor(int color, boolean alpha) { - byte r = (byte) ((color >> 16) & 0xFF); - byte g = (byte) ((color >> 8) & 0xFF); - byte b = (byte) (color & 0xFF); + public BasicData setColor(int color, boolean alpha) { + byte r = (byte) ((color >> 16) & 0xFF); + byte g = (byte) ((color >> 8) & 0xFF); + byte b = (byte) (color & 0xFF); - if (alpha) { - byte a = (byte) ((color >> 24) & 0xFF); - return setColor(r, g, b, a); - } else { - return setColor(r, g, b); - } - } + if (alpha) { + byte a = (byte) ((color >> 24) & 0xFF); + return setColor(r, g, b, a); + } else { + return setColor(r, g, b); + } + } - public BasicData setColor(int r, int g, int b) { - return setColor((byte) r, (byte) g, (byte) b); - } + public BasicData setColor(int r, int g, int b) { + return setColor((byte) r, (byte) g, (byte) b); + } - public BasicData setColor(byte r, byte g, byte b) { - this.r = r; - this.g = g; - this.b = b; - markDirty(); - return this; - } + public BasicData setColor(byte r, byte g, byte b) { + this.r = r; + this.g = g; + this.b = b; + markDirty(); + return this; + } - public BasicData setColor(byte r, byte g, byte b, byte a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - markDirty(); - return this; - } + public BasicData setColor(byte r, byte g, byte b, byte a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + markDirty(); + return this; + } - @Override - public void write(ByteBuffer buf) { - buf.put(new byte[] { blockLight, skyLight, r, g, b, a }); - } + @Override + public void write(ByteBuffer buf) { + buf.put(new byte[]{blockLight, skyLight, r, g, b, a}); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicProgram.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicProgram.java index 5f2e671d3..76f9460bc 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicProgram.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/BasicProgram.java @@ -10,44 +10,44 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Matrix4f; public class BasicProgram extends GlProgram { - protected final int uTime; - protected final int uViewProjection; - protected final int uDebug; - protected final int uCameraPos; + protected final int uTime; + protected final int uViewProjection; + protected final int uDebug; + protected final int uCameraPos; - protected final ProgramFogMode fogMode; + protected final ProgramFogMode fogMode; - protected int uBlockAtlas; - protected int uLightMap; + protected int uBlockAtlas; + protected int uLightMap; - public BasicProgram(ResourceLocation name, int handle, ProgramFogMode.Factory fogFactory) { - super(name, handle); - uTime = getUniformLocation("uTime"); - uViewProjection = getUniformLocation("uViewProjection"); - uDebug = getUniformLocation("uDebug"); - uCameraPos = getUniformLocation("uCameraPos"); + public BasicProgram(ResourceLocation name, int handle, ProgramFogMode.Factory fogFactory) { + super(name, handle); + uTime = getUniformLocation("uTime"); + uViewProjection = getUniformLocation("uViewProjection"); + uDebug = getUniformLocation("uDebug"); + uCameraPos = getUniformLocation("uCameraPos"); - fogMode = fogFactory.create(this); + fogMode = fogFactory.create(this); - bind(); - registerSamplers(); - unbind(); - } + bind(); + registerSamplers(); + unbind(); + } - protected void registerSamplers() { - uBlockAtlas = setSamplerBinding("uBlockAtlas", 0); - uLightMap = setSamplerBinding("uLightMap", 2); - } + protected void registerSamplers() { + uBlockAtlas = setSamplerBinding("uBlockAtlas", 0); + uLightMap = setSamplerBinding("uLightMap", 2); + } - public void bind(Matrix4f viewProjection, double camX, double camY, double camZ, int debugMode) { - super.bind(); + public void bind(Matrix4f viewProjection, double camX, double camY, double camZ, int debugMode) { + super.bind(); - GL20.glUniform1i(uDebug, debugMode); - GL20.glUniform1f(uTime, AnimationTickHolder.getRenderTime()); + GL20.glUniform1i(uDebug, debugMode); + GL20.glUniform1f(uTime, AnimationTickHolder.getRenderTime()); - uploadMatrixUniform(uViewProjection, viewProjection); - GL20.glUniform3f(uCameraPos, (float) camX, (float) camY, (float) camZ); + uploadMatrixUniform(uViewProjection, viewProjection); + GL20.glUniform3f(uCameraPos, (float) camX, (float) camY, (float) camZ); - fogMode.bind(); - } + fogMode.bind(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/IFlatLight.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/IFlatLight.java index 0920e037a..fbbdd58b2 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/IFlatLight.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/IFlatLight.java @@ -5,22 +5,23 @@ import com.simibubi.create.foundation.render.backend.instancing.InstanceData; /** * An interface that implementors of {@link InstanceData} should also implement * if they wish to make use of Flywheel's provided light update methods. - * + *

* This only covers flat lighting, smooth lighting is still TODO. + * * @param The name of the class that implements this interface. */ public interface IFlatLight> { - /** - * @param blockLight An integer in the range [0, 15] representing the - * amount of block light this instance should receive. - * @return this - */ - D setBlockLight(int blockLight); + /** + * @param blockLight An integer in the range [0, 15] representing the + * amount of block light this instance should receive. + * @return this + */ + D setBlockLight(int blockLight); - /** - * @param skyLight An integer in the range [0, 15] representing the - * amount of sky light this instance should receive. - * @return this - */ - D setSkyLight(int skyLight); + /** + * @param skyLight An integer in the range [0, 15] representing the + * amount of sky light this instance should receive. + * @return this + */ + D setSkyLight(int skyLight); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelAttributes.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelAttributes.java index b4d220bc3..970fd672e 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelAttributes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelAttributes.java @@ -6,36 +6,36 @@ import com.simibubi.create.foundation.render.backend.gl.attrib.IVertexAttrib; import com.simibubi.create.foundation.render.backend.gl.attrib.VertexAttribSpec; public enum ModelAttributes implements IVertexAttrib { - VERTEX_POSITION("aPos", CommonAttributes.VEC3), - NORMAL("aNormal", CommonAttributes.NORMAL), - TEXTURE("aTexCoords", CommonAttributes.UV), - ; + VERTEX_POSITION("aPos", CommonAttributes.VEC3), + NORMAL("aNormal", CommonAttributes.NORMAL), + TEXTURE("aTexCoords", CommonAttributes.UV), + ; - private final String name; - private final VertexAttribSpec spec; + private final String name; + private final VertexAttribSpec spec; - ModelAttributes(String name, VertexAttribSpec spec) { - this.name = name; - this.spec = spec; - } + ModelAttributes(String name, VertexAttribSpec spec) { + this.name = name; + this.spec = spec; + } - @Override - public String attribName() { - return name; - } + @Override + public String attribName() { + return name; + } - @Override - public IAttribSpec attribSpec() { - return spec; - } + @Override + public IAttribSpec attribSpec() { + return spec; + } - @Override - public int getDivisor() { - return 0; - } + @Override + public int getDivisor() { + return 0; + } - @Override - public int getBufferIndex() { - return 0; - } + @Override + public int getBufferIndex() { + return 0; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelData.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelData.java index 99e3192bd..c2f338bf6 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelData.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/ModelData.java @@ -7,24 +7,24 @@ import com.simibubi.create.foundation.render.backend.RenderUtil; import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; public class ModelData extends BasicData { - private static final float[] empty = new float[25]; + private static final float[] empty = new float[25]; - private float[] matrices = empty; + private float[] matrices = empty; - public ModelData(InstancedModel owner) { - super(owner); - } + public ModelData(InstancedModel owner) { + super(owner); + } - public ModelData setTransform(MatrixStack stack) { - matrices = RenderUtil.writeMatrixStack(stack); - markDirty(); - return this; - } + public ModelData setTransform(MatrixStack stack) { + matrices = RenderUtil.writeMatrixStack(stack); + markDirty(); + return this; + } - @Override - public void write(ByteBuffer buf) { - super.write(buf); - buf.asFloatBuffer().put(matrices); - buf.position(buf.position() + matrices.length * 4); - } + @Override + public void write(ByteBuffer buf) { + super.write(buf); + buf.asFloatBuffer().put(matrices); + buf.position(buf.position() + matrices.length * 4); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedAttributes.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedAttributes.java index 9ee10ce4b..135958501 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedAttributes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedAttributes.java @@ -5,36 +5,36 @@ import com.simibubi.create.foundation.render.backend.gl.attrib.IAttribSpec; import com.simibubi.create.foundation.render.backend.gl.attrib.IVertexAttrib; public enum OrientedAttributes implements IVertexAttrib { - INSTANCE_POS("aInstancePos", CommonAttributes.VEC3), - PIVOT("aPivot", CommonAttributes.VEC3), - ROTATION("aRotation", CommonAttributes.QUATERNION), - ; + INSTANCE_POS("aInstancePos", CommonAttributes.VEC3), + PIVOT("aPivot", CommonAttributes.VEC3), + ROTATION("aRotation", CommonAttributes.QUATERNION), + ; - private final String name; - private final IAttribSpec spec; + private final String name; + private final IAttribSpec spec; - OrientedAttributes(String name, IAttribSpec spec) { - this.name = name; - this.spec = spec; - } + OrientedAttributes(String name, IAttribSpec spec) { + this.name = name; + this.spec = spec; + } - @Override - public String attribName() { - return name; - } + @Override + public String attribName() { + return name; + } - @Override - public IAttribSpec attribSpec() { - return spec; - } + @Override + public IAttribSpec attribSpec() { + return spec; + } - @Override - public int getDivisor() { - return 0; - } + @Override + public int getDivisor() { + return 0; + } - @Override - public int getBufferIndex() { - return 0; - } + @Override + public int getBufferIndex() { + return 0; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedData.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedData.java index dd3b6640d..77becf79e 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedData.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedData.java @@ -85,7 +85,7 @@ public class OrientedData extends BasicData { public void write(ByteBuffer buf) { super.write(buf); - buf.asFloatBuffer().put(new float[] { + buf.asFloatBuffer().put(new float[]{ posX, posY, posZ, diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedModel.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedModel.java index e1cd0b00b..42ee8334b 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedModel.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/OrientedModel.java @@ -7,22 +7,22 @@ import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRen import net.minecraft.client.renderer.BufferBuilder; public class OrientedModel extends InstancedModel { - public static final VertexFormat INSTANCE_FORMAT = VertexFormat.builder() - .addAttributes(BasicAttributes.class) - .addAttributes(OrientedAttributes.class) - .build(); + public static final VertexFormat INSTANCE_FORMAT = VertexFormat.builder() + .addAttributes(BasicAttributes.class) + .addAttributes(OrientedAttributes.class) + .build(); - public OrientedModel(InstancedTileRenderer renderer, BufferBuilder buf) { - super(renderer, buf); - } + public OrientedModel(InstancedTileRenderer renderer, BufferBuilder buf) { + super(renderer, buf); + } - @Override - protected OrientedData newInstance() { - return new OrientedData(this); - } + @Override + protected OrientedData newInstance() { + return new OrientedData(this); + } - @Override - protected VertexFormat getInstanceFormat() { - return INSTANCE_FORMAT; - } + @Override + protected VertexFormat getInstanceFormat() { + return INSTANCE_FORMAT; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/PartialModel.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/PartialModel.java new file mode 100644 index 000000000..87fafb9dd --- /dev/null +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/PartialModel.java @@ -0,0 +1,56 @@ +package com.simibubi.create.foundation.render.backend.core; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import net.minecraft.client.renderer.model.IBakedModel; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.event.ModelBakeEvent; +import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.model.ModelLoader; + +/** + * A helper class for loading and accessing json models. + *

+ * Creating a PartialModel will make the associated modelLocation automatically load. + * As such, PartialModels must be initialized at or before {@link ModelRegistryEvent}. + * Once {@link ModelBakeEvent} finishes, all PartialModels (with valid modelLocations) + * will have their bakedModel fields populated. + *

+ * Attempting to create a PartialModel after ModelRegistryEvent will cause an error. + */ +public class PartialModel { + + private static boolean tooLate = false; + private static final List all = new ArrayList<>(); + + protected final ResourceLocation modelLocation; + protected IBakedModel bakedModel; + + public PartialModel(ResourceLocation modelLocation) { + + if (tooLate) throw new RuntimeException("PartialModel '" + modelLocation + "' loaded after ModelRegistryEvent"); + + this.modelLocation = modelLocation; + all.add(this); + } + + public static void onModelRegistry(ModelRegistryEvent event) { + for (PartialModel partial : all) + ModelLoader.addSpecialModel(partial.modelLocation); + + tooLate = true; + } + + public static void onModelBake(ModelBakeEvent event) { + Map modelRegistry = event.getModelRegistry(); + for (PartialModel partial : all) + partial.bakedModel = modelRegistry.get(partial.modelLocation); + } + + public IBakedModel get() { + return bakedModel; + } + +} diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformAttributes.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformAttributes.java index db7428aa9..f35cdf988 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformAttributes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformAttributes.java @@ -5,35 +5,35 @@ import com.simibubi.create.foundation.render.backend.gl.attrib.IVertexAttrib; import com.simibubi.create.foundation.render.backend.gl.attrib.MatrixAttributes; public enum TransformAttributes implements IVertexAttrib { - TRANSFORM("aTransform", MatrixAttributes.MAT4), - NORMAL_MAT("aNormalMat", MatrixAttributes.MAT3), - ; + TRANSFORM("aTransform", MatrixAttributes.MAT4), + NORMAL_MAT("aNormalMat", MatrixAttributes.MAT3), + ; - private final String name; - private final IAttribSpec spec; + private final String name; + private final IAttribSpec spec; - TransformAttributes(String name, IAttribSpec spec) { - this.name = name; - this.spec = spec; - } + TransformAttributes(String name, IAttribSpec spec) { + this.name = name; + this.spec = spec; + } - @Override - public String attribName() { - return name; - } + @Override + public String attribName() { + return name; + } - @Override - public IAttribSpec attribSpec() { - return spec; - } + @Override + public IAttribSpec attribSpec() { + return spec; + } - @Override - public int getDivisor() { - return 0; - } + @Override + public int getDivisor() { + return 0; + } - @Override - public int getBufferIndex() { - return 0; - } + @Override + public int getBufferIndex() { + return 0; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformedModel.java b/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformedModel.java index b5d80ded6..e5fd44ed1 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformedModel.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/core/TransformedModel.java @@ -7,22 +7,22 @@ import com.simibubi.create.foundation.render.backend.instancing.InstancedTileRen import net.minecraft.client.renderer.BufferBuilder; public class TransformedModel extends InstancedModel { - public static final VertexFormat INSTANCE_FORMAT = VertexFormat.builder() - .addAttributes(BasicAttributes.class) - .addAttributes(TransformAttributes.class) - .build(); + public static final VertexFormat INSTANCE_FORMAT = VertexFormat.builder() + .addAttributes(BasicAttributes.class) + .addAttributes(TransformAttributes.class) + .build(); - public TransformedModel(InstancedTileRenderer renderer, BufferBuilder buf) { - super(renderer, buf); - } + public TransformedModel(InstancedTileRenderer renderer, BufferBuilder buf) { + super(renderer, buf); + } - @Override - protected ModelData newInstance() { - return new ModelData(this); - } + @Override + protected ModelData newInstance() { + return new ModelData(this); + } - @Override - protected VertexFormat getInstanceFormat() { - return INSTANCE_FORMAT; - } + @Override + protected VertexFormat getInstanceFormat() { + return INSTANCE_FORMAT; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlBuffer.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlBuffer.java index af5f0db3f..75e634063 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlBuffer.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlBuffer.java @@ -10,7 +10,7 @@ import com.simibubi.create.foundation.render.backend.Backend; public class GlBuffer extends GlObject { - protected final int bufferType; + protected final int bufferType; public GlBuffer(int bufferType) { setHandle(GL20.glGenBuffers()); diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFog.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFog.java index 02172e02e..6dfab5be8 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFog.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFog.java @@ -5,43 +5,43 @@ import org.lwjgl.opengl.GL11; import com.mojang.blaze3d.platform.GlStateManager; public class GlFog { - public static float[] FOG_COLOR = new float[] {0, 0, 0, 0}; + public static float[] FOG_COLOR = new float[]{0, 0, 0, 0}; - public static boolean fogEnabled() { - return GlStateManager.FOG.field_179049_a.field_179201_b; - } + public static boolean fogEnabled() { + return GlStateManager.FOG.field_179049_a.field_179201_b; + } - public static int getFogModeGlEnum() { - return GlStateManager.FOG.field_179047_b; - } + public static int getFogModeGlEnum() { + return GlStateManager.FOG.field_179047_b; + } - public static float getFogDensity() { - return GlStateManager.FOG.field_179048_c; - } + public static float getFogDensity() { + return GlStateManager.FOG.field_179048_c; + } - public static float getFogEnd() { - return GlStateManager.FOG.field_179046_e; - } + public static float getFogEnd() { + return GlStateManager.FOG.field_179046_e; + } - public static float getFogStart() { - return GlStateManager.FOG.field_179045_d; - } + public static float getFogStart() { + return GlStateManager.FOG.field_179045_d; + } - public static GlFogMode getFogMode() { - if (!fogEnabled()) { - return GlFogMode.NONE; - } + public static GlFogMode getFogMode() { + if (!fogEnabled()) { + return GlFogMode.NONE; + } - int mode = getFogModeGlEnum(); + int mode = getFogModeGlEnum(); - switch (mode) { - case GL11.GL_EXP2: - case GL11.GL_EXP: - return GlFogMode.EXP2; - case GL11.GL_LINEAR: - return GlFogMode.LINEAR; - default: - throw new UnsupportedOperationException("Unknown fog mode: " + mode); - } - } + switch (mode) { + case GL11.GL_EXP2: + case GL11.GL_EXP: + return GlFogMode.EXP2; + case GL11.GL_LINEAR: + return GlFogMode.LINEAR; + default: + throw new UnsupportedOperationException("Unknown fog mode: " + mode); + } + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFogMode.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFogMode.java index ff35e7e12..eb333c732 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFogMode.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlFogMode.java @@ -7,31 +7,31 @@ import com.google.common.collect.Lists; import com.simibubi.create.foundation.render.backend.gl.shader.ProgramFogMode; public enum GlFogMode { - NONE(ProgramFogMode.None::new), - LINEAR(ProgramFogMode.Linear::new, "USE_FOG_LINEAR"), - EXP2(ProgramFogMode.Exp2::new, "USE_FOG_EXP2"), - ; + NONE(ProgramFogMode.None::new), + LINEAR(ProgramFogMode.Linear::new, "USE_FOG_LINEAR"), + EXP2(ProgramFogMode.Exp2::new, "USE_FOG_EXP2"), + ; - public static final String USE_FOG = "USE_FOG"; + public static final String USE_FOG = "USE_FOG"; - private final ProgramFogMode.Factory fogFactory; - private final List defines; + private final ProgramFogMode.Factory fogFactory; + private final List defines; - GlFogMode(ProgramFogMode.Factory fogFactory) { - this.fogFactory = fogFactory; - this.defines = Collections.emptyList(); - } + GlFogMode(ProgramFogMode.Factory fogFactory) { + this.fogFactory = fogFactory; + this.defines = Collections.emptyList(); + } - GlFogMode(ProgramFogMode.Factory fogFactory, String name) { - this.fogFactory = fogFactory; - this.defines = Lists.newArrayList(USE_FOG, name); - } + GlFogMode(ProgramFogMode.Factory fogFactory, String name) { + this.fogFactory = fogFactory; + this.defines = Lists.newArrayList(USE_FOG, name); + } - public List getDefines() { - return defines; - } + public List getDefines() { + return defines; + } - public ProgramFogMode.Factory getFogFactory() { - return fogFactory; - } + public ProgramFogMode.Factory getFogFactory() { + return fogFactory; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlObject.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlObject.java index ef34e5ebe..5bc642869 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlObject.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlObject.java @@ -2,42 +2,42 @@ package com.simibubi.create.foundation.render.backend.gl; // Utility class for safely dealing with gl object handles. public abstract class GlObject { - private static final int INVALID_HANDLE = Integer.MIN_VALUE; + private static final int INVALID_HANDLE = Integer.MIN_VALUE; - private int handle = INVALID_HANDLE; + private int handle = INVALID_HANDLE; - protected final void setHandle(int handle) { - this.handle = handle; - } + protected final void setHandle(int handle) { + this.handle = handle; + } - public final int handle() { - this.checkHandle(); + public final int handle() { + this.checkHandle(); - return this.handle; - } + return this.handle; + } - protected final void checkHandle() { - if (!this.isHandleValid()) { - throw new IllegalStateException("Handle is not valid"); - } - } + protected final void checkHandle() { + if (!this.isHandleValid()) { + throw new IllegalStateException("Handle is not valid"); + } + } - protected final boolean isHandleValid() { - return this.handle != INVALID_HANDLE; - } + protected final boolean isHandleValid() { + return this.handle != INVALID_HANDLE; + } - protected final void invalidateHandle() { - this.handle = INVALID_HANDLE; - } + protected final void invalidateHandle() { + this.handle = INVALID_HANDLE; + } - public final void delete() { - if (!isHandleValid()) { - throw new IllegalStateException("Handle already deleted."); - } + public final void delete() { + if (!isHandleValid()) { + throw new IllegalStateException("Handle already deleted."); + } - deleteInternal(handle); - invalidateHandle(); - } + deleteInternal(handle); + invalidateHandle(); + } - protected abstract void deleteInternal(int handle); + protected abstract void deleteInternal(int handle); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlPrimitiveType.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlPrimitiveType.java index 1850b3670..da1d0efba 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlPrimitiveType.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlPrimitiveType.java @@ -7,33 +7,33 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public enum GlPrimitiveType { - FLOAT(4, "float", GL11.GL_FLOAT), - UBYTE(1, "ubyte", GL11.GL_UNSIGNED_BYTE), - BYTE(1, "byte", GL11.GL_BYTE), - USHORT(2, "ushort", GL11.GL_UNSIGNED_SHORT), - SHORT(2, "short", GL11.GL_SHORT), - UINT(4, "uint", GL11.GL_UNSIGNED_INT), - INT(4, "int", GL11.GL_INT); + FLOAT(4, "float", GL11.GL_FLOAT), + UBYTE(1, "ubyte", GL11.GL_UNSIGNED_BYTE), + BYTE(1, "byte", GL11.GL_BYTE), + USHORT(2, "ushort", GL11.GL_UNSIGNED_SHORT), + SHORT(2, "short", GL11.GL_SHORT), + UINT(4, "uint", GL11.GL_UNSIGNED_INT), + INT(4, "int", GL11.GL_INT); - private final int size; - private final String displayName; - private final int glConstant; + private final int size; + private final String displayName; + private final int glConstant; - GlPrimitiveType(int bytes, String name, int glEnum) { - this.size = bytes; - this.displayName = name; - this.glConstant = glEnum; - } + GlPrimitiveType(int bytes, String name, int glEnum) { + this.size = bytes; + this.displayName = name; + this.glConstant = glEnum; + } - public int getSize() { - return this.size; - } + public int getSize() { + return this.size; + } - public String getDisplayName() { - return this.displayName; - } + public String getDisplayName() { + return this.displayName; + } - public int getGlConstant() { - return this.glConstant; - } -} \ No newline at end of file + public int getGlConstant() { + return this.glConstant; + } +} diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlTexture.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlTexture.java index 30b5d3f0f..67fbd8dc5 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlTexture.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlTexture.java @@ -3,23 +3,23 @@ package com.simibubi.create.foundation.render.backend.gl; import org.lwjgl.opengl.GL20; public class GlTexture extends GlObject { - private final int textureType; + private final int textureType; - public GlTexture(int textureType) { - this.textureType = textureType; - setHandle(GL20.glGenTextures()); - } + public GlTexture(int textureType) { + this.textureType = textureType; + setHandle(GL20.glGenTextures()); + } - @Override - protected void deleteInternal(int handle) { - GL20.glDeleteTextures(handle); - } + @Override + protected void deleteInternal(int handle) { + GL20.glDeleteTextures(handle); + } - public void bind() { - GL20.glBindTexture(textureType, handle()); - } + public void bind() { + GL20.glBindTexture(textureType, handle()); + } - public void unbind() { - GL20.glBindTexture(textureType, 0); - } + public void unbind() { + GL20.glBindTexture(textureType, 0); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlVertexArray.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlVertexArray.java index 7cb3fb0de..baf9e9545 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlVertexArray.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/GlVertexArray.java @@ -5,25 +5,25 @@ import java.util.function.Consumer; import com.simibubi.create.foundation.render.backend.Backend; public class GlVertexArray extends GlObject { - public GlVertexArray() { + public GlVertexArray() { setHandle(Backend.compat.vao.genVertexArrays()); } - public void bind() { + public void bind() { Backend.compat.vao.bindVertexArray(handle()); } - public void unbind() { + public void unbind() { Backend.compat.vao.bindVertexArray(0); } - public void with(Consumer action) { - bind(); - action.accept(this); - unbind(); - } + public void with(Consumer action) { + bind(); + action.accept(this); + unbind(); + } - protected void deleteInternal(int handle) { + protected void deleteInternal(int handle) { Backend.compat.vao.deleteVertexArrays(handle); } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/CommonAttributes.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/CommonAttributes.java index acc24f822..5c1a3a91a 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/CommonAttributes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/CommonAttributes.java @@ -4,18 +4,18 @@ import com.simibubi.create.foundation.render.backend.gl.GlPrimitiveType; public class CommonAttributes { - public static final VertexAttribSpec VEC4 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 4); - public static final VertexAttribSpec VEC3 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 3); - public static final VertexAttribSpec VEC2 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 2); - public static final VertexAttribSpec FLOAT = new VertexAttribSpec(GlPrimitiveType.FLOAT, 1); + public static final VertexAttribSpec VEC4 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 4); + public static final VertexAttribSpec VEC3 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 3); + public static final VertexAttribSpec VEC2 = new VertexAttribSpec(GlPrimitiveType.FLOAT, 2); + public static final VertexAttribSpec FLOAT = new VertexAttribSpec(GlPrimitiveType.FLOAT, 1); - public static final VertexAttribSpec QUATERNION = new VertexAttribSpec(GlPrimitiveType.FLOAT, 4); - public static final VertexAttribSpec NORMAL = new VertexAttribSpec(GlPrimitiveType.BYTE, 3, true); - public static final VertexAttribSpec UV = new VertexAttribSpec(GlPrimitiveType.FLOAT, 2); + public static final VertexAttribSpec QUATERNION = new VertexAttribSpec(GlPrimitiveType.FLOAT, 4); + public static final VertexAttribSpec NORMAL = new VertexAttribSpec(GlPrimitiveType.BYTE, 3, true); + public static final VertexAttribSpec UV = new VertexAttribSpec(GlPrimitiveType.FLOAT, 2); - public static final VertexAttribSpec RGBA = new VertexAttribSpec(GlPrimitiveType.UBYTE, 4, true); - public static final VertexAttribSpec RGB = new VertexAttribSpec(GlPrimitiveType.UBYTE, 3, true); - public static final VertexAttribSpec LIGHT = new VertexAttribSpec(GlPrimitiveType.UBYTE, 2, true); + public static final VertexAttribSpec RGBA = new VertexAttribSpec(GlPrimitiveType.UBYTE, 4, true); + public static final VertexAttribSpec RGB = new VertexAttribSpec(GlPrimitiveType.UBYTE, 3, true); + public static final VertexAttribSpec LIGHT = new VertexAttribSpec(GlPrimitiveType.UBYTE, 2, true); - public static final VertexAttribSpec NORMALIZED_BYTE = new VertexAttribSpec(GlPrimitiveType.BYTE, 1, true); + public static final VertexAttribSpec NORMALIZED_BYTE = new VertexAttribSpec(GlPrimitiveType.BYTE, 1, true); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IAttribSpec.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IAttribSpec.java index 01f762f07..31369cd3f 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IAttribSpec.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IAttribSpec.java @@ -2,9 +2,9 @@ package com.simibubi.create.foundation.render.backend.gl.attrib; public interface IAttribSpec { - void vertexAttribPointer(int stride, int index, int pointer); + void vertexAttribPointer(int stride, int index, int pointer); - int getSize(); + int getSize(); - int getAttributeCount(); + int getAttributeCount(); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IVertexAttrib.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IVertexAttrib.java index ee122db00..335ba8644 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IVertexAttrib.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/IVertexAttrib.java @@ -2,11 +2,11 @@ package com.simibubi.create.foundation.render.backend.gl.attrib; public interface IVertexAttrib { - String attribName(); + String attribName(); - IAttribSpec attribSpec(); + IAttribSpec attribSpec(); - int getDivisor(); + int getDivisor(); - int getBufferIndex(); + int getBufferIndex(); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/MatrixAttributes.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/MatrixAttributes.java index 22bbf16c9..0e57cf59f 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/MatrixAttributes.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/MatrixAttributes.java @@ -5,33 +5,33 @@ import org.lwjgl.opengl.GL20; import com.simibubi.create.foundation.render.backend.gl.GlPrimitiveType; public enum MatrixAttributes implements IAttribSpec { - MAT3(3, 3), - MAT4(4, 4), - ; + MAT3(3, 3), + MAT4(4, 4), + ; - private final int rows; - private final int cols; + private final int rows; + private final int cols; - MatrixAttributes(int rows, int cols) { - this.rows = rows; - this.cols = cols; - } + MatrixAttributes(int rows, int cols) { + this.rows = rows; + this.cols = cols; + } - @Override - public void vertexAttribPointer(int stride, int index, int pointer) { - for (int i = 0; i < rows; i++) { - long attribPointer = pointer + (long) i * cols * GlPrimitiveType.FLOAT.getSize(); - GL20.glVertexAttribPointer(index + i, cols, GlPrimitiveType.FLOAT.getGlConstant(), false, stride, attribPointer); - } - } + @Override + public void vertexAttribPointer(int stride, int index, int pointer) { + for (int i = 0; i < rows; i++) { + long attribPointer = pointer + (long) i * cols * GlPrimitiveType.FLOAT.getSize(); + GL20.glVertexAttribPointer(index + i, cols, GlPrimitiveType.FLOAT.getGlConstant(), false, stride, attribPointer); + } + } - @Override - public int getSize() { - return GlPrimitiveType.FLOAT.getSize() * rows * cols; - } + @Override + public int getSize() { + return GlPrimitiveType.FLOAT.getSize() * rows * cols; + } - @Override - public int getAttributeCount() { - return rows; - } + @Override + public int getAttributeCount() { + return rows; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexAttribSpec.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexAttribSpec.java index 82cdac6fc..a9b451d01 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexAttribSpec.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexAttribSpec.java @@ -6,36 +6,36 @@ import com.simibubi.create.foundation.render.backend.gl.GlPrimitiveType; public class VertexAttribSpec implements IAttribSpec { - private final GlPrimitiveType type; - private final int count; - private final int size; - private final int attributeCount; - private final boolean normalized; + private final GlPrimitiveType type; + private final int count; + private final int size; + private final int attributeCount; + private final boolean normalized; - public VertexAttribSpec(GlPrimitiveType type, int count) { - this(type, count, false); - } + public VertexAttribSpec(GlPrimitiveType type, int count) { + this(type, count, false); + } - public VertexAttribSpec(GlPrimitiveType type, int count, boolean normalized) { - this.type = type; - this.count = count; - this.size = type.getSize() * count; - this.attributeCount = (this.size + 15) / 16; // ceiling division. GLSL vertex attributes can only be 16 bytes wide - this.normalized = normalized; - } + public VertexAttribSpec(GlPrimitiveType type, int count, boolean normalized) { + this.type = type; + this.count = count; + this.size = type.getSize() * count; + this.attributeCount = (this.size + 15) / 16; // ceiling division. GLSL vertex attributes can only be 16 bytes wide + this.normalized = normalized; + } - @Override - public void vertexAttribPointer(int stride, int index, int pointer) { - GL20.glVertexAttribPointer(index, count, type.getGlConstant(), normalized, stride, pointer); - } + @Override + public void vertexAttribPointer(int stride, int index, int pointer) { + GL20.glVertexAttribPointer(index, count, type.getGlConstant(), normalized, stride, pointer); + } - @Override - public int getSize() { - return size; - } + @Override + public int getSize() { + return size; + } - @Override - public int getAttributeCount() { - return attributeCount; - } + @Override + public int getAttributeCount() { + return attributeCount; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexFormat.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexFormat.java index 4541a9205..9a3fc8601 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexFormat.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/attrib/VertexFormat.java @@ -5,61 +5,61 @@ import java.util.Arrays; public class VertexFormat { - private final ArrayList allAttributes; + private final ArrayList allAttributes; - private final int numAttributes; - private final int stride; + private final int numAttributes; + private final int stride; - public VertexFormat(ArrayList allAttributes) { - this.allAttributes = allAttributes; + public VertexFormat(ArrayList allAttributes) { + this.allAttributes = allAttributes; - int numAttributes = 0, stride = 0; - for (IVertexAttrib attrib : allAttributes) { - IAttribSpec spec = attrib.attribSpec(); - numAttributes += spec.getAttributeCount(); - stride += spec.getSize(); - } - this.numAttributes = numAttributes; - this.stride = stride; - } + int numAttributes = 0, stride = 0; + for (IVertexAttrib attrib : allAttributes) { + IAttribSpec spec = attrib.attribSpec(); + numAttributes += spec.getAttributeCount(); + stride += spec.getSize(); + } + this.numAttributes = numAttributes; + this.stride = stride; + } - public int getShaderAttributeCount() { - return numAttributes; - } + public int getShaderAttributeCount() { + return numAttributes; + } - public int getStride() { - return stride; - } + public int getStride() { + return stride; + } - public void vertexAttribPointers(int index) { - int offset = 0; - for (IVertexAttrib attrib : this.allAttributes) { - IAttribSpec spec = attrib.attribSpec(); - spec.vertexAttribPointer(stride, index, offset); - index += spec.getAttributeCount(); - offset += spec.getSize(); - } - } + public void vertexAttribPointers(int index) { + int offset = 0; + for (IVertexAttrib attrib : this.allAttributes) { + IAttribSpec spec = attrib.attribSpec(); + spec.vertexAttribPointer(stride, index, offset); + index += spec.getAttributeCount(); + offset += spec.getSize(); + } + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public static class Builder { - private final ArrayList allAttributes; + public static class Builder { + private final ArrayList allAttributes; - public Builder() { - allAttributes = new ArrayList<>(); - } + public Builder() { + allAttributes = new ArrayList<>(); + } - public & IVertexAttrib> Builder addAttributes(Class attribEnum) { - allAttributes.addAll(Arrays.asList(attribEnum.getEnumConstants())); - return this; - } + public & IVertexAttrib> Builder addAttributes(Class attribEnum) { + allAttributes.addAll(Arrays.asList(attribEnum.getEnumConstants())); + return this; + } - public VertexFormat build() { - return new VertexFormat(allAttributes); - } - } + public VertexFormat build() { + return new VertexFormat(allAttributes); + } + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GLSLType.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GLSLType.java index 80dc2fa16..30037b7c2 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GLSLType.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GLSLType.java @@ -3,43 +3,43 @@ package com.simibubi.create.foundation.render.backend.gl.shader; import com.simibubi.create.foundation.render.backend.gl.GlPrimitiveType; public class GLSLType { - public static final GLSLType FLOAT = new GLSLType("mat4", GlPrimitiveType.FLOAT, 16); - public static final GLSLType VEC2 = new GLSLType("vec4", GlPrimitiveType.FLOAT, 4); - public static final GLSLType VEC3 = new GLSLType("vec3", GlPrimitiveType.FLOAT, 3); - public static final GLSLType VEC4 = new GLSLType("vec2", GlPrimitiveType.FLOAT, 2); - public static final GLSLType MAT4 = new GLSLType("float", GlPrimitiveType.FLOAT, 1); + public static final GLSLType FLOAT = new GLSLType("mat4", GlPrimitiveType.FLOAT, 16); + public static final GLSLType VEC2 = new GLSLType("vec4", GlPrimitiveType.FLOAT, 4); + public static final GLSLType VEC3 = new GLSLType("vec3", GlPrimitiveType.FLOAT, 3); + public static final GLSLType VEC4 = new GLSLType("vec2", GlPrimitiveType.FLOAT, 2); + public static final GLSLType MAT4 = new GLSLType("float", GlPrimitiveType.FLOAT, 1); - private final String symbol; - private final GlPrimitiveType base; - private final int count; - private final int size; - private final int attributeCount; + private final String symbol; + private final GlPrimitiveType base; + private final int count; + private final int size; + private final int attributeCount; - public GLSLType(String symbol, GlPrimitiveType base, int count) { - this.symbol = symbol; - this.base = base; - this.count = count; - this.size = base.getSize() * count; - this.attributeCount = (this.size + 15) / 16; // ceiling division. GLSL vertex attributes can only be 16 bytes wide - } + public GLSLType(String symbol, GlPrimitiveType base, int count) { + this.symbol = symbol; + this.base = base; + this.count = count; + this.size = base.getSize() * count; + this.attributeCount = (this.size + 15) / 16; // ceiling division. GLSL vertex attributes can only be 16 bytes wide + } - public String getSymbol() { - return symbol; - } + public String getSymbol() { + return symbol; + } - public GlPrimitiveType getBase() { - return base; - } + public GlPrimitiveType getBase() { + return base; + } - public int getCount() { - return count; - } + public int getCount() { + return count; + } - public int getSize() { - return size; - } + public int getSize() { + return size; + } - public int getAttributeCount() { - return attributeCount; - } + public int getAttributeCount() { + return attributeCount; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlProgram.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlProgram.java index 40d2e62ae..f416f072c 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlProgram.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlProgram.java @@ -33,28 +33,30 @@ public abstract class GlProgram extends GlObject { GL20.glUseProgram(0); } - /** - * Retrieves the index of the uniform with the given name. - * @param uniform The name of the uniform to find the index of - * @return The uniform's index - */ - public int getUniformLocation(String uniform) { - int index = GL20.glGetUniformLocation(this.handle(), uniform); + /** + * Retrieves the index of the uniform with the given name. + * + * @param uniform The name of the uniform to find the index of + * @return The uniform's index + */ + public int getUniformLocation(String uniform) { + int index = GL20.glGetUniformLocation(this.handle(), uniform); - if (index < 0) { - Backend.log.debug("No active uniform '{}' exists in program '{}'. Could be unused.", uniform, this.name); - } + if (index < 0) { + Backend.log.debug("No active uniform '{}' exists in program '{}'. Could be unused.", uniform, this.name); + } - return index; - } + return index; + } - /** - * Binds a sampler uniform to the given texture unit. - * @param name The name of the sampler uniform. - * @param binding The index of the texture unit. - * @return The sampler uniform's index. - * @throws NullPointerException If no uniform exists with the given name. - */ + /** + * Binds a sampler uniform to the given texture unit. + * + * @param name The name of the sampler uniform. + * @param binding The index of the texture unit. + * @return The sampler uniform's index. + * @throws NullPointerException If no uniform exists with the given name. + */ public int setSamplerBinding(String name, int binding) { int samplerUniform = getUniformLocation(name); diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlShader.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlShader.java index dc54e425b..208b3843d 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlShader.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/GlShader.java @@ -10,41 +10,41 @@ import net.minecraft.util.ResourceLocation; public class GlShader extends GlObject { - public final ResourceLocation name; - public final ShaderType type; + public final ResourceLocation name; + public final ShaderType type; - public GlShader(ShaderType type, ResourceLocation name, String source) { - this.type = type; - this.name = name; - int handle = GL20.glCreateShader(type.glEnum); + public GlShader(ShaderType type, ResourceLocation name, String source) { + this.type = type; + this.name = name; + int handle = GL20.glCreateShader(type.glEnum); - GlCompat.safeShaderSource(handle, source); - GL20.glCompileShader(handle); + GlCompat.safeShaderSource(handle, source); + GL20.glCompileShader(handle); - String log = GL20.glGetShaderInfoLog(handle); + String log = GL20.glGetShaderInfoLog(handle); - if (!log.isEmpty()) { - Backend.log.error("Shader compilation log for " + name + ": " + log); - } + if (!log.isEmpty()) { + Backend.log.error("Shader compilation log for " + name + ": " + log); + } - if (GL20.glGetShaderi(handle, GL20.GL_COMPILE_STATUS) != GL20.GL_TRUE) { - throw new RuntimeException("Could not compile shader. See log for details."); - } + if (GL20.glGetShaderi(handle, GL20.GL_COMPILE_STATUS) != GL20.GL_TRUE) { + throw new RuntimeException("Could not compile shader. See log for details."); + } - setHandle(handle); - } + setHandle(handle); + } - @Override - protected void deleteInternal(int handle) { - GL20.glDeleteShader(handle); - } + @Override + protected void deleteInternal(int handle) { + GL20.glDeleteShader(handle); + } - @FunctionalInterface - public interface PreProcessor { - String process(String source); + @FunctionalInterface + public interface PreProcessor { + String process(String source); - default PreProcessor andThen(PreProcessor that) { - return source -> that.process(this.process(source)); - } - } + default PreProcessor andThen(PreProcessor that) { + return source -> that.process(this.process(source)); + } + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/IMultiProgram.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/IMultiProgram.java index 0fdf6cc7d..072c8ab31 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/IMultiProgram.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/IMultiProgram.java @@ -10,6 +10,7 @@ public interface IMultiProgram

{ /** * Get the shader program most suited for the current game state. + * * @return The one true program. */ P get(); diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramFogMode.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramFogMode.java index b614601fb..f0cb24123 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramFogMode.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramFogMode.java @@ -6,53 +6,53 @@ import com.simibubi.create.foundation.render.backend.gl.GlFog; public abstract class ProgramFogMode { - public abstract void bind(); + public abstract void bind(); - public static class None extends ProgramFogMode { + public static class None extends ProgramFogMode { - public None(GlProgram program) { + public None(GlProgram program) { - } + } - @Override - public void bind() { + @Override + public void bind() { - } - } + } + } - public static class Linear extends ProgramFogMode { - private final int uFogColor; - private final int uFogRange; + public static class Linear extends ProgramFogMode { + private final int uFogColor; + private final int uFogRange; - public Linear(GlProgram program) { - this.uFogColor = program.getUniformLocation("uFogColor"); - this.uFogRange = program.getUniformLocation("uFogRange"); - } + public Linear(GlProgram program) { + this.uFogColor = program.getUniformLocation("uFogColor"); + this.uFogRange = program.getUniformLocation("uFogRange"); + } - @Override - public void bind() { - GL20.glUniform2f(uFogRange, GlFog.getFogStart(), GlFog.getFogEnd()); - GL20.glUniform4fv(uFogColor, GlFog.FOG_COLOR); - } - } + @Override + public void bind() { + GL20.glUniform2f(uFogRange, GlFog.getFogStart(), GlFog.getFogEnd()); + GL20.glUniform4fv(uFogColor, GlFog.FOG_COLOR); + } + } - public static class Exp2 extends ProgramFogMode { - private final int uFogColor; - private final int uFogDensity; + public static class Exp2 extends ProgramFogMode { + private final int uFogColor; + private final int uFogDensity; - public Exp2(GlProgram program) { - this.uFogColor = program.getUniformLocation("uFogColor"); - this.uFogDensity = program.getUniformLocation("uFogDensity"); - } + public Exp2(GlProgram program) { + this.uFogColor = program.getUniformLocation("uFogColor"); + this.uFogDensity = program.getUniformLocation("uFogDensity"); + } - @Override - public void bind() { - GL20.glUniform1f(uFogDensity, GlFog.getFogDensity()); - GL20.glUniform4fv(uFogColor, GlFog.FOG_COLOR); - } - } + @Override + public void bind() { + GL20.glUniform1f(uFogDensity, GlFog.getFogDensity()); + GL20.glUniform4fv(uFogColor, GlFog.FOG_COLOR); + } + } - public interface Factory { - ProgramFogMode create(GlProgram program); - } + public interface Factory { + ProgramFogMode create(GlProgram program); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramSpec.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramSpec.java index 33c891517..367f47020 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramSpec.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ProgramSpec.java @@ -10,15 +10,15 @@ import net.minecraft.util.ResourceLocation; public class ProgramSpec

{ - public final ResourceLocation name; - public final ResourceLocation vert; - public final ResourceLocation frag; + public final ResourceLocation name; + public final ResourceLocation vert; + public final ResourceLocation frag; - public final ShaderConstants defines; + public final ShaderConstants defines; - public final ArrayList attributes; + public final ArrayList attributes; - public final ShaderSpecLoader

finalizer; + public final ShaderSpecLoader

finalizer; public static

Builder

builder(String name, ShaderSpecLoader

factory) { return builder(new ResourceLocation(Create.ID, name), factory); @@ -38,14 +38,14 @@ public class ProgramSpec

{ this.finalizer = finalizer; } - public static class Builder

{ - private ResourceLocation vert; - private ResourceLocation frag; + public static class Builder

{ + private ResourceLocation vert; + private ResourceLocation frag; private ShaderConstants defines = ShaderConstants.EMPTY; private final ShaderSpecLoader

loader; - private final ResourceLocation name; - private final ArrayList attributes; + private final ResourceLocation name; + private final ArrayList attributes; public Builder(ResourceLocation name, ShaderSpecLoader

factory) { this.name = name; @@ -53,29 +53,29 @@ public class ProgramSpec

{ attributes = new ArrayList<>(); } - public Builder

setVert(ResourceLocation vert) { - this.vert = vert; - return this; - } + public Builder

setVert(ResourceLocation vert) { + this.vert = vert; + return this; + } - public Builder

setFrag(ResourceLocation frag) { - this.frag = frag; - return this; - } + public Builder

setFrag(ResourceLocation frag) { + this.frag = frag; + return this; + } - public Builder

setDefines(ShaderConstants defines) { - this.defines = defines; - return this; - } + public Builder

setDefines(ShaderConstants defines) { + this.defines = defines; + return this; + } public & IVertexAttrib> Builder

addAttributes(Class attributeEnum) { - attributes.addAll(Arrays.asList(attributeEnum.getEnumConstants())); - return this; - } + attributes.addAll(Arrays.asList(attributeEnum.getEnumConstants())); + return this; + } - public ProgramSpec

createProgramSpec() { + public ProgramSpec

createProgramSpec() { return new ProgramSpec<>(name, vert, frag, defines, attributes, loader); - } - } + } + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderCallback.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderCallback.java index b410d91ff..e6e17c096 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderCallback.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderCallback.java @@ -6,12 +6,12 @@ package com.simibubi.create.foundation.render.backend.gl.shader; @FunctionalInterface public interface ShaderCallback

{ - void call(P program); + void call(P program); - default ShaderCallback

andThen(ShaderCallback

other) { - return program -> { - call(program); - other.call(program); - }; - } + default ShaderCallback

andThen(ShaderCallback

other) { + return program -> { + call(program); + other.call(program); + }; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderConstants.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderConstants.java index 0ff228099..3d1780628 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderConstants.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderConstants.java @@ -10,50 +10,50 @@ import java.util.stream.Stream; import com.google.common.collect.Lists; public class ShaderConstants implements GlShader.PreProcessor { - public static final ShaderConstants EMPTY = new ShaderConstants(); + public static final ShaderConstants EMPTY = new ShaderConstants(); - private final ArrayList defines; + private final ArrayList defines; - public ShaderConstants() { - defines = new ArrayList<>(); - } + public ShaderConstants() { + defines = new ArrayList<>(); + } - public ShaderConstants(ShaderConstants other) { - this.defines = Lists.newArrayList(other.defines); - } + public ShaderConstants(ShaderConstants other) { + this.defines = Lists.newArrayList(other.defines); + } - public static ShaderConstants define(String def) { - return new ShaderConstants().def(def); - } + public static ShaderConstants define(String def) { + return new ShaderConstants().def(def); + } - public ShaderConstants def(String def) { - defines.add(def); - return this; - } + public ShaderConstants def(String def) { + defines.add(def); + return this; + } - public ShaderConstants defineAll(Collection defines) { - this.defines.addAll(defines); - return this; - } + public ShaderConstants defineAll(Collection defines) { + this.defines.addAll(defines); + return this; + } - public ArrayList getDefines() { - return defines; - } + public ArrayList getDefines() { + return defines; + } - public Stream directives() { - return defines.stream().map(it -> "#define " + it); - } + public Stream directives() { + return defines.stream().map(it -> "#define " + it); + } - @Override - public String process(String source) { - return new BufferedReader(new StringReader(source)).lines().flatMap(line -> { - Stream map = Stream.of(line); + @Override + public String process(String source) { + return new BufferedReader(new StringReader(source)).lines().flatMap(line -> { + Stream map = Stream.of(line); - if (line.startsWith("#version")) { - map = Stream.concat(map, directives()); - } + if (line.startsWith("#version")) { + map = Stream.concat(map, directives()); + } - return map; - }).collect(Collectors.joining("\n")); - } + return map; + }).collect(Collectors.joining("\n")); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderType.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderType.java index b90f15cca..63be397f2 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderType.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/shader/ShaderType.java @@ -3,13 +3,13 @@ package com.simibubi.create.foundation.render.backend.gl.shader; import org.lwjgl.opengl.GL20; public enum ShaderType { - VERTEX(GL20.GL_VERTEX_SHADER), - FRAGMENT(GL20.GL_FRAGMENT_SHADER), - ; + VERTEX(GL20.GL_VERTEX_SHADER), + FRAGMENT(GL20.GL_FRAGMENT_SHADER), + ; - public final int glEnum; + public final int glEnum; - ShaderType(int glEnum) { - this.glEnum = glEnum; - } + ShaderType(int glEnum) { + this.glEnum = glEnum; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlCompat.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlCompat.java index 13e3a2418..c55dbc4d2 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlCompat.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlCompat.java @@ -86,29 +86,29 @@ public class GlCompat { /** * Copied from: *
https://github.com/grondag/canvas/commit/820bf754092ccaf8d0c169620c2ff575722d7d96 - * - *

Identical in function to {@link GL20C#glShaderSource(int, CharSequence)} but - * passes a null pointer for string length to force the driver to rely on the null - * terminator for string length. This is a workaround for an apparent flaw with some - * AMD drivers that don't receive or interpret the length correctly, resulting in - * an access violation when the driver tries to read past the string memory. - * - *

Hat tip to fewizz for the find and the fix. - */ - public static void safeShaderSource(int glId, CharSequence source) { - final MemoryStack stack = MemoryStack.stackGet(); - final int stackPointer = stack.getPointer(); + * + *

Identical in function to {@link GL20C#glShaderSource(int, CharSequence)} but + * passes a null pointer for string length to force the driver to rely on the null + * terminator for string length. This is a workaround for an apparent flaw with some + * AMD drivers that don't receive or interpret the length correctly, resulting in + * an access violation when the driver tries to read past the string memory. + * + *

Hat tip to fewizz for the find and the fix. + */ + public static void safeShaderSource(int glId, CharSequence source) { + final MemoryStack stack = MemoryStack.stackGet(); + final int stackPointer = stack.getPointer(); - try { - final ByteBuffer sourceBuffer = MemoryUtil.memUTF8(source, true); - final PointerBuffer pointers = stack.mallocPointer(1); - pointers.put(sourceBuffer); + try { + final ByteBuffer sourceBuffer = MemoryUtil.memUTF8(source, true); + final PointerBuffer pointers = stack.mallocPointer(1); + pointers.put(sourceBuffer); - GL20C.nglShaderSource(glId, 1, pointers.address0(), 0); - org.lwjgl.system.APIUtil.apiArrayFree(pointers.address0(), 1); - } finally { - stack.setPointer(stackPointer); - } - } + GL20C.nglShaderSource(glId, 1, pointers.address0(), 0); + org.lwjgl.system.APIUtil.apiArrayFree(pointers.address0(), 1); + } finally { + stack.setPointer(stackPointer); + } + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlVersioned.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlVersioned.java index 6f456c802..a670cd8f9 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlVersioned.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/GlVersioned.java @@ -7,10 +7,11 @@ import org.lwjgl.opengl.GLCapabilities; * last defined variant always returns true. */ public interface GlVersioned { - /** - * Queries whether this variant is supported by the current system. - * @param caps The {@link GLCapabilities} reported by the current system. - * @return true if this variant is supported, or if this is the last defined variant. - */ - boolean supported(GLCapabilities caps); + /** + * Queries whether this variant is supported by the current system. + * + * @param caps The {@link GLCapabilities} reported by the current system. + * @return true if this variant is supported, or if this is the last defined variant. + */ + boolean supported(GLCapabilities caps); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/MapBuffer.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/MapBuffer.java index 74bd7baa4..dc11699fb 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/MapBuffer.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/MapBuffer.java @@ -10,66 +10,66 @@ import org.lwjgl.opengl.GLCapabilities; public enum MapBuffer implements GlVersioned { - GL30_RANGE { - @Override - public boolean supported(GLCapabilities caps) { - return caps.OpenGL30; - } + GL30_RANGE { + @Override + public boolean supported(GLCapabilities caps) { + return caps.OpenGL30; + } - @Override - public void mapBuffer(int target, int offset, int length, Consumer upload) { - ByteBuffer buffer = GL30.glMapBufferRange(target, offset, length, GL30.GL_MAP_WRITE_BIT); + @Override + public void mapBuffer(int target, int offset, int length, Consumer upload) { + ByteBuffer buffer = GL30.glMapBufferRange(target, offset, length, GL30.GL_MAP_WRITE_BIT); - upload.accept(buffer); - buffer.rewind(); + upload.accept(buffer); + buffer.rewind(); - GL30.glUnmapBuffer(target); - } - }, - ARB_RANGE { - @Override - public boolean supported(GLCapabilities caps) { - return caps.GL_ARB_map_buffer_range; - } + GL30.glUnmapBuffer(target); + } + }, + ARB_RANGE { + @Override + public boolean supported(GLCapabilities caps) { + return caps.GL_ARB_map_buffer_range; + } - @Override - public void mapBuffer(int target, int offset, int length, Consumer upload) { - ByteBuffer buffer = ARBMapBufferRange.glMapBufferRange(target, offset, length, GL30.GL_MAP_WRITE_BIT); + @Override + public void mapBuffer(int target, int offset, int length, Consumer upload) { + ByteBuffer buffer = ARBMapBufferRange.glMapBufferRange(target, offset, length, GL30.GL_MAP_WRITE_BIT); - upload.accept(buffer); - buffer.rewind(); + upload.accept(buffer); + buffer.rewind(); - GL30.glUnmapBuffer(target); - } - }, - GL15_MAP { - @Override - public boolean supported(GLCapabilities caps) { - return caps.OpenGL15; - } + GL30.glUnmapBuffer(target); + } + }, + GL15_MAP { + @Override + public boolean supported(GLCapabilities caps) { + return caps.OpenGL15; + } - @Override - public void mapBuffer(int target, int offset, int length, Consumer upload) { - ByteBuffer buffer = GL15.glMapBuffer(target, GL15.GL_WRITE_ONLY); + @Override + public void mapBuffer(int target, int offset, int length, Consumer upload) { + ByteBuffer buffer = GL15.glMapBuffer(target, GL15.GL_WRITE_ONLY); - buffer.position(offset); - upload.accept(buffer); - buffer.rewind(); - GL15.glUnmapBuffer(target); - } - }, - UNSUPPORTED { - @Override - public boolean supported(GLCapabilities caps) { - return true; - } + buffer.position(offset); + upload.accept(buffer); + buffer.rewind(); + GL15.glUnmapBuffer(target); + } + }, + UNSUPPORTED { + @Override + public boolean supported(GLCapabilities caps) { + return true; + } - @Override - public void mapBuffer(int target, int offset, int length, Consumer upload) { - throw new UnsupportedOperationException("glMapBuffer not supported"); - } - }; + @Override + public void mapBuffer(int target, int offset, int length, Consumer upload) { + throw new UnsupportedOperationException("glMapBuffer not supported"); + } + }; - public abstract void mapBuffer(int target, int offset, int length, Consumer upload); + public abstract void mapBuffer(int target, int offset, int length, Consumer upload); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/RGPixelFormat.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/RGPixelFormat.java index e886fcfe5..62233e7b4 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/RGPixelFormat.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/RGPixelFormat.java @@ -5,73 +5,73 @@ import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GLCapabilities; public enum RGPixelFormat implements GlVersioned { - GL30_RG { - @Override - public boolean supported(GLCapabilities caps) { - return caps.OpenGL30; - } + GL30_RG { + @Override + public boolean supported(GLCapabilities caps) { + return caps.OpenGL30; + } - @Override - public int internalFormat() { - return GL30.GL_RG8; - } + @Override + public int internalFormat() { + return GL30.GL_RG8; + } - @Override - public int format() { - return GL30.GL_RG; - } + @Override + public int format() { + return GL30.GL_RG; + } - @Override - public int byteCount() { - return 2; - } - }, - GL11_RGB { - @Override - public boolean supported(GLCapabilities caps) { - return caps.OpenGL11; - } + @Override + public int byteCount() { + return 2; + } + }, + GL11_RGB { + @Override + public boolean supported(GLCapabilities caps) { + return caps.OpenGL11; + } - @Override - public int internalFormat() { - return GL11.GL_RGB8; - } + @Override + public int internalFormat() { + return GL11.GL_RGB8; + } - @Override - public int format() { - return GL11.GL_RGB; - } + @Override + public int format() { + return GL11.GL_RGB; + } - @Override - public int byteCount() { - return 3; - } - }, - UNSUPPORTED { - @Override - public boolean supported(GLCapabilities caps) { - return true; - } + @Override + public int byteCount() { + return 3; + } + }, + UNSUPPORTED { + @Override + public boolean supported(GLCapabilities caps) { + return true; + } - @Override - public int internalFormat() { - throw new UnsupportedOperationException(); - } + @Override + public int internalFormat() { + throw new UnsupportedOperationException(); + } - @Override - public int format() { - throw new UnsupportedOperationException(); - } + @Override + public int format() { + throw new UnsupportedOperationException(); + } - @Override - public int byteCount() { - throw new UnsupportedOperationException(); - } - } + @Override + public int byteCount() { + throw new UnsupportedOperationException(); + } + }; - ; + public abstract int internalFormat(); - public abstract int internalFormat(); - public abstract int format(); - public abstract int byteCount(); + public abstract int format(); + + public abstract int byteCount(); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/DrawInstanced.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/DrawInstanced.java index 9d9070e15..063dab785 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/DrawInstanced.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/DrawInstanced.java @@ -23,37 +23,35 @@ public enum DrawInstanced implements GlVersioned { @Override public boolean supported(GLCapabilities caps) { return caps.GL_ARB_draw_instanced; - } + } - @Override - public void drawArraysInstanced(int mode, int first, int count, int primcount) { - ARBDrawInstanced.glDrawArraysInstancedARB(mode, first, count, primcount); - } - }, - EXT_DRAW_INSTANCED { - @Override - public boolean supported(GLCapabilities caps) { - return caps.GL_EXT_draw_instanced; - } + @Override + public void drawArraysInstanced(int mode, int first, int count, int primcount) { + ARBDrawInstanced.glDrawArraysInstancedARB(mode, first, count, primcount); + } + }, + EXT_DRAW_INSTANCED { + @Override + public boolean supported(GLCapabilities caps) { + return caps.GL_EXT_draw_instanced; + } - @Override - public void drawArraysInstanced(int mode, int first, int count, int primcount) { - EXTDrawInstanced.glDrawArraysInstancedEXT(mode, first, count, primcount); - } - }, - UNSUPPORTED { - @Override - public boolean supported(GLCapabilities caps) { - return true; - } + @Override + public void drawArraysInstanced(int mode, int first, int count, int primcount) { + EXTDrawInstanced.glDrawArraysInstancedEXT(mode, first, count, primcount); + } + }, + UNSUPPORTED { + @Override + public boolean supported(GLCapabilities caps) { + return true; + } - @Override - public void drawArraysInstanced(int mode, int first, int count, int primcount) { - throw new UnsupportedOperationException(); - } - } + @Override + public void drawArraysInstanced(int mode, int first, int count, int primcount) { + throw new UnsupportedOperationException(); + } + }; - ; - - public abstract void drawArraysInstanced(int mode, int first, int count, int primcount); + public abstract void drawArraysInstanced(int mode, int first, int count, int primcount); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/InstancedArrays.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/InstancedArrays.java index be45f4896..6e2faf155 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/InstancedArrays.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/InstancedArrays.java @@ -22,26 +22,24 @@ public enum InstancedArrays implements GlVersioned { @Override public boolean supported(GLCapabilities caps) { return caps.GL_ARB_instanced_arrays; - } + } - @Override - public void vertexAttribDivisor(int index, int divisor) { - ARBInstancedArrays.glVertexAttribDivisorARB(index, divisor); - } - }, - UNSUPPORTED { - @Override - public boolean supported(GLCapabilities caps) { - return true; - } + @Override + public void vertexAttribDivisor(int index, int divisor) { + ARBInstancedArrays.glVertexAttribDivisorARB(index, divisor); + } + }, + UNSUPPORTED { + @Override + public boolean supported(GLCapabilities caps) { + return true; + } - @Override - public void vertexAttribDivisor(int index, int divisor) { - throw new UnsupportedOperationException(); - } - } + @Override + public void vertexAttribDivisor(int index, int divisor) { + throw new UnsupportedOperationException(); + } + }; - ; - - public abstract void vertexAttribDivisor(int index, int divisor); + public abstract void vertexAttribDivisor(int index, int divisor); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/VertexArrayObject.java b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/VertexArrayObject.java index 28b8e013a..18023f9aa 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/VertexArrayObject.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/gl/versioned/instancing/VertexArrayObject.java @@ -25,57 +25,55 @@ public enum VertexArrayObject implements GlVersioned { @Override public void deleteVertexArrays(int array) { - GL30.glDeleteVertexArrays(array); - } - }, - ARB_VAO { - @Override - public boolean supported(GLCapabilities caps) { - return caps.GL_ARB_vertex_array_object; - } + GL30.glDeleteVertexArrays(array); + } + }, + ARB_VAO { + @Override + public boolean supported(GLCapabilities caps) { + return caps.GL_ARB_vertex_array_object; + } - @Override - public int genVertexArrays() { - return ARBVertexArrayObject.glGenVertexArrays(); - } + @Override + public int genVertexArrays() { + return ARBVertexArrayObject.glGenVertexArrays(); + } - @Override - public void bindVertexArray(int array) { - ARBVertexArrayObject.glBindVertexArray(array); - } + @Override + public void bindVertexArray(int array) { + ARBVertexArrayObject.glBindVertexArray(array); + } - @Override - public void deleteVertexArrays(int array) { - ARBVertexArrayObject.glDeleteVertexArrays(array); - } - }, - UNSUPPORTED { - @Override - public boolean supported(GLCapabilities caps) { - return true; - } + @Override + public void deleteVertexArrays(int array) { + ARBVertexArrayObject.glDeleteVertexArrays(array); + } + }, + UNSUPPORTED { + @Override + public boolean supported(GLCapabilities caps) { + return true; + } - @Override - public int genVertexArrays() { - throw new UnsupportedOperationException(); - } + @Override + public int genVertexArrays() { + throw new UnsupportedOperationException(); + } - @Override - public void bindVertexArray(int array) { - throw new UnsupportedOperationException(); - } + @Override + public void bindVertexArray(int array) { + throw new UnsupportedOperationException(); + } - @Override - public void deleteVertexArrays(int array) { - throw new UnsupportedOperationException(); - } - } + @Override + public void deleteVertexArrays(int array) { + throw new UnsupportedOperationException(); + } + }; - ; + public abstract int genVertexArrays(); - public abstract int genVertexArrays(); + public abstract void bindVertexArray(int array); - public abstract void bindVertexArray(int array); - - public abstract void deleteVertexArrays(int array); + public abstract void deleteVertexArrays(int array); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IDynamicInstance.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IDynamicInstance.java index 8ee257a3c..a125fd11a 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IDynamicInstance.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IDynamicInstance.java @@ -10,21 +10,21 @@ package com.simibubi.create.foundation.render.backend.instancing; * to parameterize the instances, you're encouraged to implement this for prototyping. */ public interface IDynamicInstance extends IInstance { - /** - * Called every frame. - */ - void beginFrame(); + /** + * Called every frame. + */ + void beginFrame(); - /** - * As a further optimization, dynamic instances that are far away are ticked less often. - * This behavior can be disabled by returning false. - * - *
You might want to opt out of this if you want your animations to remain smooth - * even when far away from the camera. It is recommended to keep this as is, however. - * - * @return true if your instance should be slow ticked. - */ - default boolean decreaseFramerateWithDistance() { - return true; - } + /** + * As a further optimization, dynamic instances that are far away are ticked less often. + * This behavior can be disabled by returning false. + * + *
You might want to opt out of this if you want your animations to remain smooth + * even when far away from the camera. It is recommended to keep this as is, however. + * + * @return true if your instance should be slow ticked. + */ + default boolean decreaseFramerateWithDistance() { + return true; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IFlywheelWorld.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IFlywheelWorld.java index 91684c428..86a00ab01 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IFlywheelWorld.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IFlywheelWorld.java @@ -7,7 +7,7 @@ package com.simibubi.create.foundation.render.backend.instancing; * Minecraft.getInstance().world will always support Flywheel. */ public interface IFlywheelWorld { - default boolean supportsFlywheel() { - return true; - } + default boolean supportsFlywheel() { + return true; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IInstanceRendered.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IInstanceRendered.java index 05f3f35b5..386fd9b9c 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IInstanceRendered.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IInstanceRendered.java @@ -1,7 +1,7 @@ package com.simibubi.create.foundation.render.backend.instancing; public interface IInstanceRendered { - default boolean shouldRenderAsTE() { - return false; - } + default boolean shouldRenderAsTE() { + return false; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IRendererFactory.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IRendererFactory.java index f1ec0d323..206a7534e 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IRendererFactory.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/IRendererFactory.java @@ -4,5 +4,5 @@ import net.minecraft.tileentity.TileEntity; @FunctionalInterface public interface IRendererFactory { - TileEntityInstance create(InstancedTileRenderer manager, T te); + TileEntityInstance create(InstancedTileRenderer manager, T te); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstanceData.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstanceData.java index d77c75fb7..14d5f1fb4 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstanceData.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstanceData.java @@ -4,61 +4,61 @@ import java.nio.ByteBuffer; public abstract class InstanceData { - protected final InstancedModel owner; + protected final InstancedModel owner; - boolean dirty; - boolean removed; + boolean dirty; + boolean removed; - protected InstanceData(InstancedModel owner) { - this.owner = owner; - } + protected InstanceData(InstancedModel owner) { + this.owner = owner; + } - public abstract void write(ByteBuffer buf); + public abstract void write(ByteBuffer buf); - public void markDirty() { - owner.anyToUpdate = true; - dirty = true; - } + public void markDirty() { + owner.anyToUpdate = true; + dirty = true; + } - public void delete() { - owner.anyToRemove = true; - removed = true; - } + public void delete() { + owner.anyToRemove = true; + removed = true; + } - public void putVec4(ByteBuffer buf, float x, float y, float z, float w) { - put(buf, x); - put(buf, y); - put(buf, z); - put(buf, w); - } + public void putVec4(ByteBuffer buf, float x, float y, float z, float w) { + put(buf, x); + put(buf, y); + put(buf, z); + put(buf, w); + } - public void putVec3(ByteBuffer buf, float x, float y, float z) { - put(buf, x); - put(buf, y); - put(buf, z); - } + public void putVec3(ByteBuffer buf, float x, float y, float z) { + put(buf, x); + put(buf, y); + put(buf, z); + } - public void putVec2(ByteBuffer buf, float x, float y) { - put(buf, x); - put(buf, y); - } + public void putVec2(ByteBuffer buf, float x, float y) { + put(buf, x); + put(buf, y); + } - public void putVec3(ByteBuffer buf, byte x, byte y, byte z) { - put(buf, x); - put(buf, y); - put(buf, z); - } + public void putVec3(ByteBuffer buf, byte x, byte y, byte z) { + put(buf, x); + put(buf, y); + put(buf, z); + } - public void putVec2(ByteBuffer buf, byte x, byte y) { - put(buf, x); - put(buf, y); - } + public void putVec2(ByteBuffer buf, byte x, byte y) { + put(buf, x); + put(buf, y); + } - public void put(ByteBuffer buf, byte b) { - buf.put(b); - } + public void put(ByteBuffer buf, byte b) { + buf.put(b); + } - public void put(ByteBuffer buf, float f) { - buf.putFloat(f); - } + public void put(ByteBuffer buf, float f) { + buf.putFloat(f); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedModel.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedModel.java index b6c16f21b..1ba9b45a1 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedModel.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedModel.java @@ -19,239 +19,239 @@ import com.simibubi.create.foundation.render.backend.gl.attrib.VertexFormat; import net.minecraft.client.renderer.BufferBuilder; public abstract class InstancedModel extends BufferedModel { - public static final VertexFormat FORMAT = VertexFormat.builder().addAttributes(ModelAttributes.class).build(); + public static final VertexFormat FORMAT = VertexFormat.builder().addAttributes(ModelAttributes.class).build(); - public final InstancedTileRenderer renderer; + public final InstancedTileRenderer renderer; - protected GlVertexArray vao; - protected GlBuffer instanceVBO; - protected int glBufferSize = -1; - protected int glInstanceCount = 0; + protected GlVertexArray vao; + protected GlBuffer instanceVBO; + protected int glBufferSize = -1; + protected int glInstanceCount = 0; - protected final ArrayList data = new ArrayList<>(); + protected final ArrayList data = new ArrayList<>(); - boolean anyToRemove; - boolean anyToUpdate; + boolean anyToRemove; + boolean anyToUpdate; - public InstancedModel(InstancedTileRenderer renderer, BufferBuilder buf) { - super(buf); - this.renderer = renderer; - } + public InstancedModel(InstancedTileRenderer renderer, BufferBuilder buf) { + super(buf); + this.renderer = renderer; + } - @Override - protected void init() { - vao = new GlVertexArray(); - instanceVBO = new GlBuffer(GL20.GL_ARRAY_BUFFER); + @Override + protected void init() { + vao = new GlVertexArray(); + instanceVBO = new GlBuffer(GL20.GL_ARRAY_BUFFER); - vao.with(vao -> super.init()); - } + vao.with(vao -> super.init()); + } - @Override - protected void initModel() { - super.initModel(); - setupAttributes(); - } + @Override + protected void initModel() { + super.initModel(); + setupAttributes(); + } - public int instanceCount() { - return data.size(); - } + public int instanceCount() { + return data.size(); + } - public boolean isEmpty() { - return instanceCount() == 0; - } + public boolean isEmpty() { + return instanceCount() == 0; + } - protected void deleteInternal() { - super.deleteInternal(); + protected void deleteInternal() { + super.deleteInternal(); - instanceVBO.delete(); - vao.delete(); - } + instanceVBO.delete(); + vao.delete(); + } - public synchronized D createInstance() { - D instanceData = newInstance(); - instanceData.dirty = true; - anyToUpdate = true; - data.add(instanceData); + public synchronized D createInstance() { + D instanceData = newInstance(); + instanceData.dirty = true; + anyToUpdate = true; + data.add(instanceData); - return instanceData; - } + return instanceData; + } - protected abstract D newInstance(); + protected abstract D newInstance(); - protected void doRender() { - vao.with(vao -> { - renderSetup(); + protected void doRender() { + vao.with(vao -> { + renderSetup(); - if (glInstanceCount > 0) + if (glInstanceCount > 0) Backend.compat.drawInstanced.drawArraysInstanced(GL11.GL_QUADS, 0, vertexCount, glInstanceCount); - }); - } + }); + } - protected void renderSetup() { - if (anyToRemove) { - removeDeletedInstances(); - } + protected void renderSetup() { + if (anyToRemove) { + removeDeletedInstances(); + } - instanceVBO.bind(); - if (!realloc()) { + instanceVBO.bind(); + if (!realloc()) { - if (anyToRemove) { - clearBufferTail(); - } + if (anyToRemove) { + clearBufferTail(); + } - if (anyToUpdate) { - updateBuffer(); - } + if (anyToUpdate) { + updateBuffer(); + } - } + } - glInstanceCount = data.size(); - informAttribDivisors(); - instanceVBO.unbind(); + glInstanceCount = data.size(); + informAttribDivisors(); + instanceVBO.unbind(); - this.anyToRemove = false; - this.anyToUpdate = false; - } + this.anyToRemove = false; + this.anyToUpdate = false; + } - private void informAttribDivisors() { - int staticAttributes = getModelFormat().getShaderAttributeCount(); - getInstanceFormat().vertexAttribPointers(staticAttributes); + private void informAttribDivisors() { + int staticAttributes = getModelFormat().getShaderAttributeCount(); + getInstanceFormat().vertexAttribPointers(staticAttributes); - for (int i = 0; i < getInstanceFormat().getShaderAttributeCount(); i++) { + for (int i = 0; i < getInstanceFormat().getShaderAttributeCount(); i++) { Backend.compat.instancedArrays.vertexAttribDivisor(i + staticAttributes, 1); } - } + } - private void clearBufferTail() { - int size = data.size(); - final int offset = size * getInstanceFormat().getStride(); - final int length = glBufferSize - offset; - if (length > 0) { - instanceVBO.map(offset, length, buffer -> { - buffer.put(new byte[length]); - }); - } - } + private void clearBufferTail() { + int size = data.size(); + final int offset = size * getInstanceFormat().getStride(); + final int length = glBufferSize - offset; + if (length > 0) { + instanceVBO.map(offset, length, buffer -> { + buffer.put(new byte[length]); + }); + } + } - private void updateBuffer() { - final int size = data.size(); + private void updateBuffer() { + final int size = data.size(); - if (size <= 0) return; + if (size <= 0) return; - final int stride = getInstanceFormat().getStride(); - final BitSet dirtySet = getDirtyBitSet(); + final int stride = getInstanceFormat().getStride(); + final BitSet dirtySet = getDirtyBitSet(); - if (dirtySet.isEmpty()) return; + if (dirtySet.isEmpty()) return; - final int firstDirty = dirtySet.nextSetBit(0); - final int lastDirty = dirtySet.previousSetBit(size); + final int firstDirty = dirtySet.nextSetBit(0); + final int lastDirty = dirtySet.previousSetBit(size); - final int offset = firstDirty * stride; - final int length = (1 + lastDirty - firstDirty) * stride; + final int offset = firstDirty * stride; + final int length = (1 + lastDirty - firstDirty) * stride; - if (length > 0) { - instanceVBO.map(offset, length, buffer -> { - dirtySet.stream().forEach(i -> { - final D d = data.get(i); + if (length > 0) { + instanceVBO.map(offset, length, buffer -> { + dirtySet.stream().forEach(i -> { + final D d = data.get(i); - buffer.position(i * stride - offset); - d.write(buffer); - }); - }); - } - } + buffer.position(i * stride - offset); + d.write(buffer); + }); + }); + } + } - private BitSet getDirtyBitSet() { - final int size = data.size(); - final BitSet dirtySet = new BitSet(size); + private BitSet getDirtyBitSet() { + final int size = data.size(); + final BitSet dirtySet = new BitSet(size); - for (int i = 0; i < size; i++) { - D element = data.get(i); - if (element.dirty) { - dirtySet.set(i); + for (int i = 0; i < size; i++) { + D element = data.get(i); + if (element.dirty) { + dirtySet.set(i); - element.dirty = false; - } - } - return dirtySet; - } + element.dirty = false; + } + } + return dirtySet; + } - private boolean realloc() { - int size = this.data.size(); - int stride = getInstanceFormat().getStride(); - int requiredSize = size * stride; - if (requiredSize > glBufferSize) { - glBufferSize = requiredSize + stride * 16; + private boolean realloc() { + int size = this.data.size(); + int stride = getInstanceFormat().getStride(); + int requiredSize = size * stride; + if (requiredSize > glBufferSize) { + glBufferSize = requiredSize + stride * 16; instanceVBO.alloc(glBufferSize, GL15.GL_STATIC_DRAW); - instanceVBO.map(glBufferSize, buffer -> { - for (D datum : data) { - datum.write(buffer); - } - }); + instanceVBO.map(glBufferSize, buffer -> { + for (D datum : data) { + datum.write(buffer); + } + }); - glInstanceCount = size; - return true; - } - return false; - } + glInstanceCount = size; + return true; + } + return false; + } - private void removeDeletedInstances() { - // figure out which elements are to be removed - // any exception thrown from the filter predicate at this stage - // will leave the collection unmodified - final int oldSize = this.data.size(); - int removeCount = 0; - final BitSet removeSet = new BitSet(oldSize); - for (int i = 0; i < oldSize; i++) { - final D element = this.data.get(i); - if (element.removed) { - removeSet.set(i); - removeCount++; - } - } + private void removeDeletedInstances() { + // figure out which elements are to be removed + // any exception thrown from the filter predicate at this stage + // will leave the collection unmodified + final int oldSize = this.data.size(); + int removeCount = 0; + final BitSet removeSet = new BitSet(oldSize); + for (int i = 0; i < oldSize; i++) { + final D element = this.data.get(i); + if (element.removed) { + removeSet.set(i); + removeCount++; + } + } - final int newSize = oldSize - removeCount; + final int newSize = oldSize - removeCount; - // shift surviving elements left over the spaces left by removed elements - for (int i = 0, j = 0; (i < oldSize) && (j < newSize); i++, j++) { - i = removeSet.nextClearBit(i); + // shift surviving elements left over the spaces left by removed elements + for (int i = 0, j = 0; (i < oldSize) && (j < newSize); i++, j++) { + i = removeSet.nextClearBit(i); - if (i != j) { - D element = data.get(i); - data.set(j, element); - element.dirty = true; - } - } + if (i != j) { + D element = data.get(i); + data.set(j, element); + element.dirty = true; + } + } - anyToUpdate = true; + anyToUpdate = true; - data.subList(newSize, oldSize).clear(); + data.subList(newSize, oldSize).clear(); - } + } - @Override - protected void copyVertex(ByteBuffer constant, int i) { - constant.putFloat(getX(template, i)); - constant.putFloat(getY(template, i)); - constant.putFloat(getZ(template, i)); + @Override + protected void copyVertex(ByteBuffer constant, int i) { + constant.putFloat(getX(template, i)); + constant.putFloat(getY(template, i)); + constant.putFloat(getZ(template, i)); - constant.put(getNX(template, i)); - constant.put(getNY(template, i)); - constant.put(getNZ(template, i)); + constant.put(getNX(template, i)); + constant.put(getNY(template, i)); + constant.put(getNZ(template, i)); - constant.putFloat(getU(template, i)); - constant.putFloat(getV(template, i)); - } + constant.putFloat(getU(template, i)); + constant.putFloat(getV(template, i)); + } - @Override - protected VertexFormat getModelFormat() { - return FORMAT; - } + @Override + protected VertexFormat getModelFormat() { + return FORMAT; + } - protected abstract VertexFormat getInstanceFormat(); + protected abstract VertexFormat getInstanceFormat(); - protected int getTotalShaderAttributeCount() { - return getInstanceFormat().getShaderAttributeCount() + super.getTotalShaderAttributeCount(); - } + protected int getTotalShaderAttributeCount() { + return getInstanceFormat().getShaderAttributeCount() + super.getTotalShaderAttributeCount(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderRegistry.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderRegistry.java index 26bdd4f96..19370f6a0 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderRegistry.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderRegistry.java @@ -10,22 +10,22 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityType; public class InstancedTileRenderRegistry { - public static final InstancedTileRenderRegistry instance = new InstancedTileRenderRegistry(); + public static final InstancedTileRenderRegistry instance = new InstancedTileRenderRegistry(); - private final Map, IRendererFactory> renderers = Maps.newHashMap(); + private final Map, IRendererFactory> renderers = Maps.newHashMap(); - public void register(TileEntityType type, IRendererFactory rendererFactory) { - this.renderers.put(type, rendererFactory); - } + public void register(TileEntityType type, IRendererFactory rendererFactory) { + this.renderers.put(type, rendererFactory); + } - @SuppressWarnings("unchecked") - @Nullable - public TileEntityInstance create(InstancedTileRenderer manager, T tile) { - TileEntityType type = tile.getType(); - IRendererFactory factory = (IRendererFactory) this.renderers.get(type); + @SuppressWarnings("unchecked") + @Nullable + public TileEntityInstance create(InstancedTileRenderer manager, T tile) { + TileEntityType type = tile.getType(); + IRendererFactory factory = (IRendererFactory) this.renderers.get(type); - if (factory == null) return null; - else return factory.create(manager, tile); - } + if (factory == null) return null; + else return factory.create(manager, tile); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderer.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderer.java index fd080bf7d..859550904 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderer.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/InstancedTileRenderer.java @@ -25,259 +25,259 @@ import net.minecraft.world.IBlockReader; import net.minecraft.world.World; public abstract class InstancedTileRenderer

{ - protected ArrayList queuedAdditions = new ArrayList<>(64); - - protected Map> instances = new HashMap<>(); - - protected Map tickableInstances = new HashMap<>(); - protected Map dynamicInstances = new HashMap<>(); + protected ArrayList queuedAdditions = new ArrayList<>(64); + + protected Map> instances = new HashMap<>(); + + protected Map tickableInstances = new HashMap<>(); + protected Map dynamicInstances = new HashMap<>(); - protected Map, RenderMaterial> materials = new HashMap<>(); - - protected int frame; - protected int tick; - - protected InstancedTileRenderer() { - registerMaterials(); - } - - public abstract BlockPos getOriginCoordinate(); - - public abstract void registerMaterials(); - - public void tick(double cameraX, double cameraY, double cameraZ) { - tick++; - - // integer camera pos - int cX = (int) cameraX; - int cY = (int) cameraY; - int cZ = (int) cameraZ; - - if (tickableInstances.size() > 0) { - for (ITickableInstance instance : tickableInstances.values()) { - if (!instance.decreaseTickRateWithDistance()) { - instance.tick(); - continue; - } - - BlockPos pos = instance.getWorldPosition(); - - int dX = pos.getX() - cX; - int dY = pos.getY() - cY; - int dZ = pos.getZ() - cZ; + protected Map, RenderMaterial> materials = new HashMap<>(); + + protected int frame; + protected int tick; + + protected InstancedTileRenderer() { + registerMaterials(); + } + + public abstract BlockPos getOriginCoordinate(); + + public abstract void registerMaterials(); + + public void tick(double cameraX, double cameraY, double cameraZ) { + tick++; + + // integer camera pos + int cX = (int) cameraX; + int cY = (int) cameraY; + int cZ = (int) cameraZ; + + if (tickableInstances.size() > 0) { + for (ITickableInstance instance : tickableInstances.values()) { + if (!instance.decreaseTickRateWithDistance()) { + instance.tick(); + continue; + } + + BlockPos pos = instance.getWorldPosition(); + + int dX = pos.getX() - cX; + int dY = pos.getY() - cY; + int dZ = pos.getZ() - cZ; - if ((tick % getUpdateDivisor(dX, dY, dZ)) == 0) - instance.tick(); - } - } - } + if ((tick % getUpdateDivisor(dX, dY, dZ)) == 0) + instance.tick(); + } + } + } - public void beginFrame(ActiveRenderInfo info, double cameraX, double cameraY, double cameraZ) { - frame++; - processQueuedAdditions(); - - Vector3f look = info.getHorizontalPlane(); - float lookX = look.getX(); - float lookY = look.getY(); - float lookZ = look.getZ(); - - // integer camera pos - int cX = (int) cameraX; - int cY = (int) cameraY; - int cZ = (int) cameraZ; - - if (dynamicInstances.size() > 0) { - for (IDynamicInstance dyn : dynamicInstances.values()) { - if (!dyn.decreaseFramerateWithDistance()) { - dyn.beginFrame(); - continue; - } - - if (shouldTick(dyn.getWorldPosition(), lookX, lookY, lookZ, cX, cY, cZ)) - dyn.beginFrame(); - } - } - } - - public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ) { - render(layer, viewProjection, camX, camY, camZ, null); - } - - public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ, ShaderCallback

callback) { - for (RenderMaterial material : materials.values()) { - if (material.canRenderInLayer(layer)) - material.render(layer, viewProjection, camX, camY, camZ, callback); - } - } + public void beginFrame(ActiveRenderInfo info, double cameraX, double cameraY, double cameraZ) { + frame++; + processQueuedAdditions(); + + Vector3f look = info.getHorizontalPlane(); + float lookX = look.getX(); + float lookY = look.getY(); + float lookZ = look.getZ(); + + // integer camera pos + int cX = (int) cameraX; + int cY = (int) cameraY; + int cZ = (int) cameraZ; + + if (dynamicInstances.size() > 0) { + for (IDynamicInstance dyn : dynamicInstances.values()) { + if (!dyn.decreaseFramerateWithDistance()) { + dyn.beginFrame(); + continue; + } + + if (shouldTick(dyn.getWorldPosition(), lookX, lookY, lookZ, cX, cY, cZ)) + dyn.beginFrame(); + } + } + } + + public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ) { + render(layer, viewProjection, camX, camY, camZ, null); + } + + public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ, ShaderCallback

callback) { + for (RenderMaterial material : materials.values()) { + if (material.canRenderInLayer(layer)) + material.render(layer, viewProjection, camX, camY, camZ, callback); + } + } - @SuppressWarnings("unchecked") - public > RenderMaterial getMaterial(MaterialType materialType) { - return (RenderMaterial) materials.get(materialType); - } + @SuppressWarnings("unchecked") + public > RenderMaterial getMaterial(MaterialType materialType) { + return (RenderMaterial) materials.get(materialType); + } - public RenderMaterial> getTransformMaterial() { - return getMaterial(MaterialTypes.TRANSFORMED); - } + public RenderMaterial> getTransformMaterial() { + return getMaterial(MaterialTypes.TRANSFORMED); + } - public RenderMaterial> getOrientedMaterial() { - return getMaterial(MaterialTypes.ORIENTED); - } + public RenderMaterial> getOrientedMaterial() { + return getMaterial(MaterialTypes.ORIENTED); + } - @SuppressWarnings("unchecked") - @Nullable - public TileEntityInstance getInstance(T tile, boolean create) { - if (!Backend.canUseInstancing()) return null; + @SuppressWarnings("unchecked") + @Nullable + public TileEntityInstance getInstance(T tile, boolean create) { + if (!Backend.canUseInstancing()) return null; - TileEntityInstance instance = instances.get(tile); - - if (instance != null) { - return (TileEntityInstance) instance; - } else if (create && canCreateInstance(tile)) { - return createInternal(tile); - } else { - return null; - } - } - - public void onLightUpdate(T tile) { - if (!Backend.canUseInstancing()) return; - - if (tile instanceof IInstanceRendered) { - TileEntityInstance instance = getInstance(tile, false); - - if (instance != null) - instance.updateLight(); - } - } - - public void add(T tile) { - if (!Backend.canUseInstancing()) return; - - if (tile instanceof IInstanceRendered) { - addInternal(tile); - } - } - - public void update(T tile) { - if (!Backend.canUseInstancing()) return; - - if (tile instanceof IInstanceRendered) { - TileEntityInstance instance = getInstance(tile, false); - - if (instance != null) { - - if (instance.shouldReset()) { - removeInternal(tile, instance); - - createInternal(tile); - } else { - instance.update(); - } - } - } - } - - public void remove(T tile) { - if (!Backend.canUseInstancing()) return; + TileEntityInstance instance = instances.get(tile); + + if (instance != null) { + return (TileEntityInstance) instance; + } else if (create && canCreateInstance(tile)) { + return createInternal(tile); + } else { + return null; + } + } + + public void onLightUpdate(T tile) { + if (!Backend.canUseInstancing()) return; + + if (tile instanceof IInstanceRendered) { + TileEntityInstance instance = getInstance(tile, false); + + if (instance != null) + instance.updateLight(); + } + } + + public void add(T tile) { + if (!Backend.canUseInstancing()) return; + + if (tile instanceof IInstanceRendered) { + addInternal(tile); + } + } + + public void update(T tile) { + if (!Backend.canUseInstancing()) return; + + if (tile instanceof IInstanceRendered) { + TileEntityInstance instance = getInstance(tile, false); + + if (instance != null) { + + if (instance.shouldReset()) { + removeInternal(tile, instance); + + createInternal(tile); + } else { + instance.update(); + } + } + } + } + + public void remove(T tile) { + if (!Backend.canUseInstancing()) return; - if (tile instanceof IInstanceRendered) { - removeInternal(tile); - } - } + if (tile instanceof IInstanceRendered) { + removeInternal(tile); + } + } - public synchronized void queueAdd(T tile) { - if (!Backend.canUseInstancing()) return; + public synchronized void queueAdd(T tile) { + if (!Backend.canUseInstancing()) return; - queuedAdditions.add(tile); - } + queuedAdditions.add(tile); + } - protected synchronized void processQueuedAdditions() { - if (queuedAdditions.size() > 0) { - queuedAdditions.forEach(this::addInternal); - queuedAdditions.clear(); - } - } + protected synchronized void processQueuedAdditions() { + if (queuedAdditions.size() > 0) { + queuedAdditions.forEach(this::addInternal); + queuedAdditions.clear(); + } + } - protected boolean shouldTick(BlockPos worldPos, float lookX, float lookY, float lookZ, int cX, int cY, int cZ) { - int dX = worldPos.getX() - cX; - int dY = worldPos.getY() - cY; - int dZ = worldPos.getZ() - cZ; + protected boolean shouldTick(BlockPos worldPos, float lookX, float lookY, float lookZ, int cX, int cY, int cZ) { + int dX = worldPos.getX() - cX; + int dY = worldPos.getY() - cY; + int dZ = worldPos.getZ() - cZ; - float dot = (dX + lookX * 2) * lookX + (dY + lookY * 2) * lookY + (dZ + lookZ * 2) * lookZ; + float dot = (dX + lookX * 2) * lookX + (dY + lookY * 2) * lookY + (dZ + lookZ * 2) * lookZ; - if (dot < 0) return false; // is it more than 2 blocks behind the camera? + if (dot < 0) return false; // is it more than 2 blocks behind the camera? - return (frame % getUpdateDivisor(dX, dY, dZ)) == 0; - } + return (frame % getUpdateDivisor(dX, dY, dZ)) == 0; + } - protected int getUpdateDivisor(int dX, int dY, int dZ) { - int dSq = dX * dX + dY * dY + dZ * dZ; + protected int getUpdateDivisor(int dX, int dY, int dZ) { + int dSq = dX * dX + dY * dY + dZ * dZ; - return (dSq / 1024) + 1; - } + return (dSq / 1024) + 1; + } - private void addInternal(TileEntity tile) { - getInstance(tile, true); - } + private void addInternal(TileEntity tile) { + getInstance(tile, true); + } - private void removeInternal(T tile) { - TileEntityInstance instance = getInstance(tile, false); + private void removeInternal(T tile) { + TileEntityInstance instance = getInstance(tile, false); - if (instance != null) { - removeInternal(tile, instance); - } - } + if (instance != null) { + removeInternal(tile, instance); + } + } - private void removeInternal(TileEntity tile, TileEntityInstance instance) { - instance.remove(); - instances.remove(tile); - dynamicInstances.remove(tile); - tickableInstances.remove(tile); - } + private void removeInternal(TileEntity tile, TileEntityInstance instance) { + instance.remove(); + instances.remove(tile); + dynamicInstances.remove(tile); + tickableInstances.remove(tile); + } - private TileEntityInstance createInternal(T tile) { - TileEntityInstance renderer = InstancedTileRenderRegistry.instance.create(this, tile); + private TileEntityInstance createInternal(T tile) { + TileEntityInstance renderer = InstancedTileRenderRegistry.instance.create(this, tile); - if (renderer != null) { - renderer.updateLight(); - instances.put(tile, renderer); + if (renderer != null) { + renderer.updateLight(); + instances.put(tile, renderer); - if (renderer instanceof IDynamicInstance) - dynamicInstances.put(tile, (IDynamicInstance) renderer); + if (renderer instanceof IDynamicInstance) + dynamicInstances.put(tile, (IDynamicInstance) renderer); - if (renderer instanceof ITickableInstance) - tickableInstances.put(tile, ((ITickableInstance) renderer)); - } + if (renderer instanceof ITickableInstance) + tickableInstances.put(tile, ((ITickableInstance) renderer)); + } - return renderer; - } + return renderer; + } - public void invalidate() { - for (RenderMaterial material : materials.values()) { - material.delete(); - } - instances.clear(); - dynamicInstances.clear(); - tickableInstances.clear(); - } + public void invalidate() { + for (RenderMaterial material : materials.values()) { + material.delete(); + } + instances.clear(); + dynamicInstances.clear(); + tickableInstances.clear(); + } - public boolean canCreateInstance(TileEntity tile) { - if (tile.isRemoved()) return false; + public boolean canCreateInstance(TileEntity tile) { + if (tile.isRemoved()) return false; - World world = tile.getWorld(); + World world = tile.getWorld(); - if (world == null) return false; + if (world == null) return false; - if (world.isAirBlock(tile.getPos())) return false; + if (world.isAirBlock(tile.getPos())) return false; - if (world == Minecraft.getInstance().world) { - BlockPos pos = tile.getPos(); + if (world == Minecraft.getInstance().world) { + BlockPos pos = tile.getPos(); - IBlockReader existingChunk = world.getExistingChunk(pos.getX() >> 4, pos.getZ() >> 4); + IBlockReader existingChunk = world.getExistingChunk(pos.getX() >> 4, pos.getZ() >> 4); - return existingChunk != null; - } + return existingChunk != null; + } - return world instanceof IFlywheelWorld && ((IFlywheelWorld) world).supportsFlywheel(); - } + return world instanceof IFlywheelWorld && ((IFlywheelWorld) world).supportsFlywheel(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/ModelFactory.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/ModelFactory.java index 61d7e36ff..2042929a8 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/ModelFactory.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/ModelFactory.java @@ -4,5 +4,5 @@ import net.minecraft.client.renderer.BufferBuilder; @FunctionalInterface public interface ModelFactory> { - B makeModel(InstancedTileRenderer renderer, BufferBuilder buf); + B makeModel(InstancedTileRenderer renderer, BufferBuilder buf); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/RenderMaterial.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/RenderMaterial.java index a56770802..bafe18da4 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/RenderMaterial.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/RenderMaterial.java @@ -1,9 +1,5 @@ package com.simibubi.create.foundation.render.backend.instancing; -import static com.simibubi.create.foundation.render.Compartment.PARTIAL; - -import java.util.HashMap; -import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.function.Predicate; @@ -14,12 +10,12 @@ import org.apache.commons.lang3.tuple.Pair; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.mojang.blaze3d.matrix.MatrixStack; -import com.simibubi.create.AllBlockPartials; -import com.simibubi.create.foundation.render.Compartment; import com.simibubi.create.foundation.render.SuperByteBufferCache; import com.simibubi.create.foundation.render.backend.Backend; import com.simibubi.create.foundation.render.backend.FastRenderDispatcher; +import com.simibubi.create.foundation.render.backend.RenderUtil; import com.simibubi.create.foundation.render.backend.core.BasicProgram; +import com.simibubi.create.foundation.render.backend.core.PartialModel; import com.simibubi.create.foundation.render.backend.gl.shader.ProgramSpec; import com.simibubi.create.foundation.render.backend.gl.shader.ShaderCallback; @@ -34,112 +30,100 @@ import net.minecraft.util.math.vector.Matrix4f; public class RenderMaterial

> { - protected final InstancedTileRenderer renderer; - protected final Map, Cache> models; - protected final ModelFactory factory; - protected final ProgramSpec

programSpec; - protected final Predicate layerPredicate; + protected final InstancedTileRenderer renderer; + protected final Cache models; + protected final ModelFactory factory; + protected final ProgramSpec

programSpec; + protected final Predicate layerPredicate; - /** - * Creates a material that renders in the default layer (CUTOUT_MIPPED) - */ - public RenderMaterial(InstancedTileRenderer renderer, ProgramSpec

programSpec, ModelFactory factory) { - this(renderer, programSpec, factory, type -> type == RenderType.getCutoutMipped()); - } + /** + * Creates a material that renders in the default layer (CUTOUT_MIPPED) + */ + public RenderMaterial(InstancedTileRenderer renderer, ProgramSpec

programSpec, ModelFactory factory) { + this(renderer, programSpec, factory, type -> type == RenderType.getCutoutMipped()); + } - public RenderMaterial(InstancedTileRenderer renderer, ProgramSpec

programSpec, ModelFactory factory, Predicate layerPredicate) { - this.renderer = renderer; - this.models = new HashMap<>(); - this.factory = factory; - this.programSpec = programSpec; - this.layerPredicate = layerPredicate; - registerCompartment(Compartment.PARTIAL); - registerCompartment(Compartment.DIRECTIONAL_PARTIAL); - registerCompartment(Compartment.GENERIC_TILE); - } + public RenderMaterial(InstancedTileRenderer renderer, ProgramSpec

programSpec, ModelFactory factory, Predicate layerPredicate) { + this.renderer = renderer; + this.models = CacheBuilder.newBuilder() + .removalListener(notification -> ((InstancedModel) notification.getValue()).delete()) + .build(); + this.factory = factory; + this.programSpec = programSpec; + this.layerPredicate = layerPredicate; + } - public boolean canRenderInLayer(RenderType layer) { - return layerPredicate.test(layer); - } + public boolean canRenderInLayer(RenderType layer) { + return layerPredicate.test(layer); + } - public void render(RenderType layer, Matrix4f projection, double camX, double camY, double camZ) { - render(layer, projection, camX, camY, camZ, null); - } + public void render(RenderType layer, Matrix4f projection, double camX, double camY, double camZ) { + render(layer, projection, camX, camY, camZ, null); + } - public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ, ShaderCallback

setup) { - P program = Backend.getProgram(programSpec); - program.bind(viewProjection, camX, camY, camZ, FastRenderDispatcher.getDebugMode()); + public void render(RenderType layer, Matrix4f viewProjection, double camX, double camY, double camZ, ShaderCallback

setup) { + P program = Backend.getProgram(programSpec); + program.bind(viewProjection, camX, camY, camZ, FastRenderDispatcher.getDebugMode()); - if (setup != null) setup.call(program); + if (setup != null) setup.call(program); - makeRenderCalls(); - teardown(); - } + makeRenderCalls(); + } - public void teardown() {} + public void delete() { + //runOnAll(InstancedModel::delete); + models.invalidateAll(); + } - public void delete() { - runOnAll(InstancedModel::delete); - models.values().forEach(Cache::invalidateAll); - } + protected void makeRenderCalls() { + runOnAll(InstancedModel::render); + } - protected void makeRenderCalls() { - runOnAll(InstancedModel::render); - } + public void runOnAll(Consumer f) { + for (MODEL model : models.asMap().values()) { + f.accept(model); + } + } - public void runOnAll(Consumer f) { - for (Cache cache : models.values()) { - for (MODEL model : cache.asMap().values()) { - f.accept(model); - } - } - } + public MODEL getModel(PartialModel partial, BlockState referenceState) { + return get(partial, () -> buildModel(partial.get(), referenceState)); + } - public void registerCompartment(Compartment instance) { - models.put(instance, CacheBuilder.newBuilder().build()); - } + public MODEL getModel(PartialModel partial, BlockState referenceState, Direction dir) { + return getModel(partial, referenceState, dir, RenderUtil.rotateToFace(dir)); + } - public MODEL getModel(AllBlockPartials partial, BlockState referenceState) { - return get(PARTIAL, partial, () -> buildModel(partial.get(), referenceState)); - } + public MODEL getModel(PartialModel partial, BlockState referenceState, Direction dir, Supplier modelTransform) { + return get(Pair.of(dir, partial), + () -> buildModel(partial.get(), referenceState, modelTransform.get())); + } - public MODEL getModel(AllBlockPartials partial, BlockState referenceState, Direction dir) { - return get(Compartment.DIRECTIONAL_PARTIAL, Pair.of(dir, partial), - () -> buildModel(partial.get(), referenceState)); - } + public MODEL getModel(BlockState toRender) { + return get(toRender, () -> buildModel(toRender)); + } - public MODEL getModel(AllBlockPartials partial, BlockState referenceState, Direction dir, Supplier modelTransform) { - return get(Compartment.DIRECTIONAL_PARTIAL, Pair.of(dir, partial), - () -> buildModel(partial.get(), referenceState, modelTransform.get())); - } + public MODEL get(Object key, Supplier supplier) { + try { + return models.get(key, supplier::get); + } catch (ExecutionException e) { + e.printStackTrace(); + return null; + } + } - public MODEL getModel(BlockState toRender) { - return get(Compartment.GENERIC_TILE, toRender, () -> buildModel(toRender)); - } + private MODEL buildModel(BlockState renderedState) { + BlockRendererDispatcher dispatcher = Minecraft.getInstance().getBlockRendererDispatcher(); + return buildModel(dispatcher.getModelForState(renderedState), renderedState); + } - public MODEL get(Compartment compartment, T key, Supplier supplier) { - Cache compartmentCache = models.get(compartment); - try { - return compartmentCache.get(key, supplier::get); - } catch (ExecutionException e) { - e.printStackTrace(); - return null; - } - } + private MODEL buildModel(IBakedModel model, BlockState renderedState) { + return buildModel(model, renderedState, new MatrixStack()); + } - private MODEL buildModel(BlockState renderedState) { - BlockRendererDispatcher dispatcher = Minecraft.getInstance().getBlockRendererDispatcher(); - return buildModel(dispatcher.getModelForState(renderedState), renderedState); - } + private MODEL buildModel(IBakedModel model, BlockState referenceState, MatrixStack ms) { + BufferBuilder builder = SuperByteBufferCache.getBufferBuilder(model, referenceState, ms); - private MODEL buildModel(IBakedModel model, BlockState renderedState) { - return buildModel(model, renderedState, new MatrixStack()); - } - - private MODEL buildModel(IBakedModel model, BlockState referenceState, MatrixStack ms) { - BufferBuilder builder = SuperByteBufferCache.getBufferBuilder(model, referenceState, ms); - - return factory.makeModel(renderer, builder); - } + return factory.makeModel(renderer, builder); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/TileEntityInstance.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/TileEntityInstance.java index aece43527..f5f23f31a 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/TileEntityInstance.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/TileEntityInstance.java @@ -32,94 +32,96 @@ import net.minecraft.world.World; */ public abstract class TileEntityInstance implements IInstance { - protected final InstancedTileRenderer renderer; - protected final T tile; - protected final World world; - protected final BlockPos pos; - protected final BlockPos instancePos; - protected final BlockState blockState; + protected final InstancedTileRenderer renderer; + protected final T tile; + protected final World world; + protected final BlockPos pos; + protected final BlockPos instancePos; + protected final BlockState blockState; - public TileEntityInstance(InstancedTileRenderer renderer, T tile) { - this.renderer = renderer; - this.tile = tile; - this.world = tile.getWorld(); - this.pos = tile.getPos(); - this.blockState = tile.getBlockState(); - this.instancePos = pos.subtract(renderer.getOriginCoordinate()); - } + public TileEntityInstance(InstancedTileRenderer renderer, T tile) { + this.renderer = renderer; + this.tile = tile; + this.world = tile.getWorld(); + this.pos = tile.getPos(); + this.blockState = tile.getBlockState(); + this.instancePos = pos.subtract(renderer.getOriginCoordinate()); + } - /** - * Update instance data here. Good for when data doesn't change very often and when animations are GPU based. - * Don't query lighting data here, that's handled separately in {@link #updateLight()}. - * - *

If your animations are complex or more CPU driven, see {@link IDynamicInstance} or {@link ITickableInstance}. - */ - protected void update() { } + /** + * Update instance data here. Good for when data doesn't change very often and when animations are GPU based. + * Don't query lighting data here, that's handled separately in {@link #updateLight()}. + * + *

If your animations are complex or more CPU driven, see {@link IDynamicInstance} or {@link ITickableInstance}. + */ + protected void update() { + } - /** - * Called after construction and when a light update occurs in the world. - * - *
If your model needs it, update light here. - */ - public void updateLight() { } + /** + * Called after construction and when a light update occurs in the world. + * + *
If your model needs it, update light here. + */ + public void updateLight() { + } - /** - * Free any acquired resources. - * - *
eg. call {@link InstanceKey#delete()}. - */ - public abstract void remove(); + /** + * Free any acquired resources. + * + *
eg. call {@link InstanceKey#delete()}. + */ + public abstract void remove(); - /** - * Just before {@link #update()} would be called, shouldReset() is checked. - * If this function returns true, then this instance will be {@link #remove}d, - * and another instance will be constructed to replace it. This allows for more sane resource - * acquisition compared to trying to update everything within the lifetime of an instance. - * - * @return true if this instance should be discarded and refreshed. - */ - public boolean shouldReset() { - return tile.getBlockState() != blockState; - } + /** + * Just before {@link #update()} would be called, shouldReset() is checked. + * If this function returns true, then this instance will be {@link #remove}d, + * and another instance will be constructed to replace it. This allows for more sane resource + * acquisition compared to trying to update everything within the lifetime of an instance. + * + * @return true if this instance should be discarded and refreshed. + */ + public boolean shouldReset() { + return tile.getBlockState() != blockState; + } - /** - * In order to accommodate for floating point precision errors at high coordinates, - * {@link InstancedTileRenderer}s are allowed to arbitrarily adjust the origin, and - * shift the world matrix provided as a shader uniform accordingly. - * - * @return The {@link BlockPos} at which the {@link TileEntity} this instance - * represents should be rendered at to appear in the correct location. - */ - public BlockPos getInstancePosition() { - return instancePos; - } + /** + * In order to accommodate for floating point precision errors at high coordinates, + * {@link InstancedTileRenderer}s are allowed to arbitrarily adjust the origin, and + * shift the world matrix provided as a shader uniform accordingly. + * + * @return The {@link BlockPos} at which the {@link TileEntity} this instance + * represents should be rendered at to appear in the correct location. + */ + public BlockPos getInstancePosition() { + return instancePos; + } - @Override - public BlockPos getWorldPosition() { - return pos; - } + @Override + public BlockPos getWorldPosition() { + return pos; + } - protected void relight(BlockPos pos, IFlatLight... models) { - relight(world.getLightLevel(LightType.BLOCK, pos), world.getLightLevel(LightType.SKY, pos), models); - } + protected void relight(BlockPos pos, IFlatLight... models) { + relight(world.getLightLevel(LightType.BLOCK, pos), world.getLightLevel(LightType.SKY, pos), models); + } - protected > void relight(BlockPos pos, Stream models) { - relight(world.getLightLevel(LightType.BLOCK, pos), world.getLightLevel(LightType.SKY, pos), models); - } + protected > void relight(BlockPos pos, Stream models) { + relight(world.getLightLevel(LightType.BLOCK, pos), world.getLightLevel(LightType.SKY, pos), models); + } - protected void relight(int block, int sky, IFlatLight... models) { - relight(block, sky, Arrays.stream(models)); - } + protected void relight(int block, int sky, IFlatLight... models) { + relight(block, sky, Arrays.stream(models)); + } - protected > void relight(int block, int sky, Stream models) { - models.forEach(model -> model.setBlockLight(block).setSkyLight(sky)); - } + protected > void relight(int block, int sky, Stream models) { + models.forEach(model -> model.setBlockLight(block).setSkyLight(sky)); + } - protected RenderMaterial> getTransformMaterial() { - return renderer.getTransformMaterial(); - } + protected RenderMaterial> getTransformMaterial() { + return renderer.getTransformMaterial(); + } - protected RenderMaterial> getOrientedMaterial() { - return renderer.getOrientedMaterial(); - } + protected RenderMaterial> getOrientedMaterial() { + return renderer.getOrientedMaterial(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/util/InstanceGroup.java b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/util/InstanceGroup.java index f550f4e46..6aa8f0cff 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/instancing/util/InstanceGroup.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/instancing/util/InstanceGroup.java @@ -8,7 +8,7 @@ import java.util.List; import com.simibubi.create.foundation.render.backend.instancing.InstanceData; import com.simibubi.create.foundation.render.backend.instancing.InstancedModel; -public class InstanceGroup extends AbstractCollection { +public class InstanceGroup extends AbstractCollection { final InstancedModel model; final List backing; @@ -30,7 +30,6 @@ public class InstanceGroup extends AbstractCollection } /** - * * @param count * @return True if the number of elements changed. */ diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/CoordinateConsumer.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/CoordinateConsumer.java index 4011c19e0..6f20a8c33 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/CoordinateConsumer.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/CoordinateConsumer.java @@ -2,5 +2,5 @@ package com.simibubi.create.foundation.render.backend.light; @FunctionalInterface public interface CoordinateConsumer { - void consume(int x, int y, int z); + void consume(int x, int y, int z); } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/EmptyLighter.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/EmptyLighter.java index b58653899..a92cf4e27 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/EmptyLighter.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/EmptyLighter.java @@ -5,12 +5,12 @@ import com.simibubi.create.content.contraptions.components.structureMovement.Con // so other contraptions don't crash before they have a lighter public class EmptyLighter extends ContraptionLighter { - public EmptyLighter(Contraption contraption) { - super(contraption); - } + public EmptyLighter(Contraption contraption) { + super(contraption); + } - @Override - public GridAlignedBB getContraptionBounds() { - return new GridAlignedBB(0, 0, 0, 1, 1, 1); - } + @Override + public GridAlignedBB getContraptionBounds() { + return new GridAlignedBB(0, 0, 0, 1, 1, 1); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/GridAlignedBB.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/GridAlignedBB.java index b8d499010..3703143f5 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/GridAlignedBB.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/GridAlignedBB.java @@ -11,313 +11,313 @@ import net.minecraft.util.math.SectionPos; import net.minecraft.util.math.vector.Vector3i; public class GridAlignedBB { - public int minX; - public int minY; - public int minZ; - public int maxX; - public int maxY; - public int maxZ; + public int minX; + public int minY; + public int minZ; + public int maxX; + public int maxY; + public int maxZ; - public GridAlignedBB(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } + public GridAlignedBB(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + } - public static GridAlignedBB ofRadius(int radius) { - return new GridAlignedBB(-radius, -radius, -radius, radius + 1, radius + 1, radius + 1); - } + public static GridAlignedBB ofRadius(int radius) { + return new GridAlignedBB(-radius, -radius, -radius, radius + 1, radius + 1, radius + 1); + } - public static GridAlignedBB copy(GridAlignedBB bb) { - return new GridAlignedBB(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - } + public static GridAlignedBB copy(GridAlignedBB bb) { + return new GridAlignedBB(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + } - public static GridAlignedBB from(AxisAlignedBB aabb) { - int minX = (int) Math.floor(aabb.minX); - int minY = (int) Math.floor(aabb.minY); - int minZ = (int) Math.floor(aabb.minZ); - int maxX = (int) Math.ceil(aabb.maxX); - int maxY = (int) Math.ceil(aabb.maxY); - int maxZ = (int) Math.ceil(aabb.maxZ); - return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); - } + public static GridAlignedBB from(AxisAlignedBB aabb) { + int minX = (int) Math.floor(aabb.minX); + int minY = (int) Math.floor(aabb.minY); + int minZ = (int) Math.floor(aabb.minZ); + int maxX = (int) Math.ceil(aabb.maxX); + int maxY = (int) Math.ceil(aabb.maxY); + int maxZ = (int) Math.ceil(aabb.maxZ); + return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + } - public static GridAlignedBB from(SectionPos pos) { - return new GridAlignedBB(pos.getWorldStartX(), - pos.getWorldStartY(), - pos.getWorldStartZ(), - pos.getWorldEndX() + 1, - pos.getWorldEndY() + 1, - pos.getWorldEndZ() + 1); - } + public static GridAlignedBB from(SectionPos pos) { + return new GridAlignedBB(pos.getWorldStartX(), + pos.getWorldStartY(), + pos.getWorldStartZ(), + pos.getWorldEndX() + 1, + pos.getWorldEndY() + 1, + pos.getWorldEndZ() + 1); + } - public static GridAlignedBB from(BlockPos start, BlockPos end) { - return new GridAlignedBB(start.getX(), - start.getY(), - start.getZ(), - end.getX() + 1, - end.getY() + 1, - end.getZ() + 1); - } + public static GridAlignedBB from(BlockPos start, BlockPos end) { + return new GridAlignedBB(start.getX(), + start.getY(), + start.getZ(), + end.getX() + 1, + end.getY() + 1, + end.getZ() + 1); + } - public static GridAlignedBB from(int sectionX, int sectionZ) { - int startX = sectionX << 4; - int startZ = sectionZ << 4; - return new GridAlignedBB(startX, - 0, - startZ, - startX + 16, - 256, - startZ + 16); - } + public static GridAlignedBB from(int sectionX, int sectionZ) { + int startX = sectionX << 4; + int startZ = sectionZ << 4; + return new GridAlignedBB(startX, + 0, + startZ, + startX + 16, + 256, + startZ + 16); + } - public static AxisAlignedBB toAABB(GridAlignedBB bb) { - return new AxisAlignedBB(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - } + public static AxisAlignedBB toAABB(GridAlignedBB bb) { + return new AxisAlignedBB(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + } - public GridAlignedBB copy() { - return copy(this); - } + public GridAlignedBB copy() { + return copy(this); + } - public boolean sameAs(GridAlignedBB other) { - return minX == other.minX && - minY == other.minY && - minZ == other.minZ && - maxX == other.maxX && - maxY == other.maxY && - maxZ == other.maxZ; - } + public boolean sameAs(GridAlignedBB other) { + return minX == other.minX && + minY == other.minY && + minZ == other.minZ && + maxX == other.maxX && + maxY == other.maxY && + maxZ == other.maxZ; + } - public void fixMinMax() { - int minX = Math.min(this.minX, this.maxX); - int minY = Math.min(this.minY, this.maxY); - int minZ = Math.min(this.minZ, this.maxZ); - int maxX = Math.max(this.minX, this.maxX); - int maxY = Math.max(this.minY, this.maxY); - int maxZ = Math.max(this.minZ, this.maxZ); + public void fixMinMax() { + int minX = Math.min(this.minX, this.maxX); + int minY = Math.min(this.minY, this.maxY); + int minZ = Math.min(this.minZ, this.maxZ); + int maxX = Math.max(this.minX, this.maxX); + int maxY = Math.max(this.minY, this.maxY); + int maxZ = Math.max(this.minZ, this.maxZ); - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + } - public int sizeX() { - return maxX - minX; - } + public int sizeX() { + return maxX - minX; + } - public int sizeY() { - return maxY - minY; - } + public int sizeY() { + return maxY - minY; + } - public int sizeZ() { - return maxZ - minZ; - } + public int sizeZ() { + return maxZ - minZ; + } - public int volume() { - return sizeX() * sizeY() * sizeZ(); - } + public int volume() { + return sizeX() * sizeY() * sizeZ(); + } - public boolean empty() { - // if any dimension has side length 0 this box contains no volume - return minX == maxX || - minY == maxY || - minZ == maxZ; - } + public boolean empty() { + // if any dimension has side length 0 this box contains no volume + return minX == maxX || + minY == maxY || + minZ == maxZ; + } - public void translate(Vector3i by) { - translate(by.getX(), by.getY(), by.getZ()); - } + public void translate(Vector3i by) { + translate(by.getX(), by.getY(), by.getZ()); + } - public void translate(int x, int y, int z) { - minX += x; - maxX += x; - minY += y; - maxY += y; - minZ += z; - maxZ += z; - } + public void translate(int x, int y, int z) { + minX += x; + maxX += x; + minY += y; + maxY += y; + minZ += z; + maxZ += z; + } - public void mirrorAbout(Direction.Axis axis) { - Vector3i axisVec = Direction.getFacingFromAxis(Direction.AxisDirection.POSITIVE, axis).getDirectionVec(); - int flipX = axisVec.getX() - 1; - int flipY = axisVec.getY() - 1; - int flipZ = axisVec.getZ() - 1; + public void mirrorAbout(Direction.Axis axis) { + Vector3i axisVec = Direction.getFacingFromAxis(Direction.AxisDirection.POSITIVE, axis).getDirectionVec(); + int flipX = axisVec.getX() - 1; + int flipY = axisVec.getY() - 1; + int flipZ = axisVec.getZ() - 1; - int maxX = this.maxX * flipX; - int maxY = this.maxY * flipY; - int maxZ = this.maxZ * flipZ; - this.maxX = this.minX * flipX; - this.maxY = this.minY * flipY; - this.maxZ = this.minZ * flipZ; - this.minX = maxX; - this.minY = maxY; - this.minZ = maxZ; - } + int maxX = this.maxX * flipX; + int maxY = this.maxY * flipY; + int maxZ = this.maxZ * flipZ; + this.maxX = this.minX * flipX; + this.maxY = this.minY * flipY; + this.maxZ = this.minZ * flipZ; + this.minX = maxX; + this.minY = maxY; + this.minZ = maxZ; + } - /** - * Grow this bounding box to have power of 2 side length, scaling from the center. - */ - public void nextPowerOf2Centered() { - int sizeX = sizeX(); - int sizeY = sizeY(); - int sizeZ = sizeZ(); + /** + * Grow this bounding box to have power of 2 side length, scaling from the center. + */ + public void nextPowerOf2Centered() { + int sizeX = sizeX(); + int sizeY = sizeY(); + int sizeZ = sizeZ(); - int newSizeX = RenderUtil.nextPowerOf2(sizeX); - int newSizeY = RenderUtil.nextPowerOf2(sizeY); - int newSizeZ = RenderUtil.nextPowerOf2(sizeZ); + int newSizeX = RenderUtil.nextPowerOf2(sizeX); + int newSizeY = RenderUtil.nextPowerOf2(sizeY); + int newSizeZ = RenderUtil.nextPowerOf2(sizeZ); - int diffX = newSizeX - sizeX; - int diffY = newSizeY - sizeY; - int diffZ = newSizeZ - sizeZ; + int diffX = newSizeX - sizeX; + int diffY = newSizeY - sizeY; + int diffZ = newSizeZ - sizeZ; - minX -= diffX / 2; // floor division for the minimums - minY -= diffY / 2; - minZ -= diffZ / 2; - maxX += (diffX + 1) / 2; // ceiling divison for the maximums - maxY += (diffY + 1) / 2; - maxZ += (diffZ + 1) / 2; - } + minX -= diffX / 2; // floor division for the minimums + minY -= diffY / 2; + minZ -= diffZ / 2; + maxX += (diffX + 1) / 2; // ceiling divison for the maximums + maxY += (diffY + 1) / 2; + maxZ += (diffZ + 1) / 2; + } - /** - * Grow this bounding box to have power of 2 side lengths, scaling from the minimum coords. - */ - public void nextPowerOf2() { - int sizeX = RenderUtil.nextPowerOf2(sizeX()); - int sizeY = RenderUtil.nextPowerOf2(sizeY()); - int sizeZ = RenderUtil.nextPowerOf2(sizeZ()); + /** + * Grow this bounding box to have power of 2 side lengths, scaling from the minimum coords. + */ + public void nextPowerOf2() { + int sizeX = RenderUtil.nextPowerOf2(sizeX()); + int sizeY = RenderUtil.nextPowerOf2(sizeY()); + int sizeZ = RenderUtil.nextPowerOf2(sizeZ()); - this.maxX = this.minX + sizeX; - this.maxY = this.minY + sizeY; - this.maxZ = this.minZ + sizeZ; - } + this.maxX = this.minX + sizeX; + this.maxY = this.minY + sizeY; + this.maxZ = this.minZ + sizeZ; + } - public boolean hasPowerOf2Sides() { - // this is only true if all individual side lengths are powers of 2 - return isPowerOf2(volume()); - } + public boolean hasPowerOf2Sides() { + // this is only true if all individual side lengths are powers of 2 + return isPowerOf2(volume()); + } - public void grow(int s) { - this.grow(s, s, s); - } + public void grow(int s) { + this.grow(s, s, s); + } - public void grow(int x, int y, int z) { - minX -= x; - minY -= y; - minZ -= z; - maxX += x; - maxY += y; - maxZ += z; - } + public void grow(int x, int y, int z) { + minX -= x; + minY -= y; + minZ -= z; + maxX += x; + maxY += y; + maxZ += z; + } - public GridAlignedBB intersect(GridAlignedBB other) { - int minX = Math.max(this.minX, other.minX); - int minY = Math.max(this.minY, other.minY); - int minZ = Math.max(this.minZ, other.minZ); - int maxX = Math.min(this.maxX, other.maxX); - int maxY = Math.min(this.maxY, other.maxY); - int maxZ = Math.min(this.maxZ, other.maxZ); - return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); - } + public GridAlignedBB intersect(GridAlignedBB other) { + int minX = Math.max(this.minX, other.minX); + int minY = Math.max(this.minY, other.minY); + int minZ = Math.max(this.minZ, other.minZ); + int maxX = Math.min(this.maxX, other.maxX); + int maxY = Math.min(this.maxY, other.maxY); + int maxZ = Math.min(this.maxZ, other.maxZ); + return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + } - public void intersectAssign(GridAlignedBB other) { - this.minX = Math.max(this.minX, other.minX); - this.minY = Math.max(this.minY, other.minY); - this.minZ = Math.max(this.minZ, other.minZ); - this.maxX = Math.min(this.maxX, other.maxX); - this.maxY = Math.min(this.maxY, other.maxY); - this.maxZ = Math.min(this.maxZ, other.maxZ); - } + public void intersectAssign(GridAlignedBB other) { + this.minX = Math.max(this.minX, other.minX); + this.minY = Math.max(this.minY, other.minY); + this.minZ = Math.max(this.minZ, other.minZ); + this.maxX = Math.min(this.maxX, other.maxX); + this.maxY = Math.min(this.maxY, other.maxY); + this.maxZ = Math.min(this.maxZ, other.maxZ); + } - public GridAlignedBB union(GridAlignedBB other) { - int minX = Math.min(this.minX, other.minX); - int minY = Math.min(this.minY, other.minY); - int minZ = Math.min(this.minZ, other.minZ); - int maxX = Math.max(this.maxX, other.maxX); - int maxY = Math.max(this.maxY, other.maxY); - int maxZ = Math.max(this.maxZ, other.maxZ); - return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); - } + public GridAlignedBB union(GridAlignedBB other) { + int minX = Math.min(this.minX, other.minX); + int minY = Math.min(this.minY, other.minY); + int minZ = Math.min(this.minZ, other.minZ); + int maxX = Math.max(this.maxX, other.maxX); + int maxY = Math.max(this.maxY, other.maxY); + int maxZ = Math.max(this.maxZ, other.maxZ); + return new GridAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); + } - public void unionAssign(GridAlignedBB other) { - this.minX = Math.min(this.minX, other.minX); - this.minY = Math.min(this.minY, other.minY); - this.minZ = Math.min(this.minZ, other.minZ); - this.maxX = Math.max(this.maxX, other.maxX); - this.maxY = Math.max(this.maxY, other.maxY); - this.maxZ = Math.max(this.maxZ, other.maxZ); - } + public void unionAssign(GridAlignedBB other) { + this.minX = Math.min(this.minX, other.minX); + this.minY = Math.min(this.minY, other.minY); + this.minZ = Math.min(this.minZ, other.minZ); + this.maxX = Math.max(this.maxX, other.maxX); + this.maxY = Math.max(this.maxY, other.maxY); + this.maxZ = Math.max(this.maxZ, other.maxZ); + } - public void unionAssign(AxisAlignedBB other) { - this.minX = Math.min(this.minX, (int) Math.floor(other.minX)); - this.minY = Math.min(this.minY, (int) Math.floor(other.minY)); - this.minZ = Math.min(this.minZ, (int) Math.floor(other.minZ)); - this.maxX = Math.max(this.maxX, (int) Math.ceil(other.maxX)); - this.maxY = Math.max(this.maxY, (int) Math.ceil(other.maxY)); - this.maxZ = Math.max(this.maxZ, (int) Math.ceil(other.maxZ)); - } + public void unionAssign(AxisAlignedBB other) { + this.minX = Math.min(this.minX, (int) Math.floor(other.minX)); + this.minY = Math.min(this.minY, (int) Math.floor(other.minY)); + this.minZ = Math.min(this.minZ, (int) Math.floor(other.minZ)); + this.maxX = Math.max(this.maxX, (int) Math.ceil(other.maxX)); + this.maxY = Math.max(this.maxY, (int) Math.ceil(other.maxY)); + this.maxZ = Math.max(this.maxZ, (int) Math.ceil(other.maxZ)); + } - public boolean intersects(GridAlignedBB other) { - return this.intersects(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ); - } + public boolean intersects(GridAlignedBB other) { + return this.intersects(other.minX, other.minY, other.minZ, other.maxX, other.maxY, other.maxZ); + } - public boolean contains(GridAlignedBB other) { - return other.minX >= this.minX && - other.maxX <= this.maxX && - other.minY >= this.minY && - other.maxY <= this.maxY && - other.minZ >= this.minZ && - other.maxZ <= this.maxZ; - } + public boolean contains(GridAlignedBB other) { + return other.minX >= this.minX && + other.maxX <= this.maxX && + other.minY >= this.minY && + other.maxY <= this.maxY && + other.minZ >= this.minZ && + other.maxZ <= this.maxZ; + } - public boolean isContainedBy(GridAlignedBB other) { - return other.contains(this); - } + public boolean isContainedBy(GridAlignedBB other) { + return other.contains(this); + } - public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - return this.minX < maxX && this.maxX > minX && this.minY < maxY && this.maxY > minY && this.minZ < maxZ && this.maxZ > minZ; - } + public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return this.minX < maxX && this.maxX > minX && this.minY < maxY && this.maxY > minY && this.minZ < maxZ && this.maxZ > minZ; + } - public void forEachContained(CoordinateConsumer func) { - if (empty()) return; + public void forEachContained(CoordinateConsumer func) { + if (empty()) return; - for (int x = minX; x < maxX; x++) { - for (int y = Math.max(minY, 0); y < Math.min(maxY, 255); y++) { // clamp to world height limits - for (int z = minZ; z < maxZ; z++) { - func.consume(x, y, z); - } - } - } - } + for (int x = minX; x < maxX; x++) { + for (int y = Math.max(minY, 0); y < Math.min(maxY, 255); y++) { // clamp to world height limits + for (int z = minZ; z < maxZ; z++) { + func.consume(x, y, z); + } + } + } + } - public AxisAlignedBB toAABB() { - return toAABB(this); - } + public AxisAlignedBB toAABB() { + return toAABB(this); + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - GridAlignedBB that = (GridAlignedBB) o; + GridAlignedBB that = (GridAlignedBB) o; - return this.sameAs(that); - } + return this.sameAs(that); + } - @Override - public int hashCode() { - int result = minX; - result = 31 * result + minY; - result = 31 * result + minZ; - result = 31 * result + maxX; - result = 31 * result + maxY; - result = 31 * result + maxZ; - return result; - } + @Override + public int hashCode() { + int result = minX; + result = 31 * result + minY; + result = 31 * result + minZ; + result = 31 * result + maxX; + result = 31 * result + maxY; + result = 31 * result + maxZ; + return result; + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightUpdater.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightUpdater.java index dd63bef83..089376a23 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightUpdater.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightUpdater.java @@ -49,11 +49,11 @@ public class LightUpdater { /** * Add a listener associated with the given {@link BlockPos}. - * + *

* When a light update occurs in the chunk the position is contained in, * {@link LightUpdateListener#onLightUpdate} will be called. * - * @param pos The position in the world that the listener cares about. + * @param pos The position in the world that the listener cares about. * @param listener The object that wants to receive light update notifications. */ public void startListening(BlockPos pos, LightUpdateListener listener) { @@ -71,11 +71,11 @@ public class LightUpdater { /** * Add a listener associated with the given {@link GridAlignedBB}. - * + *

* When a light update occurs in any chunk spanning the given volume, * {@link LightUpdateListener#onLightUpdate} will be called. * - * @param volume The volume in the world that the listener cares about. + * @param volume The volume in the world that the listener cares about. * @param listener The object that wants to receive light update notifications. */ public void startListening(GridAlignedBB volume, LightUpdateListener listener) { @@ -106,8 +106,8 @@ public class LightUpdater { /** * Dispatch light updates to all registered {@link LightUpdateListener}s. * - * @param world The world in which light was updated. - * @param type The type of light that changed. + * @param world The world in which light was updated. + * @param type The type of light that changed. * @param sectionPos A long representing the section position where light changed. */ public void onLightUpdate(IBlockDisplayReader world, LightType type, long sectionPos) { diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolume.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolume.java index e201550f7..ae0bdaa23 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolume.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolume.java @@ -19,291 +19,294 @@ import net.minecraft.world.LightType; public class LightVolume { - private GridAlignedBB sampleVolume; - private GridAlignedBB textureVolume; - private ByteBuffer lightData; - - private boolean bufferDirty; - private boolean removed; - - private final GlTexture glTexture; - - private final RGPixelFormat pixelFormat; - - public LightVolume(GridAlignedBB sampleVolume) { - setSampleVolume(sampleVolume); - - pixelFormat = Backend.compat.pixelFormat; - - this.glTexture = new GlTexture(GL20.GL_TEXTURE_3D); - this.lightData = MemoryUtil.memAlloc(this.textureVolume.volume() * pixelFormat.byteCount()); - - // allocate space for the texture - GL20.glActiveTexture(GL20.GL_TEXTURE4); - glTexture.bind(); - - int sizeX = textureVolume.sizeX(); - int sizeY = textureVolume.sizeY(); - int sizeZ = textureVolume.sizeZ(); - GL12.glTexImage3D(GL12.GL_TEXTURE_3D, 0, pixelFormat.internalFormat(), sizeX, sizeY, sizeZ, 0, pixelFormat.format(), GL20.GL_UNSIGNED_BYTE, 0); - - glTexture.unbind(); - GL20.glActiveTexture(GL20.GL_TEXTURE0); - } - - private void setSampleVolume(GridAlignedBB sampleVolume) { - this.sampleVolume = sampleVolume; - this.textureVolume = sampleVolume.copy(); - this.textureVolume.nextPowerOf2Centered(); - } - - public GridAlignedBB getTextureVolume() { - return GridAlignedBB.copy(textureVolume); - } - - public GridAlignedBB getSampleVolume() { - return GridAlignedBB.copy(sampleVolume); - } - - public int getMinX() { - return textureVolume.minX; - } - - public int getMinY() { - return textureVolume.minY; - } - - public int getMinZ() { - return textureVolume.minZ; - } - - public int getMaxX() { - return textureVolume.maxX; - } - - public int getMaxY() { - return textureVolume.maxY; - } - - public int getMaxZ() { - return textureVolume.maxZ; - } - - public int getSizeX() { - return textureVolume.sizeX(); - } - - public int getSizeY() { - return textureVolume.sizeY(); - } - - public int getSizeZ() { - return textureVolume.sizeZ(); - } - - public void move(IBlockDisplayReader world, GridAlignedBB newSampleVolume) { - if (textureVolume.contains(newSampleVolume)) { - if (newSampleVolume.intersects(sampleVolume)) { - GridAlignedBB newArea = newSampleVolume.intersect(sampleVolume); - sampleVolume = newSampleVolume; - - copyLight(world, newArea); - } else { - sampleVolume = newSampleVolume; - initialize(world); - } - } else { - setSampleVolume(newSampleVolume); - int volume = textureVolume.volume(); - if (volume * 2 > lightData.capacity()) { - lightData = MemoryUtil.memRealloc(lightData, volume * 2); - } - initialize(world); - } - } - - public void notifyLightUpdate(IBlockDisplayReader world, LightType type, GridAlignedBB changedVolume) { - if (removed) - return; - - if (!changedVolume.intersects(sampleVolume)) - return; - changedVolume = changedVolume.intersect(sampleVolume); // compute the region contained by us that has dirty lighting data. - - if (type == LightType.BLOCK) copyBlock(world, changedVolume); - else if (type == LightType.SKY) copySky(world, changedVolume); - } - - public void notifyLightPacket(IBlockDisplayReader world, int chunkX, int chunkZ) { - if (removed) return; - - GridAlignedBB changedVolume = GridAlignedBB.from(chunkX, chunkZ); - if (!changedVolume.intersects(sampleVolume)) - return; - changedVolume.intersectAssign(sampleVolume); // compute the region contained by us that has dirty lighting data. - - copyLight(world, changedVolume); - } - - /** - * Completely (re)populate this volume with block and sky lighting data. - * This is expensive and should be avoided. - */ - public void initialize(IBlockDisplayReader world) { - BlockPos.Mutable pos = new BlockPos.Mutable(); - - int shiftX = textureVolume.minX; - int shiftY = textureVolume.minY; - int shiftZ = textureVolume.minZ; - - sampleVolume.forEachContained((x, y, z) -> { - pos.setPos(x, y, z); - - int blockLight = world.getLightLevel(LightType.BLOCK, pos); - int skyLight = world.getLightLevel(LightType.SKY, pos); - - writeLight(x - shiftX, y - shiftY, z - shiftZ, blockLight, skyLight); - }); - - bufferDirty = true; - } - - /** - * Copy block light from the world into this volume. - * @param worldVolume the region in the world to copy data from. - */ - public void copyBlock(IBlockDisplayReader world, GridAlignedBB worldVolume) { - BlockPos.Mutable pos = new BlockPos.Mutable(); - - int xShift = textureVolume.minX; - int yShift = textureVolume.minY; - int zShift = textureVolume.minZ; - - worldVolume.forEachContained((x, y, z) -> { - pos.setPos(x, y, z); - - int light = world.getLightLevel(LightType.BLOCK, pos); - - writeBlock(x - xShift, y - yShift, z - zShift, light); - }); - - bufferDirty = true; - } - - /** - * Copy sky light from the world into this volume. - * @param worldVolume the region in the world to copy data from. - */ - public void copySky(IBlockDisplayReader world, GridAlignedBB worldVolume) { - BlockPos.Mutable pos = new BlockPos.Mutable(); - - int xShift = textureVolume.minX; - int yShift = textureVolume.minY; - int zShift = textureVolume.minZ; - - worldVolume.forEachContained((x, y, z) -> { - pos.setPos(x, y, z); - - int light = world.getLightLevel(LightType.SKY, pos); - - writeSky(x - xShift, y - yShift, z - zShift, light); - }); - - bufferDirty = true; - } - - /** - * Copy all light from the world into this volume. - * @param worldVolume the region in the world to copy data from. - */ - public void copyLight(IBlockDisplayReader world, GridAlignedBB worldVolume) { - BlockPos.Mutable pos = new BlockPos.Mutable(); - - int xShift = textureVolume.minX; - int yShift = textureVolume.minY; - int zShift = textureVolume.minZ; - - worldVolume.forEachContained((x, y, z) -> { - pos.setPos(x, y, z); - - int block = world.getLightLevel(LightType.BLOCK, pos); - int sky = world.getLightLevel(LightType.SKY, pos); - - writeLight(x - xShift, y - yShift, z - zShift, block, sky); - }); - - bufferDirty = true; - } - - public void bind() { - // just in case something goes wrong or we accidentally call this before this volume is properly disposed of. - if (lightData == null || removed) return; - - GL13.glActiveTexture(GL20.GL_TEXTURE4); - glTexture.bind(); - GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_MIN_FILTER, GL13.GL_LINEAR); - GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_MAG_FILTER, GL13.GL_LINEAR); - GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_S, GL20.GL_MIRRORED_REPEAT); - GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_R, GL20.GL_MIRRORED_REPEAT); - GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_T, GL20.GL_MIRRORED_REPEAT); - - uploadTexture(); - } - - private void uploadTexture() { - if (bufferDirty) { - GL20.glPixelStorei(GL20.GL_UNPACK_ROW_LENGTH, 0); - GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_PIXELS, 0); - GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_ROWS, 0); - GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_IMAGES, 0); - GL20.glPixelStorei(GL20.GL_UNPACK_IMAGE_HEIGHT, 0); - GL20.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, 2); - int sizeX = textureVolume.sizeX(); - int sizeY = textureVolume.sizeY(); - int sizeZ = textureVolume.sizeZ(); - - GL12.glTexSubImage3D(GL12.GL_TEXTURE_3D, 0, 0, 0, 0, sizeX, sizeY, sizeZ, pixelFormat.format(), GL20.GL_UNSIGNED_BYTE, lightData); - - GL20.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, 4); // 4 is the default - bufferDirty = false; - } - } - - public void unbind() { - glTexture.unbind(); - } - - public void delete() { - removed = true; - RenderWork.enqueue(() -> { - glTexture.delete(); - MemoryUtil.memFree(lightData); - lightData = null; - }); - } - - private void writeLight(int x, int y, int z, int block, int sky) { - byte b = (byte) ((block & 0xF) << 4); - byte s = (byte) ((sky & 0xF) << 4); - - int i = posToIndex(x, y, z); - lightData.put(i, b); - lightData.put(i + 1, s); - } - - private void writeBlock(int x, int y, int z, int block) { - byte b = (byte) ((block & 0xF) << 4); - - lightData.put(posToIndex(x, y, z), b); - } - - private void writeSky(int x, int y, int z, int sky) { - byte b = (byte) ((sky & 0xF) << 4); - - lightData.put(posToIndex(x, y, z) + 1, b); - } - - private int posToIndex(int x, int y, int z) { - return (x + textureVolume.sizeX() * (y + z * textureVolume.sizeY())) * pixelFormat.byteCount(); - } + private GridAlignedBB sampleVolume; + private GridAlignedBB textureVolume; + private ByteBuffer lightData; + + private boolean bufferDirty; + private boolean removed; + + private final GlTexture glTexture; + + private final RGPixelFormat pixelFormat; + + public LightVolume(GridAlignedBB sampleVolume) { + setSampleVolume(sampleVolume); + + pixelFormat = Backend.compat.pixelFormat; + + this.glTexture = new GlTexture(GL20.GL_TEXTURE_3D); + this.lightData = MemoryUtil.memAlloc(this.textureVolume.volume() * pixelFormat.byteCount()); + + // allocate space for the texture + GL20.glActiveTexture(GL20.GL_TEXTURE4); + glTexture.bind(); + + int sizeX = textureVolume.sizeX(); + int sizeY = textureVolume.sizeY(); + int sizeZ = textureVolume.sizeZ(); + GL12.glTexImage3D(GL12.GL_TEXTURE_3D, 0, pixelFormat.internalFormat(), sizeX, sizeY, sizeZ, 0, pixelFormat.format(), GL20.GL_UNSIGNED_BYTE, 0); + + glTexture.unbind(); + GL20.glActiveTexture(GL20.GL_TEXTURE0); + } + + private void setSampleVolume(GridAlignedBB sampleVolume) { + this.sampleVolume = sampleVolume; + this.textureVolume = sampleVolume.copy(); + this.textureVolume.nextPowerOf2Centered(); + } + + public GridAlignedBB getTextureVolume() { + return GridAlignedBB.copy(textureVolume); + } + + public GridAlignedBB getSampleVolume() { + return GridAlignedBB.copy(sampleVolume); + } + + public int getMinX() { + return textureVolume.minX; + } + + public int getMinY() { + return textureVolume.minY; + } + + public int getMinZ() { + return textureVolume.minZ; + } + + public int getMaxX() { + return textureVolume.maxX; + } + + public int getMaxY() { + return textureVolume.maxY; + } + + public int getMaxZ() { + return textureVolume.maxZ; + } + + public int getSizeX() { + return textureVolume.sizeX(); + } + + public int getSizeY() { + return textureVolume.sizeY(); + } + + public int getSizeZ() { + return textureVolume.sizeZ(); + } + + public void move(IBlockDisplayReader world, GridAlignedBB newSampleVolume) { + if (textureVolume.contains(newSampleVolume)) { + if (newSampleVolume.intersects(sampleVolume)) { + GridAlignedBB newArea = newSampleVolume.intersect(sampleVolume); + sampleVolume = newSampleVolume; + + copyLight(world, newArea); + } else { + sampleVolume = newSampleVolume; + initialize(world); + } + } else { + setSampleVolume(newSampleVolume); + int volume = textureVolume.volume(); + if (volume * 2 > lightData.capacity()) { + lightData = MemoryUtil.memRealloc(lightData, volume * 2); + } + initialize(world); + } + } + + public void notifyLightUpdate(IBlockDisplayReader world, LightType type, GridAlignedBB changedVolume) { + if (removed) + return; + + if (!changedVolume.intersects(sampleVolume)) + return; + changedVolume = changedVolume.intersect(sampleVolume); // compute the region contained by us that has dirty lighting data. + + if (type == LightType.BLOCK) copyBlock(world, changedVolume); + else if (type == LightType.SKY) copySky(world, changedVolume); + } + + public void notifyLightPacket(IBlockDisplayReader world, int chunkX, int chunkZ) { + if (removed) return; + + GridAlignedBB changedVolume = GridAlignedBB.from(chunkX, chunkZ); + if (!changedVolume.intersects(sampleVolume)) + return; + changedVolume.intersectAssign(sampleVolume); // compute the region contained by us that has dirty lighting data. + + copyLight(world, changedVolume); + } + + /** + * Completely (re)populate this volume with block and sky lighting data. + * This is expensive and should be avoided. + */ + public void initialize(IBlockDisplayReader world) { + BlockPos.Mutable pos = new BlockPos.Mutable(); + + int shiftX = textureVolume.minX; + int shiftY = textureVolume.minY; + int shiftZ = textureVolume.minZ; + + sampleVolume.forEachContained((x, y, z) -> { + pos.setPos(x, y, z); + + int blockLight = world.getLightLevel(LightType.BLOCK, pos); + int skyLight = world.getLightLevel(LightType.SKY, pos); + + writeLight(x - shiftX, y - shiftY, z - shiftZ, blockLight, skyLight); + }); + + bufferDirty = true; + } + + /** + * Copy block light from the world into this volume. + * + * @param worldVolume the region in the world to copy data from. + */ + public void copyBlock(IBlockDisplayReader world, GridAlignedBB worldVolume) { + BlockPos.Mutable pos = new BlockPos.Mutable(); + + int xShift = textureVolume.minX; + int yShift = textureVolume.minY; + int zShift = textureVolume.minZ; + + worldVolume.forEachContained((x, y, z) -> { + pos.setPos(x, y, z); + + int light = world.getLightLevel(LightType.BLOCK, pos); + + writeBlock(x - xShift, y - yShift, z - zShift, light); + }); + + bufferDirty = true; + } + + /** + * Copy sky light from the world into this volume. + * + * @param worldVolume the region in the world to copy data from. + */ + public void copySky(IBlockDisplayReader world, GridAlignedBB worldVolume) { + BlockPos.Mutable pos = new BlockPos.Mutable(); + + int xShift = textureVolume.minX; + int yShift = textureVolume.minY; + int zShift = textureVolume.minZ; + + worldVolume.forEachContained((x, y, z) -> { + pos.setPos(x, y, z); + + int light = world.getLightLevel(LightType.SKY, pos); + + writeSky(x - xShift, y - yShift, z - zShift, light); + }); + + bufferDirty = true; + } + + /** + * Copy all light from the world into this volume. + * + * @param worldVolume the region in the world to copy data from. + */ + public void copyLight(IBlockDisplayReader world, GridAlignedBB worldVolume) { + BlockPos.Mutable pos = new BlockPos.Mutable(); + + int xShift = textureVolume.minX; + int yShift = textureVolume.minY; + int zShift = textureVolume.minZ; + + worldVolume.forEachContained((x, y, z) -> { + pos.setPos(x, y, z); + + int block = world.getLightLevel(LightType.BLOCK, pos); + int sky = world.getLightLevel(LightType.SKY, pos); + + writeLight(x - xShift, y - yShift, z - zShift, block, sky); + }); + + bufferDirty = true; + } + + public void bind() { + // just in case something goes wrong or we accidentally call this before this volume is properly disposed of. + if (lightData == null || removed) return; + + GL13.glActiveTexture(GL20.GL_TEXTURE4); + glTexture.bind(); + GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_MIN_FILTER, GL13.GL_LINEAR); + GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_MAG_FILTER, GL13.GL_LINEAR); + GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_S, GL20.GL_MIRRORED_REPEAT); + GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_R, GL20.GL_MIRRORED_REPEAT); + GL11.glTexParameteri(GL13.GL_TEXTURE_3D, GL13.GL_TEXTURE_WRAP_T, GL20.GL_MIRRORED_REPEAT); + + uploadTexture(); + } + + private void uploadTexture() { + if (bufferDirty) { + GL20.glPixelStorei(GL20.GL_UNPACK_ROW_LENGTH, 0); + GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_PIXELS, 0); + GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_ROWS, 0); + GL20.glPixelStorei(GL20.GL_UNPACK_SKIP_IMAGES, 0); + GL20.glPixelStorei(GL20.GL_UNPACK_IMAGE_HEIGHT, 0); + GL20.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, 2); + int sizeX = textureVolume.sizeX(); + int sizeY = textureVolume.sizeY(); + int sizeZ = textureVolume.sizeZ(); + + GL12.glTexSubImage3D(GL12.GL_TEXTURE_3D, 0, 0, 0, 0, sizeX, sizeY, sizeZ, pixelFormat.format(), GL20.GL_UNSIGNED_BYTE, lightData); + + GL20.glPixelStorei(GL20.GL_UNPACK_ALIGNMENT, 4); // 4 is the default + bufferDirty = false; + } + } + + public void unbind() { + glTexture.unbind(); + } + + public void delete() { + removed = true; + RenderWork.enqueue(() -> { + glTexture.delete(); + MemoryUtil.memFree(lightData); + lightData = null; + }); + } + + private void writeLight(int x, int y, int z, int block, int sky) { + byte b = (byte) ((block & 0xF) << 4); + byte s = (byte) ((sky & 0xF) << 4); + + int i = posToIndex(x, y, z); + lightData.put(i, b); + lightData.put(i + 1, s); + } + + private void writeBlock(int x, int y, int z, int block) { + byte b = (byte) ((block & 0xF) << 4); + + lightData.put(posToIndex(x, y, z), b); + } + + private void writeSky(int x, int y, int z, int sky) { + byte b = (byte) ((sky & 0xF) << 4); + + lightData.put(posToIndex(x, y, z) + 1, b); + } + + private int posToIndex(int x, int y, int z) { + return (x + textureVolume.sizeX() * (y + z * textureVolume.sizeY())) * pixelFormat.byteCount(); + } } diff --git a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolumeDebugger.java b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolumeDebugger.java index ca96b1b79..e63257d04 100644 --- a/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolumeDebugger.java +++ b/src/main/java/com/simibubi/create/foundation/render/backend/light/LightVolumeDebugger.java @@ -10,26 +10,26 @@ import com.simibubi.create.foundation.utility.Pair; import com.simibubi.create.foundation.utility.outliner.AABBOutline; public class LightVolumeDebugger { - public static void render(MatrixStack ms, SuperRenderTypeBuffer buffer) { - ContraptionRenderDispatcher.renderers.values() - .stream() - .flatMap(r -> { - GridAlignedBB texture = r.getLighter().lightVolume.getTextureVolume(); - GridAlignedBB sample = r.getLighter().lightVolume.getSampleVolume(); + public static void render(MatrixStack ms, SuperRenderTypeBuffer buffer) { + ContraptionRenderDispatcher.renderers.values() + .stream() + .flatMap(r -> { + GridAlignedBB texture = r.getLighter().lightVolume.getTextureVolume(); + GridAlignedBB sample = r.getLighter().lightVolume.getSampleVolume(); - ArrayList> pairs = new ArrayList<>(2); + ArrayList> pairs = new ArrayList<>(2); - pairs.add(Pair.of(texture, 0xFFFFFF)); - pairs.add(Pair.of(sample, 0xFFFF00)); + pairs.add(Pair.of(texture, 0xFFFFFF)); + pairs.add(Pair.of(sample, 0xFFFF00)); - return pairs.stream(); - }) - .map(pair -> { - AABBOutline outline = new AABBOutline(GridAlignedBB.toAABB(pair.getFirst())); + return pairs.stream(); + }) + .map(pair -> { + AABBOutline outline = new AABBOutline(GridAlignedBB.toAABB(pair.getFirst())); - outline.getParams().colored(pair.getSecond()); - return outline; - }) - .forEach(outline -> outline.render(ms, buffer, AnimationTickHolder.getPartialTicks())); - } + outline.getParams().colored(pair.getSecond()); + return outline; + }) + .forEach(outline -> outline.render(ms, buffer, AnimationTickHolder.getPartialTicks())); + } } diff --git a/src/main/java/com/simibubi/create/foundation/utility/Pair.java b/src/main/java/com/simibubi/create/foundation/utility/Pair.java index 7941c090d..908e7047c 100644 --- a/src/main/java/com/simibubi/create/foundation/utility/Pair.java +++ b/src/main/java/com/simibubi/create/foundation/utility/Pair.java @@ -49,7 +49,11 @@ public class Pair { @Override public int hashCode() { - return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); + return (nullHash(first) * 31) ^ nullHash(second); + } + + int nullHash(Object o) { + return o == null ? 0 : o.hashCode(); } @Override