Jump to content

Recommended Posts

Posted

Hello Everyone,

With the new packet system combined with my poor inexperience with packets, I can't figure out how to to send an integer from a gui to its tile entity. I'll put all the code here:

 

The method in the gui that should sent a packet:

SimpaddsBase.packetPipeline.sendToAll(new PacketTank(outputSelected, tileTank.xCoord, tileTank.yCoord, tileTank.zCoord));

 

The packet handler:

package mardiff.simpadds.packets;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import mardiff.simpadds.tileentity.TileFluidTank;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import cpw.mods.fml.common.FMLCommonHandler;

public class PacketTank extends AbstractPacket {

int output, x, y, z;

public PacketTank(){
}

public PacketTank(int output, int x, int y, int z){
	this.output = output;
	this.x = x;
	this.y = y;
	this.z = z; 
}

@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {
	buffer.writeInt(output);
	buffer.writeInt(x);
	buffer.writeInt(y);
	buffer.writeInt(z);
}

@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {
	output = buffer.readInt();
	x = buffer.readInt();
	y = buffer.readInt();
	z = buffer.readInt();
}

@Override
public void handleClientSide(EntityPlayer player) {
	System.out.println("ran");
}

@Override
public void handleServerSide(EntityPlayer player) {
	System.out.println("ranPacket");

	World world = player.worldObj;

	TileEntity te = world.getTileEntity(x, y, z);

	if (te instanceof TileFluidTank)
	{
		TileFluidTank tft = (TileFluidTank)te;

		tft.output = this.output;

		FMLCommonHandler.instance().getClientToServerNetworkManager().scheduleOutboundPacket(tft.getDescriptionPacket());
	}
}

}

 

The packet pipeline, which is mostly copied from the forge tutorial:

package mardiff.simpadds.packets;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;

import mardiff.simpadds.lib.Reference;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.FMLEmbeddedChannel;
import cpw.mods.fml.common.network.FMLOutboundHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

/**
* Packet pipeline class. Directs all registered packet data to be handled by the packets themselves.
* @author sirgingalot
* some code from: cpw
*/
@ChannelHandler.Sharable
public class PacketPipeline extends MessageToMessageCodec<FMLProxyPacket, AbstractPacket> {

    private EnumMap<Side, FMLEmbeddedChannel> channels;
    private LinkedList<Class<? extends AbstractPacket>> packets = new LinkedList<Class<? extends AbstractPacket>>();
    private boolean isPostInitialised = false;

    /**
     * Register your packet with the pipeline. Discriminators are automatically set.
     *
     * @param clazz the class to register
     *
     * @return whether registration was successful. Failure may occur if 256 packets have been registered or if the registry already contains this packet
     */
    public boolean registerPacket(Class<? extends AbstractPacket> clazz) {
        if (this.packets.size() > 256) {
            // You should log here!!
            return false;
        }

        if (this.packets.contains(clazz)) {
            // You should log here!!
            return false;
        }

        if (this.isPostInitialised) {
            // You should log here!!
            return false;
        }

        this.packets.add(clazz);
        return true;
    }

    // In line encoding of the packet, including discriminator setting
    @Override
    protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {
        ByteBuf buffer = Unpooled.buffer();
        Class<? extends AbstractPacket> clazz = msg.getClass();
        if (!this.packets.contains(msg.getClass())) {
            throw new NullPointerException("No Packet Registered for: " + msg.getClass().getCanonicalName());
        }

        byte discriminator = (byte) this.packets.indexOf(clazz);
        buffer.writeByte(discriminator);
        msg.encodeInto(ctx, buffer);
        FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer.copy(), ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
        out.add(proxyPacket);
    }

    // In line decoding and handling of the packet
    @Override
    protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
        ByteBuf payload = msg.payload();
        byte discriminator = payload.readByte();
        Class<? extends AbstractPacket> clazz = this.packets.get(discriminator);
        if (clazz == null) {
            throw new NullPointerException("No packet registered for discriminator: " + discriminator);
        }

        AbstractPacket pkt = clazz.newInstance();
        pkt.decodeInto(ctx, payload.slice());

        EntityPlayer player;
        switch (FMLCommonHandler.instance().getEffectiveSide()) {
            case CLIENT:
                player = this.getClientPlayer();
                pkt.handleClientSide(player);
                break;

            case SERVER:
                INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
                player = ((NetHandlerPlayServer) netHandler).playerEntity;
                pkt.handleServerSide(player);
                break;

            default:
        }

        out.add(pkt);
    }

    // Method to call from FMLInitializationEvent
    public void initialize() {
        this.channels = NetworkRegistry.INSTANCE.newChannel(Reference.MOD_ID, this);
    }

    // Method to call from FMLPostInitializationEvent
    // Ensures that packet discriminators are common between server and client by using logical sorting
    public void postInitialize() {
        if (this.isPostInitialised) {
            return;
        }

        this.isPostInitialised = true;
        Collections.sort(this.packets, new Comparator<Class<? extends AbstractPacket>>() {

            @Override
            public int compare(Class<? extends AbstractPacket> clazz1, Class<? extends AbstractPacket> clazz2) {
                int com = String.CASE_INSENSITIVE_ORDER.compare(clazz1.getCanonicalName(), clazz2.getCanonicalName());
                if (com == 0) {
                    com = clazz1.getCanonicalName().compareTo(clazz2.getCanonicalName());
                }

                return com;
            }
        });
    }

    @SideOnly(Side.CLIENT)
    private EntityPlayer getClientPlayer() {
        return Minecraft.getMinecraft().thePlayer;
    }

    /**
     * Send this message to everyone.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     */
    public void sendToAll(AbstractPacket message) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to the specified player.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     * @param player  The player to send it to
     */
    public void sendTo(AbstractPacket message, EntityPlayerMP player) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to everyone within a certain range of a point.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     * @param point   The {@link cpw.mods.fml.common.network.NetworkRegistry.TargetPoint} around which to send
     */
    public void sendToAllAround(AbstractPacket message, NetworkRegistry.TargetPoint point) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to everyone within the supplied dimension.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message     The message to send
     * @param dimensionId The dimension id to target
     */
    public void sendToDimension(AbstractPacket message, int dimensionId) {
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);
        this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);
        this.channels.get(Side.SERVER).writeAndFlush(message);
    }

    /**
     * Send this message to the server.
     * <p/>
     * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
     *
     * @param message The message to send
     */
    public void sendToServer(AbstractPacket message) {
        this.channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
        this.channels.get(Side.CLIENT).writeAndFlush(message);
    }
}

 

The abstract packet class, which is entirely copied:

package mardiff.simpadds.packets;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import net.minecraft.entity.player.EntityPlayer;


/**
* AbstractPacket class. Should be the parent of all packets wishing to use the PacketPipeline.
* @author sirgingalot
*/
public abstract class AbstractPacket {

    /**
     * Encode the packet data into the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils})
     *
     * @param ctx    channel context
     * @param buffer the buffer to encode into
     */
    public abstract void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer);

    /**
     * Decode the packet data from the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils})
     *
     * @param ctx    channel context
     * @param buffer the buffer to decode from
     */
    public abstract void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer);

    /**
     * Handle a packet on the client side. Note this occurs after decoding has completed.
     *
     * @param player the player reference
     */
    public abstract void handleClientSide(EntityPlayer player);

    /**
     * Handle a packet on the server side. Note this occurs after decoding has completed.
     *
     * @param player the player reference
     */
    public abstract void handleServerSide(EntityPlayer player);
}

 

The area in my main mod class directed for packets:

public static final PacketPipeline packetPipeline = new PacketPipeline();

@EventHandler
public void initialise(FMLInitializationEvent evt) {
    packetPipeline.initialize();
}

@EventHandler
public void postInitialise(FMLPostInitializationEvent evt) {
    packetPipeline.postInitialize();
}

 

And at this point, I have no idea what method to use in the tile entity, be it onDataPacket or receiveClientEvent. Thanks for reading all this clutter and helping out if you can.

If you really want help, give that modder a thank you.

 

Modders LOVE thank yous.

Posted

Did you register your custom packet class?

public void initialise() {
this.channels = NetworkRegistry.INSTANCE.newChannel(ModInfo.CHANNEL, this);
// add this line:
registerPackets();
}

// and make this method
public void registerPackets() {
registerPacket(YourCustomPacket1.class);
registerPacket(YourCustomPacket2.class);
// ... etc. for all your packet classes
}

Posted

Is there a reason you're not using Packet250CustomPayload?

 

It's super easy.

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

Don't quote me on this, but I don't think Packet250CustomPayload is useful anymore, given the new layout of the network system. It basically requires that you create a custom packet class for each set of data you want to send, as the reading, writing, and processing of the packet is all done internally in the packet class itself now.

 

PacketHandler classes with 20 different handling methods are a thing of the past :P

Posted

Ahhh.  Ok.

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

Don't quote me on this, but I don't think Packet250CustomPayload is useful anymore, given the new layout of the network system. It basically requires that you create a custom packet class for each set of data you want to send, as the reading, writing, and processing of the packet is all done internally in the packet class itself now.

 

PacketHandler classes with 20 different handling methods are a thing of the past :P

 

wasnt there another example though...

at bottom page1 of  http://www.minecraftforge.net/forum/index.php/topic,15403.msg81874.html#msg81874

Noppes did an alternative to the DynamicClassPacket netty handler in the Tutorials .

I am not running it, I'm doing the NettyTut dynamic class,

but the alternative from Noppes looks like the old way jazzed up for 17x

Posted

Sorry for not replying and apparently leaving you all in suspense, but it was just that I needed to register the handler. After that I just had to screw around and delete some things and it works like a charm now. Thanks guys.

If you really want help, give that modder a thank you.

 

Modders LOVE thank yous.

  • 2 weeks later...
Posted

Sorry for not replying and apparently leaving you all in suspense, but it was just that I needed to register the handler. After that I just had to screw around and delete some things and it works like a charm now. Thanks guys.

how did you make the server get the packet?

i'm having a problem with the server doesn't seem to receive the packets i send it (it does not print anything out in console from the server)

 

i use this code when i'm trying to send a packets

 

MainClass.packetPipeline.sendToAll(new TestPacket());

 

i also tryed to change the code to

 

MainClass.packetPipeline.sendToServer(new TestPacket());

 

no reaction from the server at all when i send the packet

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

    • Was launching forge for the first time and it crashed: Processor failed, invalid outputs: /home/frenchy/.local/share/PrismLauncher/libraries/net/minecraft/client/1.20.1-20230612.114412/client-1.20.1-20230612.114412-slim.jar Expected: de86b035d2da0f78940796bb95c39a932ed84834 Actual: a8fb49bc364562847d6e7e6775e3a1b3f6b2bb05 /home/frenchy/.local/share/PrismLauncher/libraries/net/minecraft/client/1.20.1-20230612.114412/client-1.20.1-20230612.114412-extra.jar Expected: 8c5a95cbce940cfdb304376ae9fea47968d02587 Actual: cf941ba69e11f5a9de15d0c319d61854c456a116 No idea why I think it's because I'm on linux or something  
    • Game crashed on launch with:  Processor failed, invalid outputs: /home/user/.local/share/PrismLauncher/libraries/net/minecraft/client/1.20.1-20230612.114412/client-1.20.1-20230612.114412-slim.jar Expected: de86b035d2da0f78940796bb95c39a932ed84834 Actual: a8fb49bc364562847d6e7e6775e3a1b3f6b2bb05 /home/user/.local/share/PrismLauncher/libraries/net/minecraft/client/1.20.1-20230612.114412/client-1.20.1-20230612.114412-extra.jar Expected: 8c5a95cbce940cfdb304376ae9fea47968d02587 Actual: cf941ba69e11f5a9de15d0c319d61854c456a116 No idea why, but im on linux which might matter
    • PixelmonGo est un incroyable serveur Pixelmon disponible grâce à notre launcher en version 1.16.5 Ce serveur accepte les joueurs premiums comme les cracks ! Un gameplay unique vous attend.. Rejoignez nous dès maintenant ! Site: https://pixelmongo.fr/ Launcher: https://pixelmongo.fr/launcher/ Discord: https://discord.gg/pixelmongo Découvrez notre serveur minecraft Pixelmon moddé basé sur un univers mélangeant Minecraft et Pokémon. Plus de 900 Pokémon à capturer ainsi que des fusions unique au serveur, un hôtel des ventes, un monde aventure reproduisant l'aventure de sinnoh, Explorez des donjons de chaque team maléfique au début de votre aventure, accomplissez des quêtes et remportez des récompenses quotidiennes. Revivez vos meilleurs souvenirs Pokémon au sein d'une communauté multijoueur dynamique. Rejoignez le meilleur serveur minecraft pixelmon français des maintenant en téléchargeant notre launcher. Pixelmongo est la référence en serveur pixelmon en France ! Présentation Amenez votre Minecraft dans le monde des Pokémon, ou des Pokémon dans votre monde Minecraft ! Avec Pixelmon, découvrez votre monde Minecraft sous un nouvel angle. Pixelmon est un mod populaire pour Minecraft qui permet aux joueurs d'attraper, d'entraîner et de combattre des Pokémon dans le monde de Minecraft. Développé par un groupe de fans dévoués, le mod ajoute une large gamme de créatures Pokémon au jeu. Il possède des fonctionnalités et des mécanismes uniques qui en font une expérience amusante et engageante pour les joueurs de tous âges. Le mod Pixelmon est disponible pour les mondes Minecraft solo et multijoueur et peut être téléchargé et installé à l'aide de divers lanceurs et modpacks. Une fois installé, les joueurs peuvent explorer le monde et rencontrer des Pokémon dans la nature, se battre avec d'autres entraîneurs et créer leur propre équipe de créatures puissantes. L'une des fonctionnalités clés de Pixelmon est la possibilité de capturer et d'entraîner des Pokémon en utilisant diverses méthodes. Les joueurs peuvent fabriquer des Pokéballs et les utiliser pour capturer des Pokémon sauvages, qui peuvent ensuite être entraînés et améliorés au fil du temps. Chaque Pokémon a des capacités et des mouvements uniques, ce qui rend important pour les joueurs de choisir la bonne équipe de créatures pour chaque combat. Capturez des Pokémons, constituez une équipe, entraînez-les et remportez des combats contre d'autres joueurs ! Dans un univers reprenant les standards du jeu Nintendo original : Dresseurs, centres Pokémon, mais aussi fossiles et matériaux divers. Les Pokémon comme dans le jeu original sont classés par type (Insecte, Ténèbres, Dragon, Électrique, Combat, Feu, Vol, Spectre, Plante, Sol, Glace, Normal, Poison, Psy, Pierre, Acier, Eau), ce qui définira les faiblesses et les spécificités des Pokémons. Par exemple, un Pokémon de type Feu subira deux fois plus de dégâts si l'attaque du Pokémon ennemi est de type Glace. Le mod possède 900 Pokémon différents plus ou moins rares qui apparaîtront en fonction de leur environnement (jour, nuit et biomes). Les Pokémon évoluent en fonction de leur niveau (jusqu'à 100). Plus leur niveau est élevé, plus ils seront forts et auront des attaques plus puissantes. Pour augmenter le niveau de votre Pokémon, et ainsi évoluer, vous devrez combattre d'autres Pokémon et les vaincre. Plus vos adversaires sont forts, plus ils vous rapporteront de l'expérience. Les Pokémons ont également leurs propres statistiques (attaque, défense, vitesse, vitesse d'attaque et vitesse de défense). Ils peuvent également avoir des tailles et des formes différentes, et peuvent occasionnellement vous donner des objets une fois tués. Pour les capturer, vous devrez utiliser des pokéballs, qui selon leur forme seront plus ou moins efficaces. Pixelmon est un mod amusant et engageant pour Minecraft qui ajoute une touche unique et passionnante au jeu. Avec sa large gamme de fonctionnalités et de mécanismes, il offre aux joueurs des possibilités infinies d'exploration et de plaisir, ce qui en fait un choix populaire pour les fans de Minecraft et de Pokemon.  
    • Hi all,  I have the following issue: I'd like to parse some json using gson and rely on the (somewhat new) java record types. This is supported in gson 2.10+. Gson is already a dependency used by minecraft, however it's 2.8.x for 1.19.2 which I'm targeting at the moment. My idea was to include the newer version of the library in my mod and then shadow it so it gets used inside the scope of my mod instead of the older 2.8. This works fine for building the jar: If I decompile my mod.jar, I can see that it's correctly using the shadowed classes. However obviously when using the runClient intellj config, the shadowing doesn't get invoked. Is there any way of invoking shadow when using runClient, or am I on the wrong track and there's a better way of doing this entirely?   Thanks in advance!   Edit: After some further thinking, I've come up with this abomination:   build.gradle // New task for extracting the result of shadowJar into the classes directory // This includes our shadowed gson jar tasks.register("extractShadowJar", Copy) { // Depend on shadowJar so we always use the up to date version of the shadowed content dependsOn shadowJar from(zipTree(shadowJar.archiveFile)) { // filter to copy only our code (and ignore assets, META-INF, etc) // Also copies gson as it gets shadowed into com.oppendev.shadow.gson include "com/**" } duplicatesStrategy(DuplicatesStrategy.INCLUDE) into("$buildDir/classes/java/main") // Extract into the classes directory } // Tell gradle to invoke our new task before executing any java code. This way we ensure that we use the shadowed gson tasks.withType(JavaExec).configureEach { dependsOn(extractShadowJar) } // Shadow config shadowJar { relocate 'com.google.gson', 'com.oppendev.shadow.gson' configurations = [project.configurations.runtimeClasspath] zip64 true dependencies { include(dependency('com.google.code.gson:gson')) } } Is this a reasonable thing to do? Is this completely cursed and I should burn in dev ops hell? Is there a better way to do this? Feel free to grill me in the replies
    • Yep I did upgrade just because it showed me a new version available.  I'll redownload the mod list and make sure anything works.  Thanks!
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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