Jump to content

[1.10.2+] [!UNSOLVED!] Custom World Generator does nothing or wrong stuff


Recommended Posts

Posted

Hi,

 

I'm currently writing a complete world generator from scratch using OpenSimplexNoise, Minecraft 1.10.2 and Forge 12.18.1.2073 with Mappings snapshot_20160823.

 

Now I ran into a problem:

 

When I click on "Create New World" I can see the loading screen, but after that nothing happens.... It just freezes... Even when I click on the red "X" from the window nothing happens anymore.... and Windows does not show that the window isn't reacting anymore (I can even move the window... just not close it without task manager).

The problem now: It does nothing... just stops doing anything in the creating world process... no error or crash-log.

 

Here is the code:

[spoiler=WorldType]

public class PrimevalWorldType extends WorldType {

private static PrimevalChunkManager chunkManager;
public static TerrainGenerator terrainGenerator;

public PrimevalWorldType(String name) {
	super(name);
}

@Override
public BiomeProvider getBiomeProvider(World world) {
	if(world.provider.getDimension() == 0) {
		if(chunkManager == null) {
			chunkManager = new PrimevalChunkManager(Biomes.PLAINS);
		}
		return chunkManager;
	}
	return super.getBiomeProvider(world);
}

@Override
public IChunkGenerator getChunkGenerator(World world, String generatorOptions) {
	if(world.provider.getDimension() == 0) {
		if(terrainGenerator == null) {
			terrainGenerator = new TerrainGenerator(world, world.getSeed());

			return terrainGenerator;
		}
	}

	return super.getChunkGenerator(world, generatorOptions);
}

@Override
public float getCloudHeight() {
	return 256.f;
}
}

 

[spoiler=ChunkManager]

public class PrimevalChunkManager extends BiomeProvider {

    /** The biome generator object. */
    private final Biome biome;

    public PrimevalChunkManager(Biome biomeIn)
    {
        this.biome = biomeIn;
    }

    /**
     * Returns the biome generator
     */
    public Biome getBiome(BlockPos pos)
    {
        return this.biome;
    }

    /**
     * Returns an array of biomes for the location input.
     */
    public Biome[] getBiomesForGeneration(Biome[] biomes, int x, int z, int width, int height)
    {
        if (biomes == null || biomes.length < width * height)
        {
            biomes = new Biome[width * height];
        }

        Arrays.fill(biomes, 0, width * height, this.biome);
        return biomes;
    }

    /**
     * Gets biomes to use for the blocks and loads the other data like temperature and humidity onto the
     * WorldChunkManager.
     */
    public Biome[] getBiomes(@Nullable Biome[] oldBiomeList, int x, int z, int width, int depth)
    {
        if (oldBiomeList == null || oldBiomeList.length < width * depth)
        {
            oldBiomeList = new Biome[width * depth];
        }

        Arrays.fill(oldBiomeList, 0, width * depth, this.biome);
        return oldBiomeList;
    }

    /**
     * Gets a list of biomes for the specified blocks.
     */
    public Biome[] getBiomes(@Nullable Biome[] listToReuse, int x, int z, int width, int length, boolean cacheFlag)
    {
        return this.getBiomes(listToReuse, x, z, width, length);
    }

    @Nullable
    public BlockPos findBiomePosition(int x, int z, int range, List<Biome> biomes, Random random)
    {
        return biomes.contains(this.biome) ? new BlockPos(x - range + random.nextInt(range * 2 + 1), 0, z - range + random.nextInt(range * 2 + 1)) : null;
    }

    /**
     * checks given Chunk's Biomes against List of allowed ones
     */
    public boolean areBiomesViable(int x, int z, int radius, List<Biome> allowed)
    {
        return allowed.contains(this.biome);
    }
}

 

[spoiler=TerrainGenerator]

public class TerrainGenerator implements IChunkGenerator {

private Random random;
private World world;
private OpenSimplexNoise simplex;

public TerrainGenerator(World world, long seed) {
	this.world = world;
	this.random = new Random(seed);
	this.simplex = new OpenSimplexNoise(seed);
}

@Override
public Chunk provideChunk(int x, int z) {
	random.setSeed((long) x * 341873128712l + (long) z * 132897987541l);
	ChunkPrimer primer = new ChunkPrimer();

	double noise = 0;

	for(int i = 0; i < 16; i++)
		for(int y = 0; i < 16; y++)
			noise = generateNewNoise(8, i, y, .5, 1);

	this.generateTerrain(x, z, primer, noise);

	// store in the process pile
	Chunk chunk = new Chunk(this.world, primer, x, z);

	chunk.generateSkylightMap();

	Biome[] abiome = this.world.getBiomeProvider().getBiomes((Biome[])null, x * 16, z * 16, 16, 16);
        byte[] abyte = chunk.getBiomeArray();

        for (int i1 = 0; i1 < abyte.length; ++i1)
        {
            abyte[i1] = (byte)Biome.getIdForBiome(abiome[i1]);
        }

        chunk.generateSkylightMap();
        
	return chunk;
}

private double generateNewNoise(int iterations, int x, int z, double persistence, double scale) {
	double maxAmp = 0;
	double amp = 1;
	double freq = scale;
	double noise = 0;

	// add successively smaller, higher-frequency terms
	// each iteration is called an octave, because it is twice the frequency of the iteration before it
	for(int i = 0; i < iterations; ++i) { // iterations = number of octaves
		for(int y = 1; y < 230; y++) {
			noise += simplex.eval(x * freq, y * freq, z * freq) * amp;
			maxAmp += amp;
			amp += 1/(2^iterations); //*= persistence;
			freq *=  2;
		}
	}

	// take the average value of the iterations
	noise /= maxAmp;

	// normalize the result
	//noise = noise * (high - low) / 2 + (high + low) / 2;

	return noise;
}

public void generateTerrain(int x, int z, ChunkPrimer primer, double noise) {
	for(int i = 0; i < 16; i++) { // x-axis
		for(int y = 0; i < 16; y++) { // z-axis
			for(int k = 0; k < 256; k++) { // y-axis
				if(k > noise) {
					if(k < 63)
						primer.setBlockState(i, k, y, Blocks.WATER.getDefaultState());
					else
						primer.setBlockState(i, k, y, Blocks.AIR.getDefaultState());
				} else
					primer.setBlockState(i, k, y, Blocks.STONE.getDefaultState());
			}
		}
	}
}

@Override
public void populate(int x, int z) {
	// TODO Auto-generated method stub

}

@Override
public boolean generateStructures(Chunk chunkIn, int x, int z) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public List<SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public void recreateStructures(Chunk chunkIn, int x, int z) {
	// TODO Auto-generated method stub

}
}

 

 

For anyone who now thinks the generateNewNoise method does not work... it works perfectly. I tested the whole noise generating stuff outside of MC in a small test project and got some nice looking bitmaps out of it. Only when trying to put that whole stuff into the MC "API" it stops working... and I get nothing...

 

I haven't written much extra code yet, because I first want to have it working and see how the world looks and modify it until it looks nice before I want to add biomes and GenLayer stuff and a lot of other stuff, because then it's easier to fix problems and find them and change stuff as it would be when having a dozen of classes and thousands of lines of code.....

 

I hope someone can help me with this complex stuff... And I would like any explanation which is possible, because it took me even some month to get the knowledge to get it working outside of Minecraft (even when I don't know the math in the OpenSimplexNoise algorythm).

 

Thx in advance.  ;)

Bektor

 

EDIT:

Now it generates only water from layer 1 to about 63 and everything above is air and layer 0 is stone. So no hills and just water...

 

Here is the updated code:

[spoiler=TerrainGenerator]

public class TerrainGenerator implements IChunkGenerator {

private Random random;
private World world;
private OpenSimplexNoise simplex;

private double[] noise = new double[256];

public TerrainGenerator(World world, long seed) {
	this.world = world;
	this.random = new Random(seed);
	this.simplex = new OpenSimplexNoise(seed);
}

@Override
public Chunk provideChunk(int x, int z) {
	random.setSeed((long) x * 341873128712l + (long) z * 132897987541l);
	ChunkPrimer primer = new ChunkPrimer();

	for(int i = 0; i < 16; i++)
		for(int y = 0; y < 16; y++) {
			noise[i * 16 + y] = 0.d;
			noise[i * 16 + y] = generateNewNoise(8, i, y, .5, 1);
		}

	this.generateTerrain(x, z, primer, noise);

	// store in the process pile
	Chunk chunk = new Chunk(this.world, primer, x, z);

	chunk.generateSkylightMap();

	Biome[] abiome = this.world.getBiomeProvider().getBiomes((Biome[])null, x * 16, z * 16, 16, 16);
        byte[] abyte = chunk.getBiomeArray();

        for (int i1 = 0; i1 < abyte.length; ++i1)
        {
            abyte[i1] = (byte)Biome.getIdForBiome(abiome[i1]);
        }

        chunk.generateSkylightMap();
        
	return chunk;
}

private double generateNewNoise(int iterations, int x, int z, double persistence, double scale) {
	double maxAmp = 0;
	double amp = 1;
	double freq = scale;
	double noise = 0;

	// add successively smaller, higher-frequency terms
	// each iteration is called an octave, because it is twice the frequency of the iteration before it
	for(int i = 0; i < iterations; ++i) { // iterations = number of octaves
		for(int y = 1; y < 230; y++) {
			noise += simplex.eval(x * freq, y * freq, z * freq) * amp;
			maxAmp += amp;
			amp += 1/(2^iterations); //*= persistence;
			freq *=  2;
		}
	}

	// take the average value of the iterations
	noise /= maxAmp;

	// normalize the result
	//noise = noise * (high - low) / 2 + (high + low) / 2;

	return noise;
}

public void generateTerrain(int x, int z, ChunkPrimer primer, double[] noise) {
	int height;
	for(int i = 0; i < 16; i++) { // x-axis
		for(int y = 0; y < 16; y++) { // z-axis
			height = (int) noise[y * 16 + i];
			for(int k = 0; k < 256; k++) { // y-axis
				if(k > height) {
					if(k < 63)
						primer.setBlockState(i, k, y, Blocks.WATER.getDefaultState());
					else
						primer.setBlockState(i, k, y, Blocks.AIR.getDefaultState());
				} else
					primer.setBlockState(i, k, y, Blocks.STONE.getDefaultState());
			}
		}
	}
}

@Override
public void populate(int x, int z) {
	// TODO Auto-generated method stub

}

@Override
public boolean generateStructures(Chunk chunkIn, int x, int z) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public List<SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public void recreateStructures(Chunk chunkIn, int x, int z) {
	// TODO Auto-generated method stub

}
}

 

Developer of Primeval Forest.

Posted

I can't help you with the world generation itself, but I suggest you use your IDE's debugger to pause the process when Minecraft freezes and see what it's executing. This may give you a better idea of what's causing the freezes.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

I can't help you with the world generation itself, but I suggest you use your IDE's debugger to pause the process when Minecraft freezes and see what it's executing. This may give you a better idea of what's causing the freezes.

Ok.

 

	double noise = 0; // breakpoint 1

	for(int i = 0; i < 16; i++)
		for(int y = 0; i < 16; y++)
			noise = generateNewNoise(8, i, y, .5, 1);

	this.generateTerrain(x, z, primer, noise); // breakpoint 2

 

When I press F8 in eclipse to execute the code between breakpoint 1 and 2 it just stops... So I can stop then the complete application because it jumps out of the debug stuff (even when I click the button to run to the next breakpoint).

 

So I think the problem is somewhere there in some code which works fine outside of Minecraft.

Developer of Primeval Forest.

Posted

	double noise = 0; // breakpoint 1

	for(int i = 0; i < 16; i++)
		for(int y = 0; i < 16; y++)
			noise = generateNewNoise(8, i, y, .5, 1);

	this.generateTerrain(x, z, primer, noise); // breakpoint 2

 

Double check the termination condition in your nested for-loop.

Posted

Double check the termination condition in your nested for-loop.

 

I see it.  Tee hee.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Ok, I fixed those mistakes now.

But for some reason it generates now only water... from level 1 to about 63 it generates only water and above only air.

Level 0 is one layer of stone.

 

There aren't even any hills etc. :(

For the updated code, pls look at the top of the thread. Edited the main post there. ;)

Developer of Primeval Forest.

Posted

noise[i * 16 + y] = 0.d;
noise[i * 16 + y] = generateNewNoise(8, i, y, .5, 1);

 

 

First line is unnecessary, you're already overwriting whatever is in there with the return of generateNewNoise.

 

 

The generateTerrain function should be returning the modified ChunkPrimer, you're using it like a C style pointer, which doesn't work in Java, there are only references.

Posted

noise[i * 16 + y] = 0.d;
noise[i * 16 + y] = generateNewNoise(8, i, y, .5, 1);

 

 

First line is unnecessary, you're already overwriting whatever is in there with the return of generateNewNoise.

 

 

The generateTerrain function should be returning the modified ChunkPrimer, you're using it like a C style pointer, which doesn't work in Java, there are only references.

Ok, I changed it now with returning the ChunkPrimer from generateTerrain , but nothing changed. The world looks the same as before.

Developer of Primeval Forest.

Posted

Ok, I found something interesting out:

 

Output of the test project:

WP9mqZN

 

Output of the same noise function in Minecraft:

7nuQkdG

 

Hm... anyone who knows how to fix this and why it is working outside of Minecraft, but not inside of Minecraft??????

 

 

Developer of Primeval Forest.

Posted

EDIT: Wait, never mind, this shouldn't make a difference.

 

Might be wrong here, but are you sure

height = (int) noise[y * 16 + i];

isn't supposed to be

height = (int) noise[i * 16 + y];

Posted

EDIT: Wait, never mind, this shouldn't make a difference.

 

Might be wrong here, but are you sure

height = (int) noise[y * 16 + i];

isn't supposed to be

height = (int) noise[i * 16 + y];

Well... not quite sure about it. :P

Just did that to store the noise in an array, because I have to store it somewhere when I change the noise variable again... so I used here an array (while I used in my Test Project just a noise value and saved the noise value result direclty to the picture before recalculating that value for the next pixel).

But either way... if you do the first thing or the second thing of the code you posted... it changes nothing.. It just changes the location of where the calculated noise variable is saved. ;)

 

EDIT: Ok, I just found out that it seems to be a problem with the array itself. Without an array it's working, but I don't know any solution which would work to implement such a thing in Minecraft and with an array it seems to be that the

generateNewNoise

method is always putting out the same value for a reason I don't know.

Developer of Primeval Forest.

Posted

In the generateNewNoise method:

 

amp += 1/(2^iterations); //*= persistence;

 

I might be wrong in my assumption, but I think you are meaning to do 2iterations. If so, that's not the Java exponent operator. That's the bitwise xor operator.

Use Math.pow(2, iterations) instead.

Posted

In the generateNewNoise method:

 

amp += 1/(2^iterations); //*= persistence;

 

I might be wrong in my assumption, but I think you are meaning to do 2iterations. If so, that's not the Java exponent operator. That's the bitwise xor operator.

Use Math.pow(2, iterations) instead.

Well, even when using Math.pow(2, iterations), the result is the same.

Developer of Primeval Forest.

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.