Search in sources :

Example 1 with PacketSender

use of net.fabricmc.fabric.api.networking.v1.PacketSender in project map-canvas-api by Patbox.

the class TestMod method onInitialize.

public void onInitialize() {
    CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> {
        dispatcher.register(literal("test").then(argument("dir", IntegerArgumentType.integer(0, Direction.values().length)).then(argument("rot", IntegerArgumentType.integer(0, 4)).executes(this::test))));
        dispatcher.register(literal("setfps").then(argument("fps", IntegerArgumentType.integer(1)).executes((ctx) -> {
            this.msPerFrame = 1000 / IntegerArgumentType.getInteger(ctx, "fps");
            return 0;
        })));
        dispatcher.register(literal("saveimage").executes((ctx -> {
            var image = CanvasUtils.toImage(this.lastImage);
            try {
                ImageIO.write(image, "png", Files.newOutputStream(FabricLoader.getInstance().getGameDir().resolve("output.png"), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        })));
    });
    ServerPlayConnectionEvents.JOIN.register((ServerPlayNetworkHandler handler, PacketSender sender, MinecraftServer server) -> {
        this.canvas.addPlayer(handler);
    });
    ServerPlayConnectionEvents.DISCONNECT.register((ServerPlayNetworkHandler handler, MinecraftServer server) -> {
        this.canvas.removePlayer(handler);
    });
    try {
        var image = ImageIO.read(new URL("https://cdn.discordapp.com/attachments/552976908070027270/854881217950122024/tinypotato.png"));
        for (int i = 0; i < 10; i++) {
            long start = System.currentTimeMillis();
            this.tater = CanvasImage.from(image);
            System.out.println("Buildin time passed = " + (System.currentTimeMillis() - start));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        this.logo = CanvasImage.from(ImageIO.read(Files.newInputStream(FabricLoader.getInstance().getModContainer("map-canvas-api").get().getPath("assets/icon.png"))));
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        var vanillaZip = PolymerUtils.getClientJar();
        var compPath = FabricLoader.getInstance().getGameDir().resolve("coml.zip");
        var unsPath = FabricLoader.getInstance().getGameDir().resolve("uns.zip");
        var vanillaJsonPath = FabricLoader.getInstance().getGameDir().resolve("../vanilla-font-json.zip");
        if (!Files.exists(compPath)) {
            FileUtils.copyURLToFile(new URL("https://github.com/Compliance-Resource-Pack/Compliance-Java-32x/releases/download/beta-20/Compliance-32x-Java-Beta-20.zip"), compPath.toFile(), 10000, 10000);
        }
        if (!Files.exists(unsPath)) {
            FileUtils.copyURLToFile(new URL("https://media.forgecdn.net/files/3354/621/Unsanded-1.1.zip"), unsPath.toFile(), 10000, 10000);
        }
        var hdPack = new ZipFile(compPath.toFile());
        var unsPack = new ZipFile(unsPath.toFile());
        var jsonPack = new ZipFile(vanillaJsonPath.toFile());
        this.font = FontUtils.fromVanillaFormat(new Identifier("minecraft:default"), vanillaZip);
        this.fontHd = FontUtils.fromVanillaFormat(new Identifier("minecraft:default"), hdPack, vanillaZip);
        this.fontUnsanded = FontUtils.fromVanillaFormat(new Identifier("minecraft:default"), unsPack, jsonPack);
        var path = FabricLoader.getInstance().getGameDir().resolve("fonts_export");
        Files.createDirectories(path);
        {
            var stream = new FileOutputStream(path.resolve("vanilla.mcaf").toFile());
            RawBitmapFontSerializer.write((BitmapFont) this.font, stream);
            stream.close();
        }
        {
            var stream = new FileOutputStream(path.resolve("unsanded.mcaf").toFile());
            RawBitmapFontSerializer.write((BitmapFont) this.fontUnsanded, stream);
            stream.close();
        }
        {
            var stream = new FileOutputStream(path.resolve("alt.mcaf").toFile());
            RawBitmapFontSerializer.write((BitmapFont) FontUtils.fromVanillaFormat(new Identifier("minecraft:alt"), vanillaZip), stream);
            stream.close();
        }
        {
            var stream = new FileOutputStream(path.resolve("illageralt.mcaf").toFile());
            RawBitmapFontSerializer.write((BitmapFont) FontUtils.fromVanillaFormat(new Identifier("minecraft:illageralt"), vanillaZip), stream);
            stream.close();
        }
        vanillaZip.close();
        hdPack.close();
        unsPack.close();
        jsonPack.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
    } catch (Exception e) {
        e.printStackTrace();
    }
    ServerLifecycleEvents.SERVER_STARTED.register((s) -> {
        this.setCurrentRenderer(this.menuRenderer);
        this.renderers.add(new Pair<>("TaterDemo", new TaterDemoRenderer(this.tater, this.fontHd, this.logo)));
        this.renderers.add(new Pair<>("SimpleSurface", new SurfaceRenderer()));
        this.renderers.add(new Pair<>("Raycast", new RaycastRenderer(s)));
        if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
            this.renderers.add(new Pair<>("Client Framebuffer", new ClientRenderer()));
        }
        this.startUpdateThread();
    });
    ServerLifecycleEvents.SERVER_STOPPED.register((s) -> {
        this.setCurrentRenderer(this.menuRenderer);
        this.renderers.clear();
        this.activeRenderer = false;
    });
}
Also used : PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) ServerPlayNetworkHandler(net.minecraft.server.network.ServerPlayNetworkHandler) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) MinecraftServer(net.minecraft.server.MinecraftServer) Identifier(net.minecraft.util.Identifier) ZipFile(java.util.zip.ZipFile) FileOutputStream(java.io.FileOutputStream) BitmapFont(eu.pb4.mapcanvas.impl.font.BitmapFont)

Example 2 with PacketSender

use of net.fabricmc.fabric.api.networking.v1.PacketSender in project Biome-Makeover by Lemonszz.

the class BiomeMakeover method onInitialize.

@Override
public void onInitialize() {
    GROUP = new BiomeMakeoverItemGroup(new Identifier(MODID, MODID));
    BMEffects.init();
    BoatTypes.init();
    BMBlocks.init();
    BMItems.init();
    BMEntities.init();
    BMBlockEntities.init();
    BMPotions.init();
    BMEnchantments.init();
    BMStructures.init();
    BMWorldGen.init();
    BMCriterion.init();
    BMScreens.init();
    BMWorldEvents.init();
    BMNetwork.initCommon();
    PoltergeistHandler.init();
    WitchQuestHandler.init();
    AdjudicatorRoomListener.init();
    ServerTickEvents.END_SERVER_TICK.register((e) -> WindSystem.update());
    ServerTickEvents.END_WORLD_TICK.register(TumbleweedSpawner::update);
    // TODO: Move
    CommandRegistrationCallback.EVENT.register((d, ded) -> d.register(CommandManager.literal("pillager").requires((serverCommandSource) -> serverCommandSource.hasPermissionLevel(2)).then(CommandManager.argument("pos", BlockPosArgumentType.blockPos()).then(CommandManager.argument("leader", BoolArgumentType.bool()).executes(c -> {
        ((PillagerSpawnerAccess) new PillagerSpawner()).bm_spawn(c.getSource().getWorld(), BlockPosArgumentType.getBlockPos(c, "pos"), BoolArgumentType.getBool(c, "leader"));
        return 1;
    })))));
    ServerPlayConnectionEvents.JOIN.register((ServerPlayNetworkHandler handler, PacketSender sender, MinecraftServer server) -> {
        NetworkUtil.sendSlideTime(handler.player, ((SlideEntity) handler.player).getSlideTime());
    });
    UseBlockCallback.EVENT.register((player, world, hand, hitResult) -> {
        if (!player.isSpectator()) {
            ItemStack stack = player.getStackInHand(hand);
            if (!stack.isEmpty() && stack.getItem() == BMItems.ECTOPLASM) {
                BlockPos pos = hitResult.getBlockPos();
                BlockState state = world.getBlockState(pos);
                if (state.getBlock() == Blocks.COMPOSTER) {
                    int level = state.get(ComposterBlock.LEVEL);
                    if (level > 0) {
                        if (!world.isClient()) {
                            world.syncWorldEvent(1500, pos, 1);
                            world.setBlockState(pos, BMBlocks.ECTOPLASM_COMPOSTER.getDefaultState().with(ComposterBlock.LEVEL, level));
                            if (!player.isCreative())
                                stack.decrement(1);
                        }
                        return ActionResult.SUCCESS;
                    }
                }
            }
        }
        return ActionResult.PASS;
    });
    UseEntityCallback.EVENT.register((pl, world, hand, entity, hr) -> {
        ItemStack stack = pl.getStackInHand(hand);
        if (!stack.isEmpty() && (stack.getItem() == Items.GLASS_BOTTLE || stack.getItem() == Items.EXPERIENCE_BOTTLE)) {
            if (entity instanceof LightningBugEntity) {
                if (!world.isClient()) {
                    ItemStack result = ItemUsage.method_30012(stack, pl, new ItemStack(stack.getItem() == Items.GLASS_BOTTLE ? BMBlocks.LIGHTNING_BUG_BOTTLE : BMItems.LIGHTNING_BOTTLE));
                    pl.setStackInHand(hand, result);
                    entity.remove();
                    pl.playSound(SoundEvents.ITEM_BOTTLE_FILL, 1F, 1F);
                }
                return ActionResult.SUCCESS;
            }
        }
        return ActionResult.PASS;
    });
    final Identifier BAT_LT_ID = new Identifier("minecraft", "entities/bat");
    LootTableLoadingCallback.EVENT.register((rm, lm, id, supplier, setter) -> {
        if (id.equals(BAT_LT_ID)) {
            FabricLootPoolBuilder builder = FabricLootPoolBuilder.builder().rolls(BinomialLootTableRange.create(2, 0.5F)).withEntry(ItemEntry.builder(BMItems.BAT_WING).build());
            supplier.withPool(builder.build());
        }
    });
}
Also used : ServerTickEvents(net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents) PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) FabricLootPoolBuilder(net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder) ComposterBlock(net.minecraft.block.ComposterBlock) BinomialLootTableRange(net.minecraft.loot.BinomialLootTableRange) BiomeMakeoverItemGroup(party.lemons.biomemakeover.crafting.itemgroup.BiomeMakeoverItemGroup) WindSystem(party.lemons.biomemakeover.world.WindSystem) WitchQuestHandler(party.lemons.biomemakeover.crafting.witch.WitchQuestHandler) CommandRegistrationCallback(net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback) LightningBugEntity(party.lemons.biomemakeover.entity.LightningBugEntity) BoatTypes(party.lemons.biomemakeover.util.boat.BoatTypes) TumbleweedSpawner(party.lemons.biomemakeover.world.TumbleweedSpawner) BoolArgumentType(com.mojang.brigadier.arguments.BoolArgumentType) UseEntityCallback(net.fabricmc.fabric.api.event.player.UseEntityCallback) ItemStack(net.minecraft.item.ItemStack) MinecraftServer(net.minecraft.server.MinecraftServer) AdjudicatorRoomListener(party.lemons.biomemakeover.entity.adjudicator.AdjudicatorRoomListener) ServerPlayConnectionEvents(net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents) SoundEvents(net.minecraft.sound.SoundEvents) UseBlockCallback(net.fabricmc.fabric.api.event.player.UseBlockCallback) PillagerSpawner(net.minecraft.world.gen.PillagerSpawner) party.lemons.biomemakeover.init(party.lemons.biomemakeover.init) BlockState(net.minecraft.block.BlockState) BlockPosArgumentType(net.minecraft.command.argument.BlockPosArgumentType) ItemUsage(net.minecraft.item.ItemUsage) NetworkUtil(party.lemons.biomemakeover.util.NetworkUtil) BMWorldEvents(party.lemons.biomemakeover.world.BMWorldEvents) BlockPos(net.minecraft.util.math.BlockPos) Items(net.minecraft.item.Items) ModInitializer(net.fabricmc.api.ModInitializer) ItemEntry(net.minecraft.loot.entry.ItemEntry) Blocks(net.minecraft.block.Blocks) CommandManager(net.minecraft.server.command.CommandManager) ActionResult(net.minecraft.util.ActionResult) LootTableLoadingCallback(net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback) SlideEntity(party.lemons.biomemakeover.util.extensions.SlideEntity) ItemGroup(net.minecraft.item.ItemGroup) Identifier(net.minecraft.util.Identifier) PoltergeistHandler(party.lemons.biomemakeover.world.PoltergeistHandler) PillagerSpawnerAccess(party.lemons.biomemakeover.util.access.PillagerSpawnerAccess) ServerPlayNetworkHandler(net.minecraft.server.network.ServerPlayNetworkHandler) TumbleweedSpawner(party.lemons.biomemakeover.world.TumbleweedSpawner) BiomeMakeoverItemGroup(party.lemons.biomemakeover.crafting.itemgroup.BiomeMakeoverItemGroup) PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) ServerPlayNetworkHandler(net.minecraft.server.network.ServerPlayNetworkHandler) PillagerSpawnerAccess(party.lemons.biomemakeover.util.access.PillagerSpawnerAccess) FabricLootPoolBuilder(net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder) MinecraftServer(net.minecraft.server.MinecraftServer) PillagerSpawner(net.minecraft.world.gen.PillagerSpawner) Identifier(net.minecraft.util.Identifier) BlockState(net.minecraft.block.BlockState) LightningBugEntity(party.lemons.biomemakeover.entity.LightningBugEntity) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack)

Example 3 with PacketSender

use of net.fabricmc.fabric.api.networking.v1.PacketSender in project architectury-api by architectury.

the class NetworkManagerImpl method registerS2CReceiver.

@SuppressWarnings("Convert2Lambda")
@Environment(EnvType.CLIENT)
private static void registerS2CReceiver(ResourceLocation id, List<PacketTransformer> packetTransformers, NetworkReceiver receiver) {
    S2C_RECEIVER.put(id, receiver);
    PacketTransformer transformer = PacketTransformer.concat(packetTransformers);
    ClientPlayNetworking.registerGlobalReceiver(id, new ClientPlayNetworking.PlayChannelHandler() {

        @Override
        public void receive(Minecraft client, ClientPacketListener handler, FriendlyByteBuf buf, PacketSender sender) {
            var context = context(client.player, client, true);
            transformer.inbound(NetworkManager.Side.S2C, id, buf, context, (side, id1, buf1) -> {
                NetworkReceiver networkReceiver = side == NetworkManager.Side.C2S ? C2S_RECEIVER.get(id1) : S2C_RECEIVER.get(id1);
                if (networkReceiver == null) {
                    throw new IllegalArgumentException("Network Receiver not found! " + id1);
                }
                networkReceiver.receive(buf1, context);
            });
        }
    });
    S2C_TRANSFORMERS.put(id, transformer);
}
Also used : FriendlyByteBuf(net.minecraft.network.FriendlyByteBuf) ResourceLocation(net.minecraft.resources.ResourceLocation) NetworkReceiver(dev.architectury.networking.NetworkManager.NetworkReceiver) PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) ClientPlayNetworking(net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking) Environment(net.fabricmc.api.Environment) HashMap(java.util.HashMap) BlockableEventLoop(net.minecraft.util.thread.BlockableEventLoop) ClientPacketListener(net.minecraft.client.multiplayer.ClientPacketListener) FriendlyByteBuf(net.minecraft.network.FriendlyByteBuf) Player(net.minecraft.world.entity.player.Player) ServerPlayer(net.minecraft.server.level.ServerPlayer) NetworkManager(dev.architectury.networking.NetworkManager) List(java.util.List) Entity(net.minecraft.world.entity.Entity) Minecraft(net.minecraft.client.Minecraft) Map(java.util.Map) Env(dev.architectury.utils.Env) ServerPlayNetworking(net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking) PacketSink(dev.architectury.networking.transformers.PacketSink) EnvType(net.fabricmc.api.EnvType) Packet(net.minecraft.network.protocol.Packet) PacketTransformer(dev.architectury.networking.transformers.PacketTransformer) NetworkReceiver(dev.architectury.networking.NetworkManager.NetworkReceiver) PacketTransformer(dev.architectury.networking.transformers.PacketTransformer) ClientPacketListener(net.minecraft.client.multiplayer.ClientPacketListener) PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) ClientPlayNetworking(net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking) Minecraft(net.minecraft.client.Minecraft) Environment(net.fabricmc.api.Environment)

Example 4 with PacketSender

use of net.fabricmc.fabric.api.networking.v1.PacketSender in project bewitchment by MoriyaShiine.

the class SyncContractsPacket method handle.

public static void handle(MinecraftClient client, ClientPlayNetworkHandler network, PacketByteBuf buf, PacketSender sender) {
    NbtCompound contractsCompound = buf.readNbt();
    client.execute(new Runnable() {

        @Override
        public void run() {
            if (client.player != null) {
                BWComponents.CONTRACTS_COMPONENT.maybeGet(client.player).ifPresent(contractsComponent -> {
                    contractsComponent.getContracts().clear();
                    NbtList contractsList = contractsCompound.getList("Contracts", NbtType.COMPOUND);
                    for (int i = 0; i < contractsList.size(); i++) {
                        NbtCompound contractCompound = contractsList.getCompound(i);
                        contractsComponent.addContract(new Contract.Instance(BWRegistries.CONTRACTS.get(new Identifier(contractCompound.getString("Contract"))), contractCompound.getInt("Duration"), contractCompound.getInt("Cost")));
                    }
                });
            }
        }
    });
}
Also used : PacketSender(net.fabricmc.fabric.api.networking.v1.PacketSender) PlayerEntity(net.minecraft.entity.player.PlayerEntity) Contract(moriyashiine.bewitchment.api.registry.Contract) NbtList(net.minecraft.nbt.NbtList) PacketByteBuf(net.minecraft.network.PacketByteBuf) Unpooled(io.netty.buffer.Unpooled) BWRegistries(moriyashiine.bewitchment.common.registry.BWRegistries) NbtCompound(net.minecraft.nbt.NbtCompound) ServerPlayerEntity(net.minecraft.server.network.ServerPlayerEntity) NbtType(net.fabricmc.fabric.api.util.NbtType) ServerPlayNetworking(net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking) BWComponents(moriyashiine.bewitchment.common.registry.BWComponents) Identifier(net.minecraft.util.Identifier) MinecraftClient(net.minecraft.client.MinecraftClient) ClientPlayNetworkHandler(net.minecraft.client.network.ClientPlayNetworkHandler) Bewitchment(moriyashiine.bewitchment.common.Bewitchment) Identifier(net.minecraft.util.Identifier) NbtCompound(net.minecraft.nbt.NbtCompound) NbtList(net.minecraft.nbt.NbtList)

Aggregations

PacketSender (net.fabricmc.fabric.api.networking.v1.PacketSender)4 Identifier (net.minecraft.util.Identifier)3 ServerPlayNetworking (net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking)2 MinecraftServer (net.minecraft.server.MinecraftServer)2 ServerPlayNetworkHandler (net.minecraft.server.network.ServerPlayNetworkHandler)2 BoolArgumentType (com.mojang.brigadier.arguments.BoolArgumentType)1 NetworkManager (dev.architectury.networking.NetworkManager)1 NetworkReceiver (dev.architectury.networking.NetworkManager.NetworkReceiver)1 PacketSink (dev.architectury.networking.transformers.PacketSink)1 PacketTransformer (dev.architectury.networking.transformers.PacketTransformer)1 Env (dev.architectury.utils.Env)1 BitmapFont (eu.pb4.mapcanvas.impl.font.BitmapFont)1 Unpooled (io.netty.buffer.Unpooled)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 ZipFile (java.util.zip.ZipFile)1