Jump to content

any simple cross-side methods in the Forge framework?


JoeStrout

Recommended Posts

It seems to me there are a couple of common situations that many mod developers may face, with respect to the whole client/server side issue:

  1. You have code on the client side that needs to spawn an entity (which must be done on the server side).
  2. You have code on the client side that wants to trigger an explosion (which should also be done on the server side).
  3. Or more generally, you have code on the client side that wants to modify the world, e.g. change blocks (which also must be done on the server).

These are sufficiently general and common cases that a library could do it for us — that is, prepare a packet, send it to the server, and have the server catch it and do the appropriate thing.

Before I start in on such utility code myself, are there any cases where the framework already does something like this for us?  Where?

If not, are there any common open-source solutions to this already written?

 

Link to comment
Share on other sites

Yes, it is called minecraft.

You seem to be under the inital false understanding that any of that should be triggered by the client doing anything.

Unless you're explicitly doing it from a GUI, and even in that case you should use the generic button click handlers and the like to talk to the server.

None of this logic should touch any client side code.

I do Forge for free, however the servers to run it arn't free, so anything is appreciated.
Consider supporting the team on Patreon

Link to comment
Share on other sites

Well as a concrete example of situation 1, I've got some custom mouse-button handling (and yes, I tried the built-in click handlers on the Item class, but (1) they didn't do what I need, and (2) those handlers also run on the client thread).  And in response to that mouse input — which obviously the server doesn't know anything about — I need to spawn a projectile.

I find it hard to believe that this situation is unique.

So I'm going to interpret your answer as "no" (there is no built-in support for that in the framework), and "no" (you don't know any standard open-source solution for it).

No big deal — I've already got the necessary networking code implemented for one case, and it won't take long to add the others.  Just wanted to avoid reinventing the wheel if there was a well-oiled wheel already available.

 

(But I do hear and respect your point that in most cases, Minecraft is already interpreting all the client input and sending higher-level events to the server, and we should our custom logic on the server in response to those events as much as possible.)

Link to comment
Share on other sites

Hey,

 

The first two should really be done from the server (spawning an entity client-side can lead to phantom entities... and running an explosion client side lead to phantom client-side holes since the random number generator on the server doesn't always break the same blocks). If you have something spawning a mob or explosion from the client, it would probably be best to send a custom packet over to the server with info about what mob you want to spawn or about the explosion. I don't think there are vanilla packets for that, but I could be wrong.

 

The third has a vanilla packet. I remember recently using it to create a hammer-like tool that has some custom block-breaking logic. Check out tryHarvestBlock in PlayerInteractionManager, it's sending a SPacketBlockChange packet on line 337 or so.

  • Like 1
Link to comment
Share on other sites

Thank you.

In case it's useful to anyone, here's the networking code I came up with (based on the docs) to create an explosion or spawn a projectile on the server.  (Unfortunately the "spawn a projectile" code is not generic — it's tied to a particular class, in this case a custom Throwable subclass called EntitySpell.  But perhaps it will be useful as sample code anyway.)

 

package net.strout.wizarding;

import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.math.*;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.*;
import net.minecraftforge.fml.relauncher.Side;

public class ClientToServerBridge {

	private static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(ModMain.MODID);
	private static int nextHandlerRegistrationID = 0;
	private static boolean initialized;
	
	public static class TriggerExplosionMessage implements IMessage {
		// A default constructor is always required
		public TriggerExplosionMessage() {}

		private BlockPos position;
		private float strength;
		private boolean smoke;
		
		public TriggerExplosionMessage(BlockPos position, float strength, boolean smoke) {
			this.position = position;
			this.strength = strength;
			this.smoke = smoke;
		}

		@Override public void toBytes(ByteBuf buf) {
			buf.writeInt(position.getX());
			buf.writeInt(position.getY());
			buf.writeInt(position.getZ());
			buf.writeFloat(strength);
			buf.writeBoolean(smoke);
		}

		@Override public void fromBytes(ByteBuf buf) {
			position = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
			strength = buf.readFloat();
			smoke = buf.readBoolean();
		}
	}
	
	// The params of the IMessageHandler are <REQUEST, REPLY>
	// This means that the first param is the packet you are receiving, and the second is the packet you are returning.
	// The returned packet can be used as a "response" from a sent packet.
	public static class TriggerExplosionHandler implements IMessageHandler<TriggerExplosionMessage, IMessage> {
		@Override public IMessage onMessage(TriggerExplosionMessage message, MessageContext ctx) {
			System.out.println("Received TriggerExplosionMessage");
			// This is the player the packet was sent to the server from
			EntityPlayerMP serverPlayer = ctx.getServerHandler().player;
			// Execute the action on the main server thread by adding it as a scheduled task
			WorldServer world = serverPlayer.getServerWorld();
			if (!world.isBlockLoaded(message.position)) return null;
			System.out.println("Scheduling explosion on main thread");
			world.addScheduledTask(() -> {
				System.out.println("Creating explosion");
				world.createExplosion(serverPlayer, 
						message.position.getX(),
						message.position.getY(),
						message.position.getZ(),
						message.strength, message.smoke);
			});
			// No response packet
			return null;
		}
	}
	
	
	public static class SpawnSpellMessage implements IMessage {
		// A default constructor is always required
		public SpawnSpellMessage() {}

		private Vec3d position;
		private Vec3d direction;
		
		public SpawnSpellMessage(Vec3d position, Vec3d direction) {
			this.position = position;
			this.direction = direction;
		}

		@Override public void toBytes(ByteBuf buf) {
			buf.writeFloat((float)position.x);
			buf.writeFloat((float)position.y);
			buf.writeFloat((float)position.z);
			buf.writeFloat((float)direction.x);
			buf.writeFloat((float)direction.y);
			buf.writeFloat((float)direction.z);
		}

		@Override public void fromBytes(ByteBuf buf) {
			position = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat());
			direction = new Vec3d(buf.readFloat(), buf.readFloat(), buf.readFloat());
		}
	}
	
	// The params of the IMessageHandler are <REQUEST, REPLY>
	// This means that the first param is the packet you are receiving, and the second is the packet you are returning.
	// The returned packet can be used as a "response" from a sent packet.
	public static class SpawnSpellHandler implements IMessageHandler<SpawnSpellMessage, IMessage> {
		@Override public IMessage onMessage(SpawnSpellMessage message, MessageContext ctx) {
			System.out.println("Received SpawnSpellMessage");
			// This is the player the packet was sent to the server from
			EntityPlayerMP serverPlayer = ctx.getServerHandler().player;
			// Execute the action on the main server thread by adding it as a scheduled task
			WorldServer world = serverPlayer.getServerWorld();
			if (!world.isBlockLoaded(new BlockPos(message.position))) return null;
			System.out.println("Scheduling spawning on main thread");
			world.addScheduledTask(() -> {
				System.out.println("Spawning spell");
				EntitySpell.Spawn(world, serverPlayer, message.position, message.direction);
			});
			// No response packet
			return null;
		}
	}
	
	
	//--------------------------------------------------------------------------------
	// Public API
	//--------------------------------------------------------------------------------
	
	// Initialize: call this once on startup (for example, in your pre-init handler)
	// on both client and server.
	public static void Initialize() {
		assert(!initialized);
		INSTANCE.registerMessage(TriggerExplosionHandler.class, TriggerExplosionMessage.class, nextHandlerRegistrationID++, Side.SERVER);
		INSTANCE.registerMessage(SpawnSpellHandler.class, SpawnSpellMessage.class, nextHandlerRegistrationID++, Side.SERVER);
		System.out.println("ClientToServer module registered " + nextHandlerRegistrationID + " message handlers");
		initialized = true;
	}
	
	// TriggerExplosion: call to trigger an explosion on the server from client code.
	public static void TriggerExplosion(BlockPos position, float strength, boolean smoke) {
		assert(initialized);
		System.out.println("Sending TriggerExplosionMessage message to server");
		INSTANCE.sendToServer(new TriggerExplosionMessage(position, strength, smoke));		
	}
	
	// SpawnSpell: call to spawn an EntitySpell on the server from client code.
	public static void SpawnSpell(Vec3d position, Vec3d direction) {
		assert(initialized);
		System.out.println("Sending SpawnSpell message to server");
		INSTANCE.sendToServer(new SpawnSpellMessage(position, direction));				
	}
}

 

Edited by JoeStrout
added link to docs
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



×
×
  • Create New...

Important Information

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