Add connected block model

More powerful than the 1.15 TiC one, supports 4 different connection types
This commit is contained in:
KnightMiner committed 2020-07-23 15:55:00 -05:00
1 parent ba7a804212
commit 6c0fb541b8
15 files changed
+726 -199

No files matched your search

@@ -1,82 +0,0 @@
package slimeknights.mantle.block;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld;
/**
* Creates a block with textures that connect to other blocks
* <p>
* Based off a tutorial by Darkhax, used under the Creative Commons Zero 1.0 Universal license
*/
public class ConnectedTextureBlock extends Block {
// These are the properties used for determining whether or not a side is connected. They
// do NOT take up block IDs, they are unlisted properties
public static final BooleanProperty CONNECTED_DOWN = BooleanProperty.create("connected_down");
public static final BooleanProperty CONNECTED_UP = BooleanProperty.create("connected_up");
public static final BooleanProperty CONNECTED_NORTH = BooleanProperty.create("connected_north");
public static final BooleanProperty CONNECTED_SOUTH = BooleanProperty.create("connected_south");
public static final BooleanProperty CONNECTED_WEST = BooleanProperty.create("connected_west");
public static final BooleanProperty CONNECTED_EAST = BooleanProperty.create("connected_east");
public ConnectedTextureBlock(Block.Properties builder) {
super(builder);
// By default none of the sides are connected
this.setDefaultState(this.stateContainer.getBaseState()
.with(CONNECTED_DOWN, Boolean.FALSE)
.with(CONNECTED_EAST, Boolean.FALSE)
.with(CONNECTED_NORTH, Boolean.FALSE)
.with(CONNECTED_SOUTH, Boolean.FALSE)
.with(CONNECTED_UP, Boolean.FALSE)
.with(CONNECTED_WEST, Boolean.FALSE));
}
@Override
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) {
// Creates the state to use for the block. This is where we check if every side is
// connectable or not.
return stateIn.with(CONNECTED_DOWN, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.DOWN))
.with(CONNECTED_EAST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.EAST))
.with(CONNECTED_NORTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.NORTH))
.with(CONNECTED_SOUTH, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.SOUTH))
.with(CONNECTED_UP, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.UP))
.with(CONNECTED_WEST, this.isSideConnectable(stateIn, worldIn, currentPos, Direction.WEST));
}
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
builder.add(CONNECTED_DOWN, CONNECTED_UP, CONNECTED_NORTH, CONNECTED_SOUTH, CONNECTED_WEST, CONNECTED_EAST);
}
/**
* Checks if a specific side of a block can connect to this block. For this example, a side
* is connectable if the block is the same block as this one.
*
* @param state Base state to check
* @param world The world to run the check in.
* @param pos The position of the block to check for.
* @param side The side of the block to check.
* @return Whether or not the side is connectable.
*/
private boolean isSideConnectable(BlockState state, IWorld world, BlockPos pos, Direction side) {
return this.canConnect(state, world.getBlockState(pos.offset(side)));
}
/**
* Checks if this block should connect to another block
* @param original BlockState to check
* @param connected BlockState to check
* @return True if the block is valid to connect
*/
protected boolean canConnect(BlockState original, BlockState connected) {
return original.getBlock() == connected.getBlock();
}
}
@@ -0,0 +1,66 @@
package slimeknights.mantle.block;
import com.mojang.datafixers.util.Pair;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer.Builder;
import net.minecraft.util.Direction;
import slimeknights.mantle.client.model.connected.ConnectedModel;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Used in {@link ConnectedModel} to workaround Forge #6841. Allows a multipart block like panes to have connected textures
*/
@SuppressWarnings({"unused", "JavadocReference"})
public interface IMultipartConnectedBlock {
/** Map of direction to boolean property for that direction */
Map<Direction,BooleanProperty> CONNECTED_DIRECTIONS = Arrays.stream(Direction.values())
.map(dir -> Pair.of(dir,BooleanProperty.create("connected_" + dir.getString())))
.collect(Collectors.toMap(Pair::getFirst, Pair::getSecond, (u,v) -> u, () -> new EnumMap<>(Direction.class)));
/**
* Applies false to all directions in the state, for use in {@link net.minecraft.block.Block#setDefaultState(BlockState)}
* @param state Original state
* @return State with all connections false
*/
static BlockState defaultConnections(BlockState state) {
for (BooleanProperty prop : CONNECTED_DIRECTIONS.values()) {
state = state.with(prop, false);
}
return state;
}
/**
* Fills a state container, for use in {@link Block#fillStateContainer(Builder)}
* @param builder State container builder
*/
static void fillStateContainer(Builder<Block, BlockState> builder) {
CONNECTED_DIRECTIONS.values().forEach(builder::add);
}
/**
* Checks if the block connects to the given neighbor
* @param state State to check
* @param neighbor Neighbor to check
* @return True if the block connects
*/
default boolean connects(BlockState state, BlockState neighbor) {
return state.getBlock() == neighbor.getBlock();
}
/**
* Gets the new connected state based on the given block update
* @param state Current state
* @param facing Side that updated
* @param neighbor Block on the side
* @return Updated block state
*/
default BlockState getConnectionUpdate(BlockState state, Direction facing, BlockState neighbor) {
return state.with(CONNECTED_DIRECTIONS.get(facing), connects(state, neighbor));
}
}
@@ -13,6 +13,7 @@ import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.client.book.BookLoader;
import slimeknights.mantle.client.model.connected.ConnectedModel;
import slimeknights.mantle.client.model.inventory.InventoryModel;
@SuppressWarnings("unused")
@@ -30,5 +31,6 @@ public class ClientEvents {
@SubscribeEvent
static void registerModelLoaders(ModelRegistryEvent event) {
ModelLoaderRegistry.registerLoader(Mantle.getResource("inventory"), InventoryModel.Loader.INSTANCE);
ModelLoaderRegistry.registerLoader(Mantle.getResource("connected"), ConnectedModel.Loader.INSTANCE);
}
}
@@ -0,0 +1,496 @@
package slimeknights.mantle.client.model.connected;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import net.minecraft.block.BlockState;
import net.minecraft.client.renderer.model.BakedQuad;
import net.minecraft.client.renderer.model.BlockFaceUV;
import net.minecraft.client.renderer.model.BlockModel;
import net.minecraft.client.renderer.model.BlockPart;
import net.minecraft.client.renderer.model.BlockPartFace;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.client.renderer.model.IModelTransform;
import net.minecraft.client.renderer.model.IUnbakedModel;
import net.minecraft.client.renderer.model.ItemOverrideList;
import net.minecraft.client.renderer.model.ModelBakery;
import net.minecraft.client.renderer.model.RenderMaterial;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.resources.IResourceManager;
import net.minecraft.state.BooleanProperty;
import net.minecraft.util.Direction;
import net.minecraft.util.Direction.Axis;
import net.minecraft.util.Direction.Plane;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.TransformationMatrix;
import net.minecraft.world.IBlockDisplayReader;
import net.minecraftforge.client.model.BakedModelWrapper;
import net.minecraftforge.client.model.IModelConfiguration;
import net.minecraftforge.client.model.IModelLoader;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.data.EmptyModelData;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.client.model.data.ModelDataMap;
import net.minecraftforge.client.model.data.ModelProperty;
import net.minecraftforge.client.model.geometry.IModelGeometry;
import slimeknights.mantle.block.IMultipartConnectedBlock;
import slimeknights.mantle.client.model.ModelJsonUtils;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Model that handles generating variants for connected textures
*/
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
public class ConnectedModel implements IModelGeometry<ConnectedModel> {
/** Property of the connections cache key. Contains a 6 bit number with each bit representing a direction */
private static final ModelProperty<Byte> CONNECTIONS = new ModelProperty<>();
/** Parent model */
private final BlockModel model;
/** Map of texture name to index of suffixes (indexed as 0bENWS) */
private final Map<String,String[]> connectedTextures;
/** Function to run to check if this block connects to another */
private final BiPredicate<BlockState,BlockState> connectionPredicate;
/** List of sides to check when getting block directions */
private final Set<Direction> sides;
/** Map of full texture name to the resulting material, filled during {@link #getTextures(IModelConfiguration, Function, Set)} */
private final Map<String,Either<RenderMaterial,String>> suffixedTextures = new HashMap<>();
@Override
public Collection<RenderMaterial> getTextures(IModelConfiguration owner, Function<ResourceLocation,IUnbakedModel> modelGetter, Set<Pair<String,String>> missingTextureErrors) {
Collection<RenderMaterial> textures = model.getTextures(modelGetter, missingTextureErrors);
// for all connected textures, add suffix textures
for (Entry<String,String[]> entry : connectedTextures.entrySet()) {
// fetch data from the base texture
String name = entry.getKey();
RenderMaterial base = owner.resolveTexture(name);
ResourceLocation atlas = base.getAtlasLocation();
ResourceLocation texture = base.getTextureLocation();
String namespace = texture.getNamespace();
String path = texture.getPath();
// use base atlas and texture, but suffix the name
// skip suffix 0, because we already added that texture
String[] suffixes = entry.getValue();
for (int i = 1; i < suffixes.length; i++) {
if (suffixes[i].isEmpty()) {
continue;
}
// skip running if we have seen it before
String suffixedName = name + "_" + suffixes[i];
if (!suffixedTextures.containsKey(suffixedName)) {
RenderMaterial mat;
// allow overriding a specific texture
if (owner.isTexturePresent(suffixedName)) {
mat = owner.resolveTexture(suffixedName);
} else {
mat = new RenderMaterial(atlas, new ResourceLocation(namespace, path + "/" + suffixes[i]));
}
textures.add(mat);
// cache the texture name, we use it a lot in rebaking
suffixedTextures.put(suffixedName, Either.left(mat));
}
}
}
return textures;
}
@Override
public IBakedModel bake(IModelConfiguration owner, ModelBakery bakery, Function<RenderMaterial,TextureAtlasSprite> spriteGetter, IModelTransform transform, ItemOverrideList overrides, ResourceLocation location) {
IBakedModel baked = model.bakeModel(bakery, model, spriteGetter, transform, location, true);
return new BakedModel(bakery, transform, baked, this);
}
@SuppressWarnings("WeakerAccess")
protected static class BakedModel extends BakedModelWrapper<IBakedModel> {
private static final ResourceLocation BAKE_LOCATION = new ResourceLocation("tconstruct:connected_model");
private final ModelBakery bakery;
private final ConnectedModel parent;
private final IModelTransform transforms;
private final IBakedModel[] cache = new IBakedModel[64];
private final Map<String,String> nameMappingCache = new HashMap<>();
protected BakedModel(ModelBakery bakery, IModelTransform transforms, IBakedModel baked, ConnectedModel parent) {
super(baked);
this.bakery = bakery;
this.transforms = transforms;
this.parent = parent;
// all directions false gives cache key of 0, that is ourself
this.cache[0] = baked;
}
/**
* Gets the direction rotated
* @param direction Original direction to rotate
* @param rotation Rotation origin, aka the face of the block we are looking at. As a result, UP is identity
* @return Rotated direction
*/
private static Direction rotateDirection(Direction direction, Direction rotation) {
if (rotation == Direction.UP) {
return direction;
}
if (rotation == Direction.DOWN) {
// Z is backwards on the bottom
if (direction.getAxis() == Axis.Z) {
return direction.getOpposite();
}
// X is normal
return direction;
}
// sides all just have the next side for left and right, and consistent up and down
switch(direction) {
case NORTH: return Direction.UP;
case SOUTH: return Direction.DOWN;
case EAST: return rotation.rotateYCCW();
case WEST: return rotation.rotateY();
}
throw new IllegalArgumentException("Direction must be horizontal axis");
}
/**
* Gets a transform function based on the block part UV and block face
* @param face Block face in question
* @param uv Block UV data
* @return Direction transform function
*/
private static Function<Direction,Direction> getTransform(Direction face, BlockFaceUV uv) {
// TODO: how do I apply UV lock?
// final transform switches from face (NSWE) to world direction, the rest are composed in to apply first
Function<Direction,Direction> transform = (d) -> rotateDirection(d, face);
// flipping
boolean flipV = uv.uvs[1] > uv.uvs[3];
if (uv.uvs[0] > uv.uvs[2]) {
// flip both
if (flipV) {
transform = transform.compose(Direction::getOpposite);
} else {
// flip U
transform = transform.compose((d) -> {
if (d.getAxis() == Axis.X) {
return d.getOpposite();
}
return d;
});
}
} else if (flipV) {
transform = transform.compose((d) -> {
if (d.getAxis() == Axis.Z) {
return d.getOpposite();
}
return d;
});
}
// rotation
switch (uv.rotation) {
// 90 degrees
case 90:
transform = transform.compose(Direction::rotateY);
break;
case 180:
transform = transform.compose(Direction::getOpposite);
break;
case 270:
transform = transform.compose(Direction::rotateYCCW);
break;
}
return transform;
}
/**
* Gets the name of this texture that supports connected textures, or null if never is connected
* @param key Name of the part texture
* @return Name of the connected texture
*/
@Nullable
private String getConnectedName(String key) {
if (key.charAt(0) == '#') {
key = key.substring(1);
}
// if the name is connected, we are done
if (parent.connectedTextures.containsKey(key)) {
return key;
}
// if we already found it, return what we found before
if (nameMappingCache.containsKey(key)) {
return nameMappingCache.get(key);
}
// otherwise, iterate into the parent models, trying to find a match
String name = key;
for(BlockModel model = parent.model; model != null; model = model.parent) {
Either<RenderMaterial, String> either = model.textures.get(name);
if (either != null) {
// if no name, its not connected
Optional<String> newName = either.right();
if (!newName.isPresent()) {
nameMappingCache.put(key, null);
return null;
}
// if the name is connected, we are done, return it
name = newName.get();
if (parent.connectedTextures.containsKey(name)) {
nameMappingCache.put(key, name);
return name;
}
}
}
// never found it
nameMappingCache.put(key, null);
return null;
}
/**
* Gets the texture suffix
* @param texture Texture name, must be a connected texture
* @param connections Connections byte
* @param transform Rotations to apply to faces
* @return Key used to cache it
*/
private String getTextureSuffix(String texture, byte connections, Function<Direction,Direction> transform) {
int key = 0;
for (Direction dir : Plane.HORIZONTAL) {
int flag = 1 << transform.apply(dir).getIndex();
if ((connections & flag) == flag) {
key |= 1 << dir.getHorizontalIndex();
}
}
// if empty, do not prefix
String[] suffixes = parent.connectedTextures.get(texture);
assert suffixes != null;
String suffix = suffixes[key];
if (suffix.isEmpty()) {
return suffix;
}
return "_" + suffix;
}
/**
* Gets the model based on the connections in the given model data
* @param connections Array of face connections, true at indexes of connected sides
* @return Model with connections applied
*/
private BlockModel applyConnections(byte connections) {
// will add new textures to this map based on connections
Map<String,Either<RenderMaterial, String>> textures = Maps.newHashMap(parent.model.textures);
// copy each element with updated faces
List<BlockPart> elements = Lists.newArrayList();
for (BlockPart part : parent.model.getElements()) {
Map<Direction,BlockPartFace> partFaces = new EnumMap<>(Direction.class);
for (Map.Entry<Direction,BlockPartFace> entry : part.mapFaces.entrySet()) {
// first, determine which texture to use on this side
Direction dir = entry.getKey();
BlockPartFace original = entry.getValue();
BlockPartFace face = original;
// follow the texture name back to the original name
// if it never reaches a connected texture, skip
String connectedTexture = getConnectedName(original.texture);
if (connectedTexture != null) {
// if empty string, we can keep the old face
String suffix = getTextureSuffix(connectedTexture, connections, getTransform(dir, original.blockFaceUV));
if (!suffix.isEmpty()) {
// suffix the texture
String fullTexture = connectedTexture + suffix;
face = new BlockPartFace(original.cullFace, original.tintIndex, "#" + fullTexture, original.blockFaceUV);
// add the suffixed texture to the map if needed
if (!textures.containsKey(fullTexture)) {
textures.put(fullTexture, parent.suffixedTextures.get(fullTexture));
}
}
}
// add the updated face
partFaces.put(dir, face);
}
// add the updated parts into a new model part
elements.add(new BlockPart(part.positionFrom, part.positionTo, partFaces, part.partRotation, part.shade));
}
// create the final model, copying data we do not change
BlockModel newModel = new BlockModel(parent.model.getParentLocation(), elements, textures,
parent.model.isAmbientOcclusion(), parent.model.func_230176_c_(),
parent.model.getAllTransforms(), Lists.newArrayList(parent.model.getOverrides()));
newModel.name = parent.model.name;
newModel.parent = parent.model.parent;
return newModel;
}
/**
* Gets an array of directions to whether a block exists on the side, indexed using direction indexes
* @param predicate Function that returns true if the block is connected on the given side
* @return Boolean array of data
*/
private static byte getConnections(Predicate<Direction> predicate) {
byte connections = 0;
for (Direction dir : Direction.values()) {
if (predicate.test(dir)) {
connections |= 1 << dir.getIndex();
}
}
return connections;
}
@Override
public IModelData getModelData(IBlockDisplayReader world, BlockPos pos, BlockState state, IModelData tileData) {
// build model data
IModelData data = tileData;
if (data == EmptyModelData.INSTANCE) {
// going to simply add properties below
data = new ModelDataMap.Builder().build();
}
TransformationMatrix rotation = transforms.getRotation();
data.setData(CONNECTIONS, getConnections((dir) -> parent.sides.contains(dir) && parent.connectionPredicate.test(state, world.getBlockState(pos.offset(rotation.rotateTransform(dir))))));
// set connected properties
// for (Direction dir : Direction.values()) {
// if (parent.sides.contains(dir)) {
// data.setData(CONNECTED_PROPERTIES.get(dir), parent.connectionPredicate.test(state, world.getBlockState(pos.offset(rotation.rotateTransform(dir)))));
// }
// }
return data;
}
/**
* Shared logic to get quads from a connections array
* @param connections Byte with 6 bits for the 6 different sides
* @param state Block state instance
* @param side Cullface
* @param rand Random instance
* @param data Model data instance
* @return Model quads for the given side
*/
protected List<BakedQuad> getCachedQuads(byte connections, @Nullable BlockState state, @Nullable Direction side, Random rand, IModelData data) {
// bake a new model if the orientation is not yet baked
if (cache[connections] == null) {
BlockModel connected = applyConnections(connections);
cache[connections] = connected.bakeModel(bakery, connected, ModelLoader.defaultTextureGetter(), transforms, BAKE_LOCATION, true);
}
// get the model for the given orientation
return cache[connections].getQuads(state, side, rand, data);
}
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, Random rand, IModelData data) {
// quick exit if no data
if (data == EmptyModelData.INSTANCE) {
return super.getQuads(state, side, rand, data);
}
// fetch connections byte from the model data, exit if missing
Byte connections = data.getData(CONNECTIONS);
if (connections == null) {
return super.getQuads(state, side, rand, data);
}
// get quads
return getCachedQuads(connections, state, side, rand, data);
}
@Override
public List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, Random rand) {
// quick exit if no state
if (state == null) {
return super.getQuads(null, side, rand);
}
// get data based on block state
TransformationMatrix rotation = transforms.getRotation();
byte connections = getConnections((dir) -> {
if (!parent.sides.contains(dir)) {
return false;
}
BooleanProperty prop = IMultipartConnectedBlock.CONNECTED_DIRECTIONS.get(rotation.rotateTransform(dir));
return state.func_235901_b_(prop) && state.get(prop);
});
return getCachedQuads(connections, state, side, rand, EmptyModelData.INSTANCE);
}
}
/** Loader class containing singleton instance */
public static class Loader implements IModelLoader<ConnectedModel> {
/** Shared loader instance */
public static final ConnectedModel.Loader INSTANCE = new ConnectedModel.Loader();
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {}
@Override
public ConnectedModel read(JsonDeserializationContext context, JsonObject json) {
BlockModel model = ModelJsonUtils.deserialize(context, json);
// root object for all model data
JsonObject data = JSONUtils.getJsonObject(json, "connection");
// need at least one connected texture
JsonObject connected = JSONUtils.getJsonObject(data, "textures");
if (connected.size() == 0) {
throw new JsonSyntaxException("Must have at least one texture in connected");
}
// build texture list
ImmutableMap.Builder<String,String[]> connectedTextures = new ImmutableMap.Builder<>();
for (Entry<String,JsonElement> entry : connected.entrySet()) {
// texture must be in the model
String name = entry.getKey();
if(!model.textures.containsKey(name)) {
throw new JsonSyntaxException("Invalid connected texture " + name + ", missing in model");
}
// get type, put in map
connectedTextures.put(name, ConnectedModelRegistry.deserializeType(entry.getValue(), "textures[" + name + "]"));
}
// get a list of sides to pay attention to
Set<Direction> sides;
if (data.has("sides")) {
JsonArray array = JSONUtils.getJsonArray(data, "sides");
sides = EnumSet.noneOf(Direction.class);
for (int i = 0; i < array.size(); i++) {
String side = JSONUtils.getString(array.get(i), "sides[" + i + "]");
Direction dir = Direction.byName(side);
if (dir == null) {
throw new JsonParseException("Invalid side " + side);
}
sides.add(dir);
}
} else {
sides = EnumSet.allOf(Direction.class);
}
// other data
BiPredicate<BlockState,BlockState> predicate = ConnectedModelRegistry.deserializePredicate(data, "predicate");
// final model instance
return new ConnectedModel(model, connectedTextures.build(), predicate, sides);
}
}
}
@@ -0,0 +1,155 @@
package slimeknights.mantle.client.model.connected;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.block.BlockState;
import net.minecraft.block.SixWayBlock;
import net.minecraft.state.BooleanProperty;
import net.minecraft.util.Direction;
import net.minecraft.util.JSONUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Place to register data related to connected block models
*/
@SuppressWarnings("WeakerAccess")
public class ConnectedModelRegistry {
/* Predicates */
/** Default state predicate, compares the blocks for equality */
private static final BiPredicate<BlockState,BlockState> BLOCK_CONNECTION_PREDICATE = (s1, s2) -> s1.getBlock() == s2.getBlock();
/** Map of name to connection type. Allows registering custom logic to connect two blocks together, used for glass panes for instance */
private static final Map<String,BiPredicate<BlockState,BlockState>> CONNECTION_PREDICATES = new HashMap<>();
/**
* Registers a new connection type
* @param name Name for the type
* @param predicate Connection logic to compare two blockstates for equality
*/
public static void registerPredicate(String name, BiPredicate<BlockState,BlockState> predicate) {
CONNECTION_PREDICATES.putIfAbsent(name, predicate);
}
/**
* Gets the connection predicate for the given JSON
* @param json JsonObject parent
* @param key Predicate key
* @return Connection predicate
*/
public static BiPredicate<BlockState,BlockState> deserializePredicate(JsonObject json, String key) {
String name = JSONUtils.getString(json, key, "block");
if (!CONNECTION_PREDICATES.containsKey(name)) {
throw new JsonSyntaxException("Unknown connection predicate " + name);
}
return CONNECTION_PREDICATES.get(name);
}
/**
* Gets a single predicate by name
* @param name Predicate name
* @return Predicate
*/
@SuppressWarnings("unused")
public static BiPredicate<BlockState,BlockState> getPredicate(String name) {
return CONNECTION_PREDICATES.getOrDefault(name, BLOCK_CONNECTION_PREDICATE);
}
/**
* Gets a property from the state if it exists
* @param state State with property
* @param prop Property to get
* @return True if the property exists and is true, false if false or missing
*/
private static boolean safeGet(BlockState state, BooleanProperty prop) {
return state.func_235901_b_(prop) && state.get(prop);
}
static {
// connect to block
registerPredicate("block", BLOCK_CONNECTION_PREDICATE);
// smarter connections for panes
registerPredicate("pane", (state, neighbor) -> {
// must be the same block, and either both blocks must be center only, or neither are center only
return state.getBlock() == neighbor.getBlock()
&& (safeGet(state, SixWayBlock.NORTH) || safeGet(state, SixWayBlock.EAST) || safeGet(state, SixWayBlock.SOUTH) || safeGet(state, SixWayBlock.WEST))
== (safeGet(neighbor, SixWayBlock.NORTH) || safeGet(neighbor, SixWayBlock.EAST) || safeGet(neighbor, SixWayBlock.SOUTH) || safeGet(neighbor, SixWayBlock.WEST));
});
}
/* Texture mapping */
/** Map of name to connection types */
private static final Map<String,String[]> CONNECTION_TYPES = new HashMap<>();
/**
* Registers a connection type
* @param name Type name
* @param mapper Function of predicate to texture name. Predicate will match NSWE, signifying the texture connects UDLR
* Only called during registration, results are cached into the 16 variants
*/
public static void registerType(String name, Function<Predicate<Direction>,String> mapper) {
if (!CONNECTION_TYPES.containsKey(name)) {
String[] suffixes = new String[16];
for (int i = 0; i < 16; i++) {
final int index = i;
suffixes[i] = mapper.apply((dir) -> {
int flag = 1 << dir.getHorizontalIndex();
return (index & flag) == flag;
});
}
CONNECTION_TYPES.put(name, suffixes);
}
}
/**
* Gets the connection type from the given JSON
* @param json JsonObject parent
* @param key Predicate key
* @return Connection predicate
*/
public static String[] deserializeType(JsonElement json, String key) {
String name = JSONUtils.getString(json, key);
if (!CONNECTION_TYPES.containsKey(name)) {
throw new JsonSyntaxException("Unknown connection type " + name);
}
return CONNECTION_TYPES.get(name);
}
static {
// connects on all four sides
registerType("cornerless_full", predicate -> {
String name = "";
if (predicate.test(Direction.NORTH)) name += "u";
if (predicate.test(Direction.SOUTH)) name += "d";
if (predicate.test(Direction.WEST)) name += "l";
if (predicate.test(Direction.EAST)) name += "r";
return name;
});
// connects horizontally
registerType("horizontal", predicate -> {
boolean right = predicate.test(Direction.EAST);
if (predicate.test(Direction.WEST)) {
return right ? "middle" : "right";
}
return right ? "left" : "";
});
// connects vertically
registerType("vertical", predicate -> {
boolean bottom = predicate.test(Direction.SOUTH);
if (predicate.test(Direction.NORTH)) {
return bottom ? "middle" : "bottom";
}
return bottom ? "top" : "";
});
// connects to just the top block
registerType("top", predicate -> predicate.test(Direction.NORTH) ? "bottom" : "");
}
}
@@ -0,0 +1,7 @@
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package slimeknights.mantle.client.model.connected;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;