Jump to content

Moriz

Members
  • Posts

    4
  • Joined

  • Last visited

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

Moriz's Achievements

Tree Puncher

Tree Puncher (2/8)

0

Reputation

  1. Whenever I register my mods recipe types to the game i receive no errors in the server log or the client log but it stops showing recipes for all items in JEI. However I can see recipes in single player. When I dont register the types it fixes the issue. How do I prevent this from happening? What am I doing wrong? This is the line I comment out to fix the issue (prevents the types from registering) public OrangeSunshine() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); BLOCKS.register(modEventBus); SOUNDS.register(modEventBus); DRUGS.register(modEventBus); ModTileEntities.register(modEventBus); ModContainers.register(modEventBus); ModVillagers.VILLAGER_PROFESSIONS.register(modEventBus); ModVillagers.POINT_OF_INTEREST_TYPES.register(modEventBus); ModItems.init(modEventBus); ModBlocks.init(); ModSounds.init(); PacketHandler.init(); ModRecipeTypes.register(modEventBus); // issue line modEventBus.addListener(this::setup); modEventBus.addListener(this::enqueueIMC); modEventBus.addListener(this::processIMC); modEventBus.addListener(this::doClientStuff); MinecraftForge.EVENT_BUS.register(this); } All my code on github : HERE
  2. @diesieben07 Thank you, I have fixed the issue!
  3. Hello, Im working on a mod called OrangeSunshine, I have run into an issue where the Mr.CrayFish mod trys to cast my "PlayerDrugs" class to its "SyncedPlayerData" class. I'm unsure if this is somthing I can fix, or somthing they will have to. Below is my stacktrace and both of the classes that cause the issue. also these are the sources of both of our mods. https://github.com/MrCrayfish/Obfuscate https://github.com/Moriz82/OrangeSunshine Here is the stack trace: [13Jan2022 16:58:42.645] [Server thread/ERROR] [net.minecraftforge.eventbus.EventBus/EVENTBUS]: Exception caught during firing event: com.BrotherHoodOfDiethylamide.OrangeSunshine.capabilities.PlayerDrugs$Implementation cannot be cast to com.mrcrayfish.obfuscate.common.data.SyncedPlayerData$DataHolder Index: 3 Listeners: 0: HIGHEST 1: ASM: net.minecraftforge.common.ForgeInternalHandler@2af1cde2 onEntityJoinWorld(Lnet/minecraftforge/event/entity/EntityJoinWorldEvent;)V 2: NORMAL 3: ASM: com.mrcrayfish.obfuscate.common.data.SyncedPlayerData@1649d454 onPlayerJoinWorld(Lnet/minecraftforge/event/entity/EntityJoinWorldEvent;)V java.lang.ClassCastException: com.BrotherHoodOfDiethylamide.OrangeSunshine.capabilities.PlayerDrugs$Implementation cannot be cast to com.mrcrayfish.obfuscate.common.data.SyncedPlayerData$DataHolder at com.mrcrayfish.obfuscate.common.data.SyncedPlayerData.getDataHolder(SyncedPlayerData.java:174) at com.mrcrayfish.obfuscate.common.data.SyncedPlayerData.onPlayerJoinWorld(SyncedPlayerData.java:212) at net.minecraftforge.eventbus.ASMEventHandler_27_SyncedPlayerData_onPlayerJoinWorld_EntityJoinWorldEvent.invoke(.dynamic) at net.minecraftforge.eventbus.ASMEventHandler.invoke(ASMEventHandler.java:85) at net.minecraftforge.eventbus.EventBus$$Lambda$2554/57696956.invoke(Unknown Source) at net.minecraftforge.eventbus.EventBus.post(EventBus.java:302) at net.minecraftforge.eventbus.EventBus.post(EventBus.java:283) at net.minecraft.world.server.ServerWorld.func_217448_f(ServerWorld.java:788) at net.minecraft.world.server.ServerWorld.func_217435_c(ServerWorld.java:780) at net.minecraft.server.management.PlayerList.func_72355_a(PlayerList.java:185) at net.minecraft.network.login.ServerLoginNetHandler.func_147326_c(ServerLoginNetHandler.java:118) at net.minecraft.network.login.ServerLoginNetHandler.func_73660_a(ServerLoginNetHandler.java:65) at net.minecraft.network.NetworkManager.func_74428_b(NetworkManager.java:222) at net.minecraft.network.NetworkSystem.func_151269_c(NetworkSystem.java:134) at net.minecraft.server.MinecraftServer.func_71190_q(MinecraftServer.java:865) at net.minecraft.server.MinecraftServer.func_71217_p(MinecraftServer.java:787) at net.minecraft.server.integrated.IntegratedServer.func_71217_p(IntegratedServer.java:78) at net.minecraft.server.MinecraftServer.func_240802_v_(MinecraftServer.java:642) at net.minecraft.server.MinecraftServer.func_240783_a_(MinecraftServer.java:232) at net.minecraft.server.MinecraftServer$$Lambda$5300/334348732.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) Here is my PlayerDrugs class : package com.BrotherHoodOfDiethylamide.OrangeSunshine.capabilities; import com.BrotherHoodOfDiethylamide.OrangeSunshine.OrangeSunshine; import com.BrotherHoodOfDiethylamide.OrangeSunshine.drugs.Drug; import com.BrotherHoodOfDiethylamide.OrangeSunshine.drugs.DrugEffects; import com.BrotherHoodOfDiethylamide.OrangeSunshine.drugs.DrugInstance; import com.BrotherHoodOfDiethylamide.OrangeSunshine.network.ActiveDrugCapSync; import com.BrotherHoodOfDiethylamide.OrangeSunshine.network.DrugCapSync; import com.BrotherHoodOfDiethylamide.OrangeSunshine.network.PacketHandler; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSidedProvider; import net.minecraftforge.fml.network.PacketDistributor; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; public class PlayerDrugs { static class Implementation implements IPlayerDrugs { private final Map<Drug, Float> active = new HashMap<>(); private final List<DrugInstance> sources = new ArrayList<>(); private final Map<Drug, Integer> abuseTimers = new HashMap<>(); private final DrugEffects drugEffects = new DrugEffects(); private int smokeTick = 0; @Override public void addDrugSource(DrugInstance drug) { sources.add(drug); } @Override public void setSources(List<DrugInstance> drugInstances) { sources.clear(); sources.addAll(drugInstances); } @Override public void removeDrugSource(DrugInstance drug) { sources.remove(drug); } @Override public void clearDrugSources() { sources.clear(); } @Override public List<DrugInstance> getDrugSources() { return sources; } @Override public void putActive(Drug drug, float effect) { if (effect > 0) { active.put(drug, effect); } else { active.remove(drug); } } @Nullable @Override public Float getActive(Drug drug) { return active.get(drug); } @Override public void clearActives() { active.clear(); } @Override public void setActives(Map<Drug, Float> activeDrugs) { active.clear(); active.putAll(activeDrugs); } @Override public Map<Drug, Float> getActiveDrugs() { return active; } @Override public void addDrugAbuse(Drug drug, int ticks) { abuseTimers.put(drug, abuseTimers.getOrDefault(drug, 0) + ticks); } @Override public int getDrugAbuse(Drug drug) { return abuseTimers.getOrDefault(drug, 0); } @Override public void tickDrugAbuse() { abuseTimers.replaceAll((drug, tick) -> tick - 1); abuseTimers.values().removeIf(tick -> tick <= 0); } @Override public void setDrugAbuseMap(Map<Drug, Integer> drugAbuseMap) { abuseTimers.clear(); abuseTimers.putAll(drugAbuseMap); } @Override public Map<Drug, Integer> getDrugAbuseMap() { return abuseTimers; } @Override public DrugEffects getDrugEffects() { return drugEffects; } @Override public void setSmokeTicks(int ticks) { smokeTick = ticks; } @Override public int getSmokeTicks() { return smokeTick; } } static class Provider implements ICapabilitySerializable<CompoundNBT> { private final Implementation defaultImplementation = new Implementation(); private final LazyOptional<IPlayerDrugs> optional = LazyOptional.of(() -> defaultImplementation); @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return optional.cast(); } @Override public CompoundNBT serializeNBT() { return (CompoundNBT) PlayerProperties.PLAYER_DRUGS.writeNBT(defaultImplementation, null); } @Override public void deserializeNBT(CompoundNBT nbt) { PlayerProperties.PLAYER_DRUGS.readNBT(defaultImplementation, null, nbt); } public void invalidate() { optional.invalidate(); } } static class Storage implements Capability.IStorage<IPlayerDrugs>{ @Nullable @Override public INBT writeNBT(Capability<IPlayerDrugs> capability, IPlayerDrugs instance, Direction side) { CompoundNBT nbt = new CompoundNBT(); ListNBT drugSources = new ListNBT(); for (DrugInstance drugInstance : instance.getDrugSources()) { CompoundNBT drugProperties = new CompoundNBT(); drugProperties.putString("id", drugInstance.toName()); drugProperties.putInt("delay", drugInstance.getDelayTime()); drugProperties.putFloat("potency", drugInstance.getPotency()); drugProperties.putInt("duration", drugInstance.getDuration()); drugProperties.putInt("timeActive", drugInstance.getTimeActive()); drugSources.add(drugProperties); } nbt.put("sources", drugSources); CompoundNBT drugAbuse = new CompoundNBT(); instance.getDrugAbuseMap().forEach((drug, tick) -> { if (tick > 0) drugAbuse.putInt(Drug.toName(drug), tick); }); nbt.put("abuse", drugAbuse); return nbt; } @Override public void readNBT(Capability<IPlayerDrugs> capability, IPlayerDrugs instance, Direction side, INBT nbtIn) { if (nbtIn != null) { CompoundNBT nbt = (CompoundNBT) nbtIn; ListNBT drugSources = nbt.getList("sources", 10); for (INBT drugSource : drugSources) { CompoundNBT drugProperties = (CompoundNBT) drugSource; Drug drug = Drug.byName(drugProperties.getString("id")); if (drug == null) { OrangeSunshine.LOGGER.warn("Tried to read non-existent registry {} from sources, ignoring", drugProperties.getString("id")); continue; } DrugInstance drugInstance = new DrugInstance(drug, drugProperties.getInt("delay"), drugProperties.getFloat("potency"), drugProperties.getInt("duration"), drugProperties.getInt("timeActive")); instance.addDrugSource(drugInstance); } CompoundNBT drugAbuse = nbt.getCompound("abuse"); for (String drugKey : drugAbuse.getAllKeys()) { Drug drug = Drug.byName(drugKey); if (drug == null) { OrangeSunshine.LOGGER.warn("Tried to read non-existent registry {} from abuse map, ignoring", drugKey); continue; } instance.addDrugAbuse(drug, drugAbuse.getInt(drugKey)); } } } } static void register() { CapabilityManager.INSTANCE.register(IPlayerDrugs.class, new PlayerDrugs.Storage(), PlayerDrugs.Implementation::new); MinecraftForge.EVENT_BUS.addGenericListener(Entity.class, PlayerDrugs::attachCapabilitiesEntity); MinecraftForge.EVENT_BUS.addListener(PlayerDrugs::onPlayerLoggedIn); MinecraftForge.EVENT_BUS.addListener(PlayerDrugs::onPlayerChangedDimension); MinecraftForge.EVENT_BUS.addListener(PlayerDrugs::onServerTick); } static void attachCapabilitiesEntity(AttachCapabilitiesEvent<Entity> event) { if (event.getObject() instanceof PlayerEntity) { PlayerDrugs.Provider provider = new PlayerDrugs.Provider(); event.addCapability(new ResourceLocation(OrangeSunshine.MOD_ID, "drugs"), provider); event.addListener(provider::invalidate); } } static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { sync((ServerPlayerEntity) event.getPlayer()); syncActives((ServerPlayerEntity) event.getPlayer()); } static void onPlayerChangedDimension(PlayerEvent.PlayerChangedDimensionEvent event) { sync((ServerPlayerEntity) event.getPlayer()); syncActives((ServerPlayerEntity) event.getPlayer()); } private static int totalTicks = 1; static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { if (totalTicks++ % (5*20) == 0) { MinecraftServer server = LogicalSidedProvider.INSTANCE.get(LogicalSide.SERVER); for (ServerPlayerEntity player : server.getPlayerList().getPlayers()) { sync(player); } } } } public static void sync(ServerPlayerEntity player) { List<DrugInstance> drugInstances = Drug.getDrugSources(player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new DrugCapSync(drugInstances)); } private static void syncActives(ServerPlayerEntity player) { Map<Drug, Float> actives = Drug.getActiveDrugs(player); PacketHandler.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new ActiveDrugCapSync(actives)); } } Here is Mr.CrayFish's SyncedPlayerData class: package com.mrcrayfish.obfuscate.common.data; import com.google.common.collect.ImmutableList; import com.mrcrayfish.obfuscate.Reference; import com.mrcrayfish.obfuscate.network.HandshakeMessages; import com.mrcrayfish.obfuscate.network.PacketHandler; import com.mrcrayfish.obfuscate.network.message.MessageSyncPlayerData; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fmllegacy.network.PacketDistributor; import org.apache.commons.lang3.Validate; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * <p>Basically a clone of DataParameter system. It's not good to init custom data parameters to * other entities that aren't your own. It can cause mismatched ids and crash the game. This synced * data system attempts to solve the problem (at least for player entities) and allows data to be * easily synced to clients. The data can only be controlled on the logical server. Changing the * data on the logical client will have no affect on the server.</p> * <p></p> * <p>To use this system you first need to create a synced data key instance. This should be a public * static final field. You will need to specify an key id (based on your modid), the serializer, and * a default value supplier.</p> * <code>public static final SyncedDataKey&lt;Double&gt; CURRENT_SPEED = SyncedDataKey.create(new ResourceLocation("examplemod:speed"), Serializers.DOUBLE, () -> 0.0);</code> * <p></p> * <p>Next the key needs to be registered. This can simply be done in the common setup of your mod.</p> * <code>SyncedPlayerData.instance().registerKey(CURRENT_SPEED);</code> * <p></p> * <p>Then anywhere you want (as long as it's on the main thread), you can set the value by calling</p> * <code>SyncedPlayerData.instance().set(player, CURRENT_SPEED, 5.0);</code> * <p></p> * <p>The value can be retrieved on the server or client by calling</p> * <code>SyncedPlayerData.instance().get(player, CURRENT_SPEED);</code> * <p></p> * <p>Author: MrCrayfish</p> */ public class SyncedPlayerData { @CapabilityInject(DataHolder.class) public static final Capability<DataHolder> CAPABILITY = null; private static SyncedPlayerData instance; private final Map<ResourceLocation, SyncedDataKey<?>> registeredDataKeys = new HashMap<>(); private final Map<Integer, SyncedDataKey<?>> idToDataKey = new HashMap<>(); private int nextKeyId = 0; private boolean dirty = false; private SyncedPlayerData() {} public static SyncedPlayerData instance() { if(instance == null) { instance = new SyncedPlayerData(); } return instance; } public static void onRegisterCapability(RegisterCapabilitiesEvent event) { event.register(DataHolder.class); } /** * Registers a synced data key into the system. * * @param key a synced data key instance */ public void registerKey(SyncedDataKey<?> key) { if(this.registeredDataKeys.containsKey(key.getKey())) { throw new IllegalArgumentException(String.format("The data key '%s' is already registered!", key.getKey())); } int nextId = this.nextKeyId++; key.setId(nextId); this.registeredDataKeys.put(key.getKey(), key); this.idToDataKey.put(nextId, key); } /** * Sets the value of a synced data key to the specified player * * @param player the player to assign the value to * @param key a registered synced data key * @param value a new value that matches the synced data key type */ public <T> void set(Player player, SyncedDataKey<T> key, T value) { if(!this.registeredDataKeys.values().contains(key)) { throw new IllegalArgumentException(String.format("The data key '%s' is not registered!", key.getKey())); } DataHolder holder = this.getDataHolder(player); if(holder != null && holder.set(player, key, value)) { if(!player.level.isClientSide()) { this.dirty = true; } } } /** * Gets the value for the synced data key from the specified player. It is best to check that * the player is alive before getting the value. * * @param player the player to retrieve the data from * @param key a registered synced data key */ public <T> T get(Player player, SyncedDataKey<T> key) { if(!this.registeredDataKeys.values().contains(key)) { throw new IllegalArgumentException(String.format("The data key '%s' is not registered!", key.getKey())); } DataHolder holder = this.getDataHolder(player); return holder != null ? holder.get(key) : key.getDefaultValueSupplier().get(); } @OnlyIn(Dist.CLIENT) public <T> void updateClientEntry(Player player, SyncedPlayerData.DataEntry<T> entry) { SyncedPlayerData.instance().set(player, entry.getKey(), entry.getValue()); } @Nullable private SyncedDataKey<?> getKey(int id) { return this.idToDataKey.get(id); } public List<SyncedDataKey<?>> getKeys() { return ImmutableList.copyOf(this.registeredDataKeys.values()); } @Nullable private DataHolder getDataHolder(Player player) { return player.getCapability(CAPABILITY, null).orElse(null); } @SubscribeEvent public void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { if(event.getObject() instanceof Player) { event.addCapability(new ResourceLocation(Reference.MOD_ID, "synced_player_data"), new Provider()); } } @SubscribeEvent public void onStartTracking(PlayerEvent.StartTracking event) { if(event.getTarget() instanceof Player && !event.getPlayer().level.isClientSide()) { Player player = (Player) event.getTarget(); DataHolder holder = this.getDataHolder(player); if(holder != null) { List<SyncedPlayerData.DataEntry<?>> entries = holder.gatherAll(); entries.removeIf(entry -> !entry.getKey().shouldSyncToAllPlayers()); if(!entries.isEmpty()) { PacketHandler.getPlayChannel().send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) event.getPlayer()), new MessageSyncPlayerData(player.getId(), entries)); } } } } @SubscribeEvent public void onPlayerJoinWorld(EntityJoinWorldEvent event) { Entity entity = event.getEntity(); if(entity instanceof Player player && !event.getWorld().isClientSide()) { DataHolder holder = this.getDataHolder(player); if(holder != null) { List<SyncedPlayerData.DataEntry<?>> entries = holder.gatherAll(); if(!entries.isEmpty()) { PacketHandler.getPlayChannel().send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MessageSyncPlayerData(player.getId(), entries)); } } } } @SubscribeEvent public void onPlayerClone(PlayerEvent.Clone event) { Player original = event.getOriginal(); if(!original.level.isClientSide()) { Player player = event.getPlayer(); DataHolder oldHolder = this.getDataHolder(original); if(oldHolder != null) { DataHolder newHolder = this.getDataHolder(player); if(newHolder != null) { Map<SyncedDataKey<?>, DataEntry<?>> dataMap = new HashMap<>(oldHolder.dataMap); if(event.isWasDeath()) { dataMap.entrySet().removeIf(entry -> !entry.getKey().isPersistent()); } newHolder.dataMap = dataMap; } } } } @SubscribeEvent public void onServerTick(TickEvent.PlayerTickEvent event) { if(event.phase == TickEvent.Phase.END) { if(this.dirty) { Player player = event.player; if(!player.level.isClientSide()) { DataHolder holder = this.getDataHolder(player); if(holder != null && holder.isDirty()) { List<SyncedPlayerData.DataEntry<?>> entries = holder.gatherDirty(); if(!entries.isEmpty()) { PacketHandler.getPlayChannel().send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MessageSyncPlayerData(player.getId(), entries)); List<SyncedPlayerData.DataEntry<?>> syncToAllEntries = entries.stream().filter(entry -> entry.getKey().shouldSyncToAllPlayers()).collect(Collectors.toList()); if(!syncToAllEntries.isEmpty()) { PacketHandler.getPlayChannel().send(PacketDistributor.TRACKING_ENTITY.with(() -> player), new MessageSyncPlayerData(player.getId(), syncToAllEntries)); } } holder.clean(); } } } } } @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if(event.phase == TickEvent.Phase.END) { if(this.dirty) { this.dirty = false; } } } public static class DataHolder { private Map<SyncedDataKey<?>, DataEntry<?>> dataMap = new HashMap<>(); private boolean dirty = false; @SuppressWarnings("unchecked") private <T> boolean set(Player player, SyncedDataKey<T> key, T value) { DataEntry<T> entry = (DataEntry<T>) this.dataMap.computeIfAbsent(key, DataEntry::new); if(!entry.getValue().equals(value)) { boolean dirty = !player.level.isClientSide() && entry.getKey().shouldSyncToClient(); entry.setValue(value, dirty); this.dirty = dirty; return true; } return false; } @Nullable @SuppressWarnings("unchecked") private <T> T get(SyncedDataKey<T> key) { return (T) this.dataMap.computeIfAbsent(key, DataEntry::new).getValue(); } private boolean isDirty() { return this.dirty; } private void clean() { this.dirty = false; this.dataMap.forEach((key, entry) -> entry.clean()); } private List<DataEntry<?>> gatherDirty() { return this.dataMap.values().stream().filter(DataEntry::isDirty).filter(entry -> entry.getKey().shouldSyncToClient()).collect(Collectors.toList()); } private List<DataEntry<?>> gatherAll() { return this.dataMap.values().stream().filter(entry -> entry.getKey().shouldSyncToClient()).collect(Collectors.toList()); } } public static class DataEntry<T> { private SyncedDataKey<T> key; private T value; private boolean dirty; private DataEntry(SyncedDataKey<T> key) { this.key = key; this.value = key.getDefaultValueSupplier().get(); } private SyncedDataKey<T> getKey() { return this.key; } private T getValue() { return this.value; } private void setValue(T value, boolean dirty) { this.value = value; this.dirty = dirty; } private boolean isDirty() { return this.dirty; } private void clean() { this.dirty = false; } public void write(FriendlyByteBuf buffer) { buffer.writeVarInt(this.key.getId()); this.key.getSerializer().write(buffer, this.value); } public static DataEntry<?> read(FriendlyByteBuf buffer) { SyncedDataKey<?> key = SyncedPlayerData.instance().getKey(buffer.readVarInt()); Validate.notNull(key, "Synced key does not exist for id"); DataEntry<?> entry = new DataEntry<>(key); entry.readValue(buffer); return entry; } private void readValue(FriendlyByteBuf buffer) { this.value = this.getKey().getSerializer().read(buffer); } private Tag writeValue() { return this.key.getSerializer().write(this.value); } private void readValue(Tag nbt) { this.value = this.key.getSerializer().read(nbt); } } public boolean updateMappings(HandshakeMessages.S2CSyncedPlayerData message) { this.idToDataKey.clear(); Map<ResourceLocation, Integer> keyMappings = message.getKeyMap(); for(ResourceLocation key : keyMappings.keySet()) { SyncedDataKey<?> syncedDataKey = this.registeredDataKeys.get(key); if(syncedDataKey == null) return false; int id = keyMappings.get(key); syncedDataKey.setId(id); this.idToDataKey.put(id, syncedDataKey); } return true; } public static class Provider implements ICapabilitySerializable<ListTag> { final DataHolder holder = new DataHolder(); final LazyOptional<DataHolder> optional = LazyOptional.of(() -> this.holder); @Override public ListTag serializeNBT() { ListTag list = new ListTag(); this.holder.dataMap.forEach((key, entry) -> { if(key.shouldSave()) { CompoundTag keyTag = new CompoundTag(); keyTag.putString("Key", key.getKey().toString()); keyTag.put("Value", entry.writeValue()); list.add(keyTag); } }); return list; } @Override public void deserializeNBT(ListTag listTag) { this.holder.dataMap.clear(); listTag.forEach(entryTag -> { CompoundTag keyTag = (CompoundTag) entryTag; ResourceLocation key = ResourceLocation.tryParse(keyTag.getString("Key")); Tag value = keyTag.get("Value"); SyncedDataKey<?> syncedDataKey = SyncedPlayerData.instance().registeredDataKeys.get(key); if(syncedDataKey != null && syncedDataKey.shouldSave()) { DataEntry<?> entry = new DataEntry<>(syncedDataKey); entry.readValue(value); this.holder.dataMap.put(syncedDataKey, entry); } }); } @Nonnull @Override @SuppressWarnings("ConstantConditions") public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return CAPABILITY.orEmpty(cap, this.optional); } } }
×
×
  • Create New...

Important Information

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