Jump to content

Recommended Posts

Posted

What I need, is a custom itemstack texture present base on some information(Currently I save these information in CompoundNBT).

These information decide and pick several textures and I need to combine them just like what vanilla "layer#" do.

These information isn't and won't be a float, so vanilla itemoverride can't solve it.

 

I'm searching a way to solve it for several days, but I got stuck in something due to leak tutorial of this kind of things.

I already read this intro to advance models in forge wesite, but it's hard to understand because I can't find things like IModel, ICustomModelLoader in this version.(But I found something like them)

And I tried hard to read DynamicBucketModel and write my code, but now I'm stuck in loading picture to Material, which I can get TextureAtlasSprite to construct a BakedModel.

 

What I already done/tried/planed:

 

I defined a new IModelLoader called MealModelLoader

public enum MealModelLoader implements IModelLoader<MealModel>{
	INSTANCE;

	@Override
	public void onResourceManagerReload(IResourceManager resourceManager){
			
	}

	@Override
	public MealModel read(JsonDeserializationContext deserializationContext, JsonObject modelContents){
		System.out.println(modelContents);

		String pathName = modelContents.has("path_name") ? modelContents.get("path_name").getAsString() : "";
		String baseFilePath = modelContents.has("base") ? modelContents.get("base").getAsString() : "";
		JsonArray parts = modelContents.has("part") ? modelContents.get("part").getAsJsonArray() : new JsonArray();
		//TODO
		return new MealModel(pathName, baseFilePath, parts);
	}
}

It return a MealModel which implement IModelGeometry<MealModel> (I'll talk about MealBakedModel which return in bake method later.)

public class MealModel implements IModelGeometry<MealModel>{
	private String pathName, baseFilePath;
	private JsonArray parts;

	public MealModel(String pathNameIn, String baseFilePathIn, JsonArray partsIn){
		this.pathName = pathNameIn;
		this.baseFilePath = baseFilePathIn;
		this.parts = partsIn;
	}

	@Override
	public IBakedModel bake(IModelConfiguration owner, ModelBakery bakery
			, Function<Material, TextureAtlasSprite> spriteGetter, IModelTransform modelTransform
			, ItemOverrideList overrides, ResourceLocation modelLocation){

		TransformationMatrix transform = modelTransform.func_225615_b_();
		TextureAtlasSprite particle = spriteGetter.apply(owner.resolveTexture("particle"));//Just using something and make game can launch successful
		ImmutableMap<TransformType, TransformationMatrix> map = PerspectiveMapWrapper.getTransforms(modelTransform);
		// TODO
		return new MealBakedModel(ImmutableList.of(), particle, map, transform.isIdentity(), owner.isSideLit());
	}

	@Override
	public Collection<Material> getTextures(IModelConfiguration owner
		, Function<ResourceLocation, IUnbakedModel> modelGetter
		, Set<Pair<String, String>> missingTextureErrors){

		Set<Material> texs = Sets.newHashSet();

		// TODO
		return texs;
	}
	
}

And I registed my MealModelLoader using ModelLoaderRegistry in FMLClientSetupEvent.

@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event){
	Containers.registAllScreen();
	RenderHandler.setup();
	ModelLoaderRegistry.registerLoader(new ResourceLocation(FoodPower.MODID, "meal"), MealModelLoader.INSTANCE);
}

Then I write json model using this loader, and try to add some information I may need to make a model.

{
	"parent": "item/generated",
	"loader": "foodpower:meal",

	"path_name": "salad",
	"base": "foodpower:meals/salad/salad_base",
	"part": [{
		"slot": "VEGETABLE",
		"textures": {
			"cabbage": "foodpower:meals/salad/salad_cabbage",
			"tomato": "foodpower:meals/salad/salad_tomato"
		}
	}, {
		"slot": "MEAT",
		"textures": {
			"beef": "foodpower:meals/salad/salad_beef",
			"chicken": "foodpower:meals/salad/salad_chicken"
		}
	}, {
		"slot": "SEASONING",
		"textures": {
			"ketchop": "foodpower:meals/salad/salad_ketchop",
			"sauce": "foodpower:meals/salad/salad_sauce"
		}
	}]
}

Now I can successfully load these json information in MealModelLoader#read, and using them to construct a MealModel.
(Maybe it's a bad idea to pass a JsonArray to MealModel? I may change it to be a something like Map<String, Map<String, String>>).

 

I'm now stuck in MealModel#bake.

I can get the path string in json file, but how can I using this to get Material?

If I get Material, I plan to get TextureAtlasSprite using parameter spriteGetter, then pass it to my MealBakedModel, is that right?

public class MealBakedModel extends BakedItemModel{

	public MealBakedModel(ImmutableList<BakedQuad> quads, TextureAtlasSprite particle,
			ImmutableMap<TransformType, TransformationMatrix> transforms,
			boolean untransformed, boolean isSideLit){
		super(quads, particle, transforms, new MealItemOverrideList(), untransformed, isSideLit);
		// TODO
	}
}

I found a method IModelConfiguration#resolveTexture, I think it may be a key, but I don't know how to use it.

/**
  * Resolves the final texture name, taking into account texture aliases and replacements.
  * @param name The name of a texture channel.
  * @return The location of the texture, or the missing texture if not found.
  */
Material resolveTexture(String name)

What does "texture channel" mean? A folder under asset/modid/textures?

I tried pass in a lot of String including name of folder which I construct under asset/modid/textures to it, but it always return the "missing texture".

 

Finally, I define a MealItemOverrideList which extends ItemOverrideList.

Because I need method ItemOverrideList#getModelWithOverrides, I override it.

public class MealItemOverrideList extends ItemOverrideList{
	public MealItemOverrideList(){
		//TODO
	}
	@Override
	public IBakedModel getModelWithOverrides(IBakedModel model, ItemStack stack, @Nullable World worldIn, @Nullable LivingEntity entityIn){
		//TODO
		return null;
	}
}

This method pass in a ItemStack, which I can get information in CompoundNBT I stored.

Then I'll use this information to make a final MealBakedModel to return.

 

Ok, that all.

So how can I make a Material using path string in json file?

And is there anything I did/planed is wrong or a bad idea? Or it has another better way to do that.

Thanks for reading these.

Posted

OK, now I know something more.

 

23 hours ago, immortalmice said:

I found a method IModelConfiguration#resolveTexture, I think it may be a key, but I don't know how to use it.


/**
  * Resolves the final texture name, taking into account texture aliases and replacements.
  * @param name The name of a texture channel.
  * @return The location of the texture, or the missing texture if not found.
  */
Material resolveTexture(String name)

What does "texture channel" mean? A folder under asset/modid/textures?

I tried pass in a lot of String including name of folder which I construct under asset/modid/textures to it, but it always return the "missing texture".

 

Texture channel is the thing you write under "textures" in your json file.

{
	"parent": "item/generated",
	"textures": {
		"layer0": "foodpower:blocks/juicer_top"
	},
	"loader": "foodpower:meal"
}

I pass in "layer0", it finally return a normal Material instead of missing texture. IModelConfiguration#isTexturePresent also return true.

 

But now I have another problem, if I change "layer0" to another key name, it won't work.

And I found that BlockModelConfiguration#isTexturePresent called BlockModel#isTexturePresent.

(net.minecraftforge.client.model.BlockModelConfiguration is the only one who implement IModelConfiguration)

BlockModel has its own JsonDeserializer, and call BlockModel#getTextures to construct a Map<String, Either<Material, String>> textures, and this field is used in BlockModel#isTexturePresent.

Code is here. the JsonObject passed in is the whole json file. The map it return is used in construct BlockModel and place in textures field directly.

private Map<String, Either<Material, String>> getTextures(JsonObject object) {
      ResourceLocation resourcelocation = AtlasTexture.LOCATION_BLOCKS_TEXTURE;
      Map<String, Either<Material, String>> map = Maps.newHashMap();
      if (object.has("textures")) {
         JsonObject jsonobject = JSONUtils.getJsonObject(object, "textures");

         for(Entry<String, JsonElement> entry : jsonobject.entrySet()) {
            map.put(entry.getKey(), func_228819_a_(resourcelocation, entry.getValue().getAsString()));
         }
      }

      return map;
}

 

So, I think it will take every key under textures, but it don't.

What I missed?

 

And I saw code in DynamicBucketModel#bake.

Material baseLocation = owner.resolveTexture("base");
if (MissingTextureSprite.getLocation().equals(baseLocation.func_229313_b_()))
{
   baseLocation = null;
}

Then I tried change the key name to "bake", but it didn't work too.

I really need some help. Thx.

Posted

Why not use Blockbench? Here you can create your Object and then play around with the Position, rotation, and how it will be look in the Inventory, …. Hope it help.

New in Modding? == Still learning!

Posted
2 hours ago, DragonITA said:

Why not use Blockbench? Here you can create your Object and then play around with the Position, rotation, and how it will be look in the Inventory, …. Hope it help.

 

What I need is the itemstack texture depend on its nbt, nbt will store some information about what ingredient player used to make this itemstack.

For example, I may need a.png, b.png, c.png 3 picture and stack them together to display this itemstack.

But according by how player maked this itemstack, I may need to stack a.png, d.png and e.png together now.

I think it's not just a single json file can solve it.

 

Thx for reply :).

Posted (edited)
9 hours ago, DragonITA said:

@immortalmice, sorry, i not really work with NBT Datas, and i not know it and it utility, but then it should be like a Bow, only that you use a NBT Data, no? Hope it help you.

Bow use a thing called ItemOverride, it can use key word "overrides" in json file to select a model depend on a float value.

For example, how hard is the bow pulled, where should compass point to and what time is it now(Vanilla clock).

To use your own float value, just call Item#addPropertyOverride and write the "predicate" field in the "overrides" section in json file that will be fine.

This is what vanilla bow model json file like.

{
    "parent": "item/generated",
    "textures": {
        "layer0": "item/bow"
    },
    "display": {
        //...
    },
    "overrides": [
        {
            "predicate": {
                "pulling": 1
            },
            "model": "item/bow_pulling_0"
        },
        {
            "predicate": {
                "pulling": 1,
                "pull": 0.65
            },
            "model": "item/bow_pulling_1"
        },
        {
            "predicate": {
                "pulling": 1,
                "pull": 0.9
            },
            "model": "item/bow_pulling_2"
        }
    ]
}

 

But my case is a combination of Strings, not a float.

Yes, I can map them to each float, however, a salad, the possible combination will be 3*13*5.(Salad is made with three kinds of ingredient, each kind has its possible choices)

That means I need to wirte 195 model file, I think it will make things worst and terrible.

 

Currently I planed to do, is extend ItemOverrideList to my custom MealItemOverrideList, and override ItemOverrideList#getModelWithOverrides, so that I can generate my model depend on my itemstack.

And it seems that I need to make my own model geometry, baked mode and model loader too, and I encounter a problem in IModelGeometry#bake, then this post spawn.

 

7 hours ago, The_Wabbit said:

Perhaps you can try looking at how the Culinary Construct Mod does its dynamic sandwich itemstack rendering: https://github.com/TheIllusiveC4/CulinaryConstruct.git.

HTH

Oh, thx.

1.12.2 is a lot different to 1.15.2 now, but its may be helpful to me in sometimes~ 

Edited by immortalmice
typo
Posted (edited)

It seem that I solve my problem in someway.

 

I still don't know how IModelConfiguration#resolveTexture worked, and I can't get a Material from it now too.

But, now I found I can directly call new Material to solve my need.

I tried new Material before but it fail at that point in time, because I missed a thing.

I need to subscribe TextureStitchEvent, so that I can add my texture to AtlasTexture.

@SubscribeEvent
public static void onTextureStitch(TextureStitchEvent.Pre event){
	if(event.getMap().func_229223_g_().equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)){
		event.addSprite(new ResourceLocation(FoodPower.MODID, "meals/salad/salad_base"));
	}
}

So now directly new a Material and transform it to TextureAtlasSprite will work.

Material m = new Material(AtlasTexture.LOCATION_BLOCKS_TEXTURE, new ResourceLocation(FoodPower.MODID, "meals/salad/salad_base"));

 

Thx from everyone who replied this post.

But I still open for any better suggestion :)

Edited by immortalmice
typo
  • Like 1
Posted

Can you make a Github repo for this? I am sure that it will be help others modders, and as it was in the 1.15.2, this would really help. 

P.S.: I not understand your system, can you explain it? It looks very interesing.

  • Like 1

New in Modding? == Still learning!

Posted (edited)
23 hours ago, DragonITA said:

Can you make a Github repo for this? I am sure that it will be help others modders, and as it was in the 1.15.2, this would really help. 

P.S.: I not understand your system, can you explain it? It looks very interesing.

Ok, here's repo. I set it public now.

https://github.com/immortalmice/FoodPower

This mod is under construction, so everything will be what I mention in README.txt.

 

My mod have many parts.

About making food, this mod has some cooking patterns, such as cake, pizza, salad...etc.

You can select a pattern to make a recipe, pattern will tell you what ingredients is necessary, and what is optional(with certain food types).

With recipe, you can follow cooking steps on it to make your food by using oven, frying pan, juicer...etc.

 

Depend on what you used in this food, after eating it will give you some buff and some special experience.

Experience will help you on cooking new meals, and most important - some special power for you in gaming minecraft.

And there some other features in this mod, so I still working hard for it :)

Edited by immortalmice
forgot giving repo link
  • Thanks 2

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.