Jump to content

Recommended Posts

Posted (edited)

Hello, I'm trying to create a custom RenderType for my block, using a custom lightmap LightmapStateCustom

 

object RenderTypes {
    private val SHADE_ENABLED = RenderState.ShadeModelState(true)
    private val LIGHTMAP_ENABLED = LightmapStateCustom()
    private val BLOCK_SHEET_MIPPED = RenderState.TextureState(AtlasTexture.LOCATION_BLOCKS_TEXTURE, false, true)

    val SOLID2: RenderType = RenderType.makeType("solid2", DefaultVertexFormats.BLOCK, 7, 2097152, true, false, RenderType.State.getBuilder().shadeModel(SHADE_ENABLED).lightmap(LIGHTMAP_ENABLED).texture(BLOCK_SHEET_MIPPED).build(true))
}

 

For now the only methods LightmapStateCustom overrides are `equals(other)` and `hashCode()` (`RenderType.makeType` would otherwise return an existing RenderType) so the RenderType is logically identical to SOLID, but the block does not render (as you can see on the screenshot below)

 

x9llQ0N.png

Edited by Alex Sim
Posted

Howdy 

I'm not sure I understand what you're trying to do.

If you make a custom render type for your block, you need to render those blocks yourselves manually.

 

Minecraft renders blocks as follows:

1) Creates a render buffer based on SOLID. Look for all blocks which have SOLID render layer; call their rendering methods to write to the SOLID render buffer

2) Create a render buffer based on CUTOUT.Look for all blocks which have CUTOUT render layer; call their rendering methods to write to the CUTOUT render buffer

3) CUTOUTMIPPED

4) TRANSLUCENT

 

Just because you've given your block a custom RenderType, doesn't mean that vanilla will create a suitable render buffer for it.  If your render type doesn't match the four vanilla block render types, it won't get drawn at all.  If it does match a vanilla render type (because you have done something tricky with equals()) then it will be rendered with the vanilla render type, not your custom render type.

 

-TGG

 

 

Posted
23 minutes ago, TheGreyGhost said:

Howdy 

I'm not sure I understand what you're trying to do.

If you make a custom render type for your block, you need to render those blocks yourselves manually.

 

Minecraft renders blocks as follows:

1) Creates a render buffer based on SOLID. Look for all blocks which have SOLID render layer; call their rendering methods to write to the SOLID render buffer

2) Create a render buffer based on CUTOUT.Look for all blocks which have CUTOUT render layer; call their rendering methods to write to the CUTOUT render buffer

3) CUTOUTMIPPED

4) TRANSLUCENT

 

Just because you've given your block a custom RenderType, doesn't mean that vanilla will create a suitable render buffer for it.  If your render type doesn't match the four vanilla block render types, it won't get drawn at all.  If it does match a vanilla render type (because you have done something tricky with equals()) then it will be rendered with the vanilla render type, not your custom render type.

 

-TGG

 

 

 

Ok thanks for the info, how would I go about it tho?

 

After a little bit of digging i found out WorldRenderer calls renderBlockLayer for each block RenderType inside the updateCameraAndRender method, is it possible to render my blocks without changing vanilla code?

Posted

Hi

Nothing easy springs to mind; if you only have a few of your blocks in the world at any one time then a TileEntityRenderer will do it.  Alternatively you could render them in RenderWorldLastEvent with your own caching + chunk-culling logic but that may have side effects with translucent textures.

 

The first thing I would personally try would be to replace WorldRenderer with a derived class (will require reflection)- at the cost of being pretty fragile and perhaps making your mod incompatible with others.  Other folks have used Reflection and asm to locate and overwrite the byte code to insert a call to a new method at the desired location - that's getting very arcane and perhaps not worth the trouble.

 

There might be other ways to do it if you have other mods installed (perhaps Optifine or similar provides an alternative mechanism for what you want to do)

 

-TGG

Posted
On 5/12/2020 at 12:10 PM, TheGreyGhost said:

Other folks have used Reflection and asm to locate and overwrite the byte code to insert a call to a new method at the desired location

Is it possible to learn this power?

Posted
3 hours ago, Alex Sim said:

Is it possible to learn this power?

Not from a Jedi.

Just wondering, but what is the specific purpose of your custom render type? It seems you just want a custom lightmap, but it would help to know your reasons since there might be safer alternatives.

I'm eager to learn and am prone to mistakes. Don't hesitate to tell me how I can improve.

Posted
Just now, imacatlolol said:

Not from a Jedi.

Just wondering, but what is the specific purpose of your custom render type? It seems you just want a custom lightmap, but it would help to know your reasons since there might be safer alternatives.

I was just experimenting for now but my (probably unreachable) goal is to light every pixel differently (maybe using the alpha level) like so:

 

68747470733a2f2f7062732e7477696d672e636f

Posted
11 minutes ago, Alex Sim said:

I was just experimenting for now but my (probably unreachable) goal is to light every pixel differently (maybe using the alpha level) like so

I see! That would certainly be achievable without needing a custom render type or lightmap.

In this case, you would want to make a custom IModelLoader and model to use with your block JSONs. See MultiLayerModel and its usages for roughly what that process would be.

Applied Energistics actually achieved this effect, but their repo is outdated and most of the actual code no longer applies. It's still a good reference for how you could try implementing it yourself if you get stumped. Just take a look at the charged certus quartz ore.

I'm eager to learn and am prone to mistakes. Don't hesitate to tell me how I can improve.

Posted (edited)
27 minutes ago, imacatlolol said:

I see! That would certainly be achievable without needing a custom render type or lightmap.

In this case, you would want to make a custom IModelLoader and model to use with your block JSONs. See MultiLayerModel and its usages for roughly what that process would be.

Applied Energistics actually achieved this effect, but their repo is outdated and most of the actual code no longer applies. It's still a good reference for how you could try implementing it yourself if you get stumped. Just take a look at the charged certus quartz ore.

 

Thanks, that's very helpful, I basically have to do something like this, definitely way easier than whatever tf I was trying to do

Edited by Alex Sim
Posted (edited)
On 5/12/2020 at 12:10 PM, TheGreyGhost said:

Other folks have used Reflection and asm to locate and overwrite the byte code to insert a call to a new method at the desired location

My quarantine fueled boredom led my to try this anyway (would be useful for other purposes in my mod)

So I made an utility class that uses Kotlin (1.4) extension functions, here is the Kotlin class on pastebin

 

The methods to use are `addMethodAfter`, `addMethodBefore`, `replaceMethod` and `replaceMethodOrFallback`

It's pretty small and should be easy enough to convert it to Java

Here is an usage example (I call it from my mod's constructor):

 

/**
 * Replaces animateTick so that it does nothing (fire particles not spawned) if in the Glacia dimension
 * Otherwise fallback to default method
**/
WallTorchBlock::class.replaceMethodOrFallback(WallTorchBlock::animateTick) {(_, world) ->
    if ((world as World).dimension?.type != Glacia.DIMENSION.type) RedefineUtils.fallback()
}

 

Edited by Alex Sim
Posted
13 minutes ago, diesieben07 said:

...

Please don't write jar mods in Java / Kotlin / JVM languages and don't use the instrumentation stuff. I don't even know how you expect that to work outside the development environment.

If you must, use Forge's coremod system.

I use Johnrengelman's shadowJar plugin to embed the libraries I use in my mod (and rename the base package), including the Kotlin runtime

You're right about the instrumentation stuff though, it apparently doesn't work outside the dev environment ?

Posted (edited)
2 hours ago, diesieben07 said:

...

Please don't write jar mods in Java / Kotlin / JVM languages and don't use the instrumentation stuff. I don't even know how you expect that to work outside the development environment.

If you must, use Forge's coremod system.

BTW correct me if I'm wrong but the only issue here seems to be the attach library, if there was a way to use it in JRE (I'm open to suggestions) the rest would probably work

Edited by Alex Sim
Posted (edited)
18 minutes ago, diesieben07 said:

No.

You should not go around the coremod system that is in place. Coremods are intentionally very limited.

Should or could? Sorry if I sound insistent but I don't see what's the issue. Aside from practical ones (whether I could, and I seem to be one dll away from being able to), why should I not?

My boredom knows no "should"

Edited by Alex Sim
Posted
2 minutes ago, diesieben07 said:

Coremods need to load in a very early stage of the game. In a different classloader than normal mods.

ClassPool.getDefault().apply {appendClassPath(LoaderClassPath(Thread.currentThread().contextClassLoader))}

This seems to work on non-dev-environment Minecraft, it used to throw javassist.NotFoundException without it;

But you probably already know why this won't work and crush my hopes and dreams ?

Posted
3 minutes ago, diesieben07 said:

I don't know how you expect this to work.

Mods load way after Minecraft classes are already loaded. There is no way to transform them then.

Doesn't redefineClasses also retransform classes?

 

public class Hello {
    public int helloWorld() {
        LogManager.getLogger().log(Level.INFO, "Hello World")
    }
}

init { //Based on my tests
    val hello = Hello()
    hello.helloWorld() //Prints "Hello World"
    Hello::class.addMethodAfter(Hello::helloWorld) {
        LogManager.getLogger().log(Level.INFO, "Goodbye World")
    }
    hello.helloWorld() //Prints "Hello World", then "Goodbye World"
}

 

I cannot add new methods or fields, but what I CAN do is change an existing method's bytecode, which is exactly what I'm doing (if you look at my source I found a little workaround to call my local variable (functional interface) by creating a new static class at runtime)

Posted (edited)
2 hours ago, diesieben07 said:

You are abusing this API. This is not what the JVM's instrumentation API is designed for.

 

Please use Forge's coremods.

Maybe, but that's exactly what the Javassist library is designed for: to assist me raping the JVM

 

Jokes aside, this would allow me to retain the old logic for a method on top of mine, and also possibly be compatible with any other hypothetical mod that would use the same approach (as if). I'm honestly not sure whether that's possible with coremods, but as far as I know two mods replacing the same class will conflict with each other

 

If that's not the case I'll look into coremods

Edited by Alex Sim
  • Guest locked this topic
Guest
This topic is now closed to further replies.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • 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() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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