Jump to content

Custom minecart model is not be rendered


Christian.

Recommended Posts

Hello all,

I'm trying to make a custom minecart. It's working so far, but theres a little issue... it's invisible. A Shdow will be drawn, but the Model itself do not render.

Here is my Renderer registration:

import com.broschi.powercart.Powercart;
import com.broschi.powercart.client.renderer.PowercartEntityRenderer;
import com.broschi.powercart.client.renderer.model.PowercartEntityModel;
import com.broschi.powercart.init.EntityInit;

import net.minecraft.world.entity.EntityType;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.client.event.EntityRenderersEvent.RegisterRenderers;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(bus = Bus.MOD, modid = Powercart.MOD_ID, value = { Dist.CLIENT })
public class ClientModEvent {
	private static final Logger LOGGER = LogManager.getLogger();
	@SubscribeEvent
	public static void registerRenderers(RegisterRenderers event) {
		event.registerEntityRenderer((EntityType)EntityInit.POWERCART.get(), PowercartEntityRenderer::new);
	}

	@SubscribeEvent
	public static void registerLayers(EntityRenderersEvent.RegisterLayerDefinitions event) {
		event.registerLayerDefinition(PowercartEntityModel.LAYER_LOCATION, PowercartEntityModel::createBodyLayer);
	}
}

And here the renderer:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.broschi.powercart.Powercart;
import com.broschi.powercart.client.renderer.model.PowercartEntityModel;
import com.broschi.powercart.common.PowercartEntity;

import net.minecraft.client.model.EntityModel;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.resources.ResourceLocation;

public class PowercartEntityRenderer<Type extends PowercartEntity> extends EntityRenderer<PowercartEntity> {
	private static final Logger LOGGER = LogManager.getLogger();
	private final EntityRendererProvider.Context context;
	private static final ResourceLocation TEXTURE = new ResourceLocation(Powercart.MOD_ID,
			"textures/entity/powercart.png");
	protected final EntityModel<Type> model;

	public PowercartEntityRenderer(EntityRendererProvider.Context context) {
		super(context);
		this.context = context;
		this.shadowRadius = 0.5F;
		this.shadowStrength = 2.0F;
		this.model = new PowercartEntityModel<>(context.bakeLayer(PowercartEntityModel.LAYER_LOCATION));
	}

	@Override
	public ResourceLocation getTextureLocation(PowercartEntity p_114482_) {
		LOGGER.info("getTextureLocation");
		return TEXTURE;
	}
}

And the model:

package com.broschi.powercart.client.renderer.model;

import com.broschi.powercart.Powercart;
import com.broschi.powercart.common.PowercartEntity;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;

import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.CubeDeformation;
import net.minecraft.client.model.geom.builders.CubeListBuilder;
import net.minecraft.client.model.geom.builders.LayerDefinition;
import net.minecraft.client.model.geom.builders.MeshDefinition;
import net.minecraft.client.model.geom.builders.PartDefinition;
import net.minecraft.resources.ResourceLocation;

public class PowercartEntityModel<T extends PowercartEntity> extends EntityModel<T> {
	// This layer location should be baked with EntityRendererProvider.Context in the entity renderer and passed into this model's constructor
	public static final ModelLayerLocation LAYER_LOCATION = new ModelLayerLocation(new ResourceLocation(Powercart.MOD_ID, "powercart"), "powercart");
	private final ModelPart bb_main;

	public PowercartEntityModel(ModelPart root) {
		this.bb_main = root.getChild("bb_main");
	}

	public static LayerDefinition createBodyLayer() {
		MeshDefinition meshdefinition = new MeshDefinition();
		PartDefinition partdefinition = meshdefinition.getRoot();

		PartDefinition bb_main = partdefinition.addOrReplaceChild("bb_main", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -7.0F, -8.0F, 16.0F, 7.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 24.0F, 0.0F));

		return LayerDefinition.create(meshdefinition, 64, 64);
	}

	@Override
	public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {

	}

	@Override
	public void renderToBuffer(PoseStack poseStack, VertexConsumer buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) {
		bb_main.render(poseStack, buffer, packedLight, packedOverlay);
	}
}

 

The model is created by blockbench. It is currently just a box with colored sides. The Texture is also created by blockbench.

 

If i start the game and summon a cart, the shadow is shown on the ground. There is no error message in the console. getTextureLocation is never called.

I am sure I am doing something obvious wrong. But i don't get it. What i am missing?

 

Thanks in advance

Edited by Christian.
Typo, syntax highlighting
Link to comment
Share on other sites

It is basicly a copy from MinecartFurnace.class:

 

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.entity.vehicle.MinecartFurnace;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.FurnaceBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;

public class PowercartEntity extends AbstractMinecart {
   private static final EntityDataAccessor<Boolean> DATA_ID_FUEL = SynchedEntityData.defineId(MinecartFurnace.class, EntityDataSerializers.BOOLEAN);
   private int fuel;
   public double xPush;
   public double zPush;
   private static final Ingredient INGREDIENT = Ingredient.of(Items.COAL, Items.CHARCOAL);

   public PowercartEntity(EntityType<?> p_38552_, Level p_38553_) {
      super((EntityType<MinecartFurnace>)p_38552_, p_38553_);
   }

   public PowercartEntity(Level p_38555_, double p_38556_, double p_38557_, double p_38558_) {
      super(EntityType.FURNACE_MINECART, p_38555_, p_38556_, p_38557_, p_38558_);
   }

   public AbstractMinecart.Type getMinecartType() {
      return AbstractMinecart.Type.FURNACE;
   }

   protected void defineSynchedData() {
      super.defineSynchedData();
      this.entityData.define(DATA_ID_FUEL, false);
   }

   public void tick() {
      super.tick();
      if (!this.level.isClientSide()) {
         if (this.fuel > 0) {
            --this.fuel;
         }

         if (this.fuel <= 0) {
            this.xPush = 0.0D;
            this.zPush = 0.0D;
         }

         this.setHasFuel(this.fuel > 0);
      }

      if (this.hasFuel() && this.random.nextInt(4) == 0) {
         this.level.addParticle(ParticleTypes.LARGE_SMOKE, this.getX(), this.getY() + 0.8D, this.getZ(), 0.0D, 0.0D, 0.0D);
      }

   }

   protected double getMaxSpeed() {
      return (this.isInWater() ? 3.0D : 4.0D) / 20.0D;
   }

   @Override
   public float getMaxCartSpeedOnRail() {
      return 0.2f;
   }

   public void destroy(DamageSource p_38560_) {
      super.destroy(p_38560_);
      if (!p_38560_.isExplosion() && this.level.getGameRules().getBoolean(GameRules.RULE_DOENTITYDROPS)) {
         this.spawnAtLocation(Blocks.FURNACE);
      }

   }

   protected void moveAlongTrack(BlockPos p_38569_, BlockState p_38570_) {
      double d0 = 1.0E-4D;
      double d1 = 0.001D;
      super.moveAlongTrack(p_38569_, p_38570_);
      Vec3 vec3 = this.getDeltaMovement();
      double d2 = vec3.horizontalDistanceSqr();
      double d3 = this.xPush * this.xPush + this.zPush * this.zPush;
      if (d3 > 1.0E-4D && d2 > 0.001D) {
         double d4 = Math.sqrt(d2);
         double d5 = Math.sqrt(d3);
         this.xPush = vec3.x / d4 * d5;
         this.zPush = vec3.z / d4 * d5;
         
         /*if (this.xPush > 0) this.xPush=5;
         if (this.zPush > 0) this.zPush=5;
         if (this.xPush < 0) this.xPush=-5;
         if (this.zPush < 0) this.zPush=-5;*/
      }

   }

   protected void applyNaturalSlowdown() {
      double d0 = this.xPush * this.xPush + this.zPush * this.zPush;
      if (d0 > 1.0E-7D) {
         d0 = Math.sqrt(d0);
         this.xPush /= d0;
         this.zPush /= d0;
         Vec3 vec3 = this.getDeltaMovement().multiply(0.8D, 0.0D, 0.8D).add(this.xPush, 0.0D, this.zPush);
         if (this.isInWater()) {
            vec3 = vec3.scale(0.1D);
         }

         this.setDeltaMovement(vec3);
      } else {
         this.setDeltaMovement(this.getDeltaMovement().multiply(0.98D, 0.0D, 0.98D));
      }

      super.applyNaturalSlowdown();
   }

   public InteractionResult interact(Player p_38562_, InteractionHand p_38563_) {
      InteractionResult ret = super.interact(p_38562_, p_38563_);
      if (ret.consumesAction()) return ret;
      ItemStack itemstack = p_38562_.getItemInHand(p_38563_);
      if (INGREDIENT.test(itemstack) && this.fuel + 3600 <= 32000) {
         if (!p_38562_.getAbilities().instabuild) {
            itemstack.shrink(1);
         }

         this.fuel += 3600;
      }

      if (this.fuel > 0) {
         this.xPush = this.getX() - p_38562_.getX();
         this.zPush = this.getZ() - p_38562_.getZ();
         LOGGER.info(this.xPush+" "+this.zPush);
      }

      return InteractionResult.sidedSuccess(this.level.isClientSide);
   }

   protected void addAdditionalSaveData(CompoundTag p_38567_) {
      super.addAdditionalSaveData(p_38567_);
      p_38567_.putDouble("PushX", this.xPush);
      p_38567_.putDouble("PushZ", this.zPush);
      p_38567_.putShort("Fuel", (short)this.fuel);
   }

   protected void readAdditionalSaveData(CompoundTag p_38565_) {
      super.readAdditionalSaveData(p_38565_);
      this.xPush = p_38565_.getDouble("PushX");
      this.zPush = p_38565_.getDouble("PushZ");
      this.fuel = p_38565_.getShort("Fuel");
   }

   protected boolean hasFuel() {
      return this.entityData.get(DATA_ID_FUEL);
   }

   protected void setHasFuel(boolean p_38577_) {
      this.entityData.set(DATA_ID_FUEL, p_38577_);
   }

   public BlockState getDefaultDisplayBlockState() {
      return Blocks.FURNACE.defaultBlockState().setValue(FurnaceBlock.FACING, Direction.NORTH).setValue(FurnaceBlock.LIT, Boolean.valueOf(this.hasFuel()));
   }
}

 

And i created an item. When i use the item, my wannabe Powercart is placed on the rail but with the default texture. When i use the summon command, my Cart is also created, but i see only the shadow.

 

Here is the item:

package com.broschi.powercart.common;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jline.utils.Log;

import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockSource;
import net.minecraft.core.Direction;
import net.minecraft.core.dispenser.DefaultDispenseItemBehavior;
import net.minecraft.core.dispenser.DispenseItemBehavior;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseRailBlock;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.RailShape;
import net.minecraft.world.level.gameevent.GameEvent;

public class PowercartItem extends Item {

	private static final Logger LOGGER = LogManager.getLogger();
	private static final DispenseItemBehavior DISPENSE_ITEM_BEHAVIOR = new DefaultDispenseItemBehavior() {

		private final DefaultDispenseItemBehavior defaultDispenseItemBehavior = new DefaultDispenseItemBehavior();

		public ItemStack execute(BlockSource p_42949_, ItemStack p_42950_) {
			Direction direction = p_42949_.getBlockState().getValue(DispenserBlock.FACING);
			Level level = p_42949_.getLevel();
			double d0 = p_42949_.x() + (double) direction.getStepX() * 1.125D;
			double d1 = Math.floor(p_42949_.y()) + (double) direction.getStepY();
			double d2 = p_42949_.z() + (double) direction.getStepZ() * 1.125D;
			BlockPos blockpos = p_42949_.getPos().relative(direction);
			BlockState blockstate = level.getBlockState(blockpos);
			RailShape railshape = blockstate.getBlock() instanceof BaseRailBlock
					? ((BaseRailBlock) blockstate.getBlock()).getRailDirection(blockstate, level, blockpos, null)
					: RailShape.NORTH_SOUTH;
			double d3;
			if (blockstate.is(BlockTags.RAILS)) {
				if (railshape.isAscending()) {
					d3 = 0.6D;
				} else {
					d3 = 0.1D;
				}
			} else {
				if (!blockstate.isAir() || !level.getBlockState(blockpos.below()).is(BlockTags.RAILS)) {
					return this.defaultDispenseItemBehavior.dispense(p_42949_, p_42950_);
				}

				BlockState blockstate1 = level.getBlockState(blockpos.below());
				RailShape railshape1 = blockstate1.getBlock() instanceof BaseRailBlock
						? blockstate1.getValue(((BaseRailBlock) blockstate1.getBlock()).getShapeProperty())
						: RailShape.NORTH_SOUTH;
				if (direction != Direction.DOWN && railshape1.isAscending()) {
					d3 = -0.4D;
				} else {
					d3 = -0.9D;
				}
			}

			AbstractMinecart abstractminecart = new PowercartEntity(level, d0, d1 + d3, d2);

			if (p_42950_.hasCustomHoverName()) {
				abstractminecart.setCustomName(p_42950_.getHoverName());
			}

			level.addFreshEntity(abstractminecart);
			p_42950_.shrink(1);
			return p_42950_;
		}

		protected void playSound(BlockSource p_42947_) {
			p_42947_.getLevel().levelEvent(1000, p_42947_.getPos(), 0);
		}
	};

	public PowercartItem(Properties properties) {
		super((new Item.Properties()).stacksTo(64).tab(CreativeModeTab.TAB_TRANSPORTATION));
		DispenserBlock.registerBehavior(this, DISPENSE_ITEM_BEHAVIOR);
	}
	
	 @Override
	 public InteractionResult useOn(UseOnContext context) {
	     Level level = context.getLevel();
	     BlockPos pos = context.getClickedPos();
	     BlockState state = level.getBlockState(pos);
	     if (!state.is(BlockTags.RAILS)) {
	        return InteractionResult.FAIL;
	     } else {
	        ItemStack itemstack = context.getItemInHand();
	        if (!level.isClientSide) {
	           RailShape shape = state.getBlock() instanceof BaseRailBlock ? ((BaseRailBlock)state.getBlock()).getRailDirection(state, level, pos, (AbstractMinecart)null) : RailShape.NORTH_SOUTH;
	           double d0 = 0.0D;
	           if (shape.isAscending()) {
	              d0 = 0.5D;
	           }
		            PowercartEntity cart = new PowercartEntity(level, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.0625D + d0, (double)pos.getZ() + 0.5D);
		            level.addFreshEntity(cart);
	        }
		         itemstack.shrink(1);
	        return InteractionResult.SUCCESS;
	     }
	 }
}

 

Link to comment
Share on other sites

37 minutes ago, diesieben07 said:

You should consider extending the class and only overriding what you need to change instead of copy-pasting the whole code...

It was not possible, because there are some protected field i want to override. I know there is a new thing called Access transformer, maybe i should learn more about it.

I changed the file to this:

package com.broschi.powercart.common;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.minecraft.network.protocol.Packet;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.vehicle.MinecartFurnace;
import net.minecraft.world.level.Level;
import net.minecraftforge.network.NetworkHooks;

public class PowercartEntity extends MinecartFurnace {

	private static final Logger LOGGER = LogManager.getLogger();
	
	public PowercartEntity(EntityType<?> entityType, Level level) {
		super((EntityType<? extends PowercartEntity>)entityType, level);
	}

	public PowercartEntity(Level p_38555_, double p_38556_, double p_38557_, double p_38558_) {
		super(p_38555_, p_38556_, p_38557_, p_38558_);
	}

	@Override
    public Packet<?> getAddEntityPacket() {
		return NetworkHooks.getEntitySpawningPacket(this);
	}
}

 

Quote

You must use your EntityType.

Can't do it anymore, because i extend MinecraftFurnace now end the constructor does not take a EntityType.

 

Problem is still there, summon spawns only a shadow and the item spawn it with the default model. How ever this is possible

Link to comment
Share on other sites

Yes, simillar to the both constructors in my class.

   public MinecartFurnace(EntityType<? extends MinecartFurnace> p_38552_, Level p_38553_) {
      super(p_38552_, p_38553_);
   }

   public MinecartFurnace(Level p_38555_, double p_38556_, double p_38557_, double p_38558_) {
      super(EntityType.FURNACE_MINECART, p_38555_, p_38556_, p_38557_, p_38558_);
   }
	public PowercartEntity(EntityType<? extends PowercartEntity> entityType, Level level) {
		super(entityType, level);
	}

	public PowercartEntity(Level p_38555_, double p_38556_, double p_38557_, double p_38558_) {
		super(p_38555_, p_38556_, p_38557_, p_38558_);
	}

AFAIK the first on is used to register the entity and the second one to create a new entity in the world. It's not like i could choose one

Link to comment
Share on other sites

Ok, ju CAN do it like this:

	public PowercartEntity(EntityType<? extends Entity> entityType, Level level) {
		super((EntityType<PowercartEntity>)entityType, level);
	}

	public PowercartEntity(Level level, double d0, double d1, double d2) {
		super((EntityType<? extends PowercartEntity>) EntityInit.POWERCART.get(), level);
		this.setPos(d0, d1, d2);
	    this.xo = d0;
	    this.yo = d1;
	    this.zo = d2;
	}

Don't know if this is what you have in mind, but it's "working". But now the cart is not rendered neither if you use the summon command nor if you place it with the item. The Shadow is drawn as specified in the Renderer class and there are smoke particels when the cart is active.

Link to comment
Share on other sites

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

    • Hello, I was trying to play a MOD in my preferred language, but I see that only some items are translated, and I go to debug and I get this information (the only thing that is translated is the bestiary):   [14sep.2024 17:14:36.415] [Render thread/WARN] [net.minecraft.client.resources.language.ClientLanguage/]: Skipped language file: mowziesmobs:lang/es_es.json (com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 394 column 2 path $.config.mowziesmobs.ice_crystal_attack_multiplier) [14sep.2024 17:14:36.421] [Render thread/WARN] [net.minecraft.client.resources.language.ClientLanguage/]: Skipped language file: iceandfire:lang/es_es.json (com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1349 column 4 path $.iceandfire.sound.subtitle.dragonflute)   Is that the reason why everything is not translated? , and is there any way to fix it? Thanks
    • I got my model to render from the models renderToBuffer method. But still not quite what I want. I want to render the model from my renderer's render method. I feel that having access to the renderer and its methods will open some doors for me later down the line. //EntityRendererProvider.Context pContext = ; I want this //ToaPlayerRenderer render = new ToaPlayerRenderer(pContext, false); // if I can get the above line to work, having the methods from the renderer class would be incredibly helpful down the line RenderType rendertype = model.renderType(p.getSkinTextureLocation()); // this should be something like render.getTextureLocation() VertexConsumer vertexconsumer = buffer.getBuffer(rendertype); model.renderToBuffer(stack, vertexconsumer, paLights, 1, 1, 1, 1, 1); // I don't want the render to happen here since it doesn't use the renderer //model.render(p, 1f, pTicks, stack, buffer, paLights); I want to render the model using this It is certainly getting closer though. Probably. I am still worried that even if pContext is initialized this new instance of the renderer class will still hit me with the classic and all too familiar "can't use static method in non-static context"
    • Hello, I am learning how to create Multipart Entities and I tried creating a PartEntity based on the EnderDragonPart code. However, when I tested summoning the entity in the game, the PartEntity appeared at position x 0, y 0, z 0 within the game. I tried to make it follow the main entity, and after testing again, the part entity followed the main entity but seemed to teleport back to x 0, y 0, z 0 every tick (I'm just guessing). I don't know how to fix this can someone help me? My github https://github.com/SteveKK666/Forge-NewWorld-1.20.1/tree/master/src/main/java/net/kk/newworldmod/entity/custom Illustration  https://drive.google.com/file/d/157SPvyQCE8GcsRXyQQkD4Dyhalz6LjBn/view?usp=drive_link Sorry for my English; I’m not very good at it. 
    • its still crashing with the same message
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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