Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
Kam committed 2026-03-08 20:10:51 -04:00
commit 06dc722aca
27 files changed
+615 -153

No files matched your search

@@ -231,12 +231,12 @@ public class AbilityCommand extends CommandKamkeelBase {
}
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
String canonicalKey = abilityKey;
String displayName = abilityKey;
if (ability != null) {
canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
displayName = ability.getDisplayName();
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
return;
}
String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
String displayName = ability.getDisplayName();
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
@@ -376,8 +376,8 @@ public class AbilityCommand extends CommandKamkeelBase {
// Chained ability
String chainName = key.substring(PlayerAbilityData.CHAIN_PREFIX.length());
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainName);
String displayName = chain != null ? chain.getDisplayName() : chainName;
sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + displayName);
String display = chain != null ? chain.getDisplayName() : chainName;
sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + display);
} else {
// Regular ability
Ability ability = AbilityController.Instance.resolveAbility(key);
@@ -823,6 +823,35 @@ public class AbilityController implements IAbilityHandler {
return null;
}
/**
* Resolve a chained ability by key and return the live (non-copied) reference.
* For validation/permission checks only — do NOT expose or modify the returned chain.
* Uses the same lookup chain as {@link #resolveChainedAbility(String)}.
*/
public ChainedAbility peekChainedAbility(String key) {
if (key == null || key.isEmpty()) return null;
ChainedAbility byId = chainedAbilitiesById.get(key);
if (byId != null) return byId;
ChainedAbility chain = chainedAbilities.get(key);
if (chain != null) return chain;
for (Map.Entry<String, ChainedAbility> entry : chainedAbilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
if (!sanitizedKey.equals(key)) {
ChainedAbility sanitized = chainedAbilities.get(sanitizedKey);
if (sanitized != null) return sanitized;
}
return null;
}
public boolean canResolveChainedAbility(String key) {
if (key == null || key.isEmpty()) return false;
if (chainedAbilitiesById.containsKey(key)) return true;
@@ -1014,19 +1043,37 @@ public class AbilityController implements IAbilityHandler {
public Ability peekAbility(String key) {
if (key == null || key.isEmpty()) return null;
// Custom: UUID lookup
Ability byUuid = customAbilitiesById.get(key);
if (byUuid != null) return byUuid;
// Built-in: exact key
Ability builtIn = builtAbilities.get(key);
if (builtIn != null) return builtIn;
for (Ability ability : builtAbilities.values()) {
if (key.equals(ability.getId())) return ability;
// Built-in: case-insensitive key
for (Map.Entry<String, Ability> entry : builtAbilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
// Built-in: by ID (case-insensitive)
for (Ability ability : builtAbilities.values()) {
if (key.equalsIgnoreCase(ability.getId())) return ability;
}
// Custom: exact name
Ability custom = customAbilities.get(key);
if (custom != null) return custom;
// Custom: case-insensitive name
for (Map.Entry<String, Ability> entry : customAbilities.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
return null;
}
@@ -968,7 +968,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
java.util.function.BooleanSupplier visible) {
String sectionLabel = StatCollector.translateToLocal("ability.icon.layer") + " " + (layerIndex + 1);
defs.add(FieldDef.section(sectionLabel).tab("Effects").visibleWhen(visible));
defs.add(FieldDef.stringField("gui.texture",
defs.add(FieldDef.textureSubGui("gui.texture",
() -> icon.getLayer(layerIndex).texture,
t -> icon.setLayerTexture(layerIndex, t))
.tab("Effects").visibleWhen(visible));
@@ -40,6 +40,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
private float desiredLength = 0.0f; // Intended beam reach (grows to maxLength)
private float currentLength = 0.0f; // Actual length after block truncation (visual + collision)
private boolean fullyExtended = false;
private boolean trackOwnerOrigin = true; // When false, laser fires independently (fireAt mode)
// Direction (normalized)
private double dirX, dirY, dirZ;
@@ -158,7 +159,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
// Origin/direction tracking runs on BOTH sides so the client can render the beam.
// Once reflected, never resume owner-tracking — the laser flies in a fixed direction.
if (!reflected) {
// When trackOwnerOrigin is false (fireAt mode), skip owner tracking entirely.
if (!reflected && trackOwnerOrigin) {
updateLaserOriginAndDirection();
}
@@ -727,6 +729,14 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
this.dirZ = z;
}
public boolean isTrackOwnerOrigin() {
return trackOwnerOrigin;
}
public void setTrackOwnerOrigin(boolean track) {
this.trackOwnerOrigin = track;
}
public float getCurrentLength() {
return currentLength;
}
@@ -868,6 +878,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
this.desiredLength = nbt.getFloat("DesiredLength");
this.currentLength = nbt.getFloat("CurrentLength");
this.fullyExtended = nbt.getBoolean("FullyExtended");
this.trackOwnerOrigin = !nbt.hasKey("TrackOwnerOrigin") || nbt.getBoolean("TrackOwnerOrigin");
this.endX = nbt.getDouble("EndX");
this.endY = nbt.getDouble("EndY");
this.endZ = nbt.getDouble("EndZ");
@@ -886,6 +897,7 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
nbt.setFloat("DesiredLength", desiredLength);
nbt.setFloat("CurrentLength", currentLength);
nbt.setBoolean("FullyExtended", fullyExtended);
nbt.setBoolean("TrackOwnerOrigin", trackOwnerOrigin);
nbt.setDouble("EndX", endX);
nbt.setDouble("EndY", endY);
nbt.setDouble("EndZ", endZ);
@@ -649,7 +649,6 @@ public class PacketHandler {
PLAYER_PACKET.registerPacket(new SpecialKeyStatePacket());
PLAYER_PACKET.registerPacket(new SyncRevisionInfoPacket());
PLAYER_PACKET.registerPacket(new RequestProperSpawnData());
// CustomGUI Packets
PLAYER_PACKET.registerPacket(new CustomGuiButtonPacket());
@@ -42,7 +42,4 @@ public enum EnumPlayerPacket {
AbilityHotbarSave,
AbilityHotbarSelect,
AbilityToggle,
// NPC Spawn Data Fix
RequestSpawnData,
}
@@ -1,96 +0,0 @@
package kamkeel.npcs.network.packets.data;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumPlayerPacket;
import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.entity.EntityNPCInterface;
import java.io.IOException;
public class RequestProperSpawnData extends AbstractPacket {
public static final String packetName = "Player|SpawnData";
private static final long REQUEST_COOLDOWN_MILLIS = 1000L;
private int entityId;
public RequestProperSpawnData() {}
public RequestProperSpawnData(int entityId) {
this.entityId = entityId;
}
@SideOnly(Side.CLIENT)
public static void clear() {
// No backlog queue to clear.
}
@Override
public Enum getType() {
return EnumPlayerPacket.RequestSpawnData;
}
@Override
public PacketChannel getChannel() {
return PacketHandler.PLAYER_PACKET;
}
@Override
@SideOnly(Side.CLIENT)
public void sendData(ByteBuf out) throws IOException {
out.writeInt(this.entityId);
}
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!(player instanceof EntityPlayerMP) || player.worldObj == null || player.worldObj.isRemote)
return;
int entityId = in.readInt();
Entity entity = player.worldObj.getEntityByID(entityId);
if (entity instanceof EntityNPCInterface) {
EntityNPCInterface npc = (EntityNPCInterface) entity;
NBTTagCompound compound = npc.writeSpawnData();
compound.setInteger("EntityId", npc.getEntityId());
PacketHandler.Instance.sendToPlayer(new UpdateNpcPacket(compound), (EntityPlayerMP) player);
}
}
@SideOnly(Side.CLIENT)
public static void reportMissingData(EntityNPCInterface npc) {
if (npc == null || npc.worldObj == null || !npc.worldObj.isRemote)
return;
int entityID = npc.getEntityId();
if (entityID <= 0)
return;
long now = System.currentTimeMillis();
if (now - npc.clientFixLastRequestMillis < REQUEST_COOLDOWN_MILLIS)
return;
if (npc.clientFixAttempts >= 3)
return;
npc.clientFixLastRequestMillis = now;
npc.clientFixAttempts++;
PacketClient.sendClient(new RequestProperSpawnData(entityID));
}
@SideOnly(Side.CLIENT)
public static boolean canDoBatchUpdate() {
return false;
}
@SideOnly(Side.CLIENT)
public static void handleBacklog() {
// No batch backlog. Requests are immediate and throttled in reportMissingData().
}
}
@@ -7,6 +7,7 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -72,5 +73,6 @@ public class EffectSavePacket extends AbstractPacket {
}
NoppesUtilServer.sendCustomEffectDataAll((EntityPlayerMP) player);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, effect.writeToNBT(false));
}
}
@@ -9,6 +9,7 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.PacketUtil;
import kamkeel.npcs.network.enums.EnumItemPacketType;
import kamkeel.npcs.network.enums.EnumRequestPacket;
import kamkeel.npcs.network.packets.data.large.GuiDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -73,5 +74,6 @@ public final class LinkedItemSavePacket extends AbstractPacket {
}
NoppesUtilServer.sendLinkedItemDataAll((EntityPlayerMP) player);
GuiDataPacket.sendGuiData((EntityPlayerMP) player, linkedItem.writeToNBT(false));
}
}
+1 -1
View File
@@ -124,7 +124,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta15")
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-prerelease1")
public class CustomNpcs {
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
@@ -9,7 +9,6 @@ import kamkeel.npcs.client.renderer.lightning.LightningBolt;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
import net.minecraft.client.Minecraft;
@@ -50,7 +49,6 @@ public class ClientTickHandler {
if (mc.theWorld == null) {
ClientCacheHandler.clearCache();
ClientAbilityState.reset();
RequestProperSpawnData.clear();
if (EnergyChargePreviewManager.ClientInstance != null) {
EnergyChargePreviewManager.ClientInstance.clear();
}
@@ -175,7 +175,7 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
java.util.function.BooleanSupplier layerVisible = () -> chainIcon.getLayerCount() > idx;
String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1);
fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.stringField("gui.texture",
fieldDefs.add(FieldDef.textureSubGui("gui.texture",
() -> chainIcon.getLayer(idx).texture,
t -> chainIcon.setLayerTexture(idx, t))
.tab("Icon").visibleWhen(layerVisible));
@@ -5,6 +5,7 @@ import cpw.mods.fml.relauncher.SideOnly;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.select.GuiAnimationSelection;
import noppes.npcs.client.gui.select.GuiSoundSelection;
import noppes.npcs.client.gui.select.GuiTexturePathSelection;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.data.Animation;
@@ -175,6 +176,18 @@ public class FieldDef {
.clearable(() -> setter.accept(""));
}
public static FieldDef textureSubGui(String label, Supplier<String> getter, Consumer<String> setter) {
FieldDef def = new FieldDef(label, FieldType.STRING_BROWSE);
def.getter = () -> getter.get();
def.setter = v -> setter.accept(v != null ? v.toString() : "");
def.subGuiFactory = () -> new GuiTexturePathSelection(getter.get());
def.subGuiResultHandler = gui -> {
GuiTexturePathSelection t = (GuiTexturePathSelection) gui;
if (t.selectedResource != null) setter.accept(t.selectedResource.toString());
};
return def;
}
public static FieldDef animSubGui(String label,
Supplier<Integer> idGetter, Consumer<Integer> idSetter,
Supplier<String> nameGetter, Consumer<String> nameSetter) {
@@ -17,5 +17,6 @@ public enum FieldType {
EFFECTS_LIST,
CUSTOM_EFFECTS_LIST,
EFFECT_ACTIONS_LIST,
ROW
ROW,
STRING_BROWSE
}
@@ -334,6 +334,25 @@ public class GuiFieldBuilder {
clearId++;
break;
}
case STRING_BROWSE: {
// Text field for manual input (URLs, paths) + browse button
int btnW = 20;
int tfW = fieldW - btnW - 2;
String sVal = def.getValue() != null ? def.getValue().toString() : "";
GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, tfW, 20, sVal);
if (!def.isEnabled()) tf.setEnabled(false);
if (hover != null) tf.setHoverText(hover);
sw.addTextField(tf);
textFieldMap.put(widgetId, def);
widgetId++;
// Browse button
GuiNpcButton browseBtn = new GuiNpcButton(clearId, fieldX + tfW + 2, y, btnW, 20, "...");
if (!def.isEnabled()) browseBtn.setEnabled(false);
sw.addButton(browseBtn);
buttonFieldMap.put(clearId, def);
clearId++;
break;
}
default:
// Unknown type — skip, incrementing IDs to stay in sync
widgetId++;
@@ -349,7 +368,7 @@ public class GuiFieldBuilder {
int fieldX = colLLabel + labelW + labelPadding;
// Available width before the scrollbar
int maxW = contentRight - fieldX - 15;
if (def.getType() == FieldType.SUB_GUI && maxW > 0) {
if ((def.getType() == FieldType.SUB_GUI || def.getType() == FieldType.STRING_BROWSE) && maxW > 0) {
// SUB_GUI fields fill all available width up to the scrollbar
fieldW = maxW;
} else if (maxW > 0 && fieldW > maxW) {
@@ -374,6 +393,8 @@ public class GuiFieldBuilder {
return 120;
case SUB_GUI:
return def.hasClearAction() ? 175 : 200;
case STRING_BROWSE:
return 200;
default:
return 80;
}
@@ -434,6 +455,15 @@ public class GuiFieldBuilder {
});
}
return true;
case STRING_BROWSE:
if (def.getSubGuiFactory() != null) {
parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> {
if (def.getSubGuiResultHandler() != null) {
def.getSubGuiResultHandler().accept(sub);
}
});
}
return true;
default:
return false;
}
@@ -473,6 +503,7 @@ public class GuiFieldBuilder {
}
return false;
case STRING:
case STRING_BROWSE:
String newVal = field.getText();
Object old = def.getValue();
String oldVal = old != null ? old.toString() : "";
@@ -304,6 +304,15 @@ public class GuiAbilityDirectory extends GuiDirectoryCategorized
// Not used — we override executeMoveItems for name-based moves
}
@Override
protected void onMoveNewItem(int catId) {
String name = prevItemName;
if (name != null && !name.isEmpty()) {
PacketClient.sendClient(new AbilityCategoryMovePacket(getCategoryType(), name, catId));
if (selectedCatId >= 0) requestItemsInCategory(selectedCatId);
}
}
@Override
protected GuiScreen getWindowedVariant() {
return new GuiNpcManageAbilities(originalNpc, false);
@@ -0,0 +1,319 @@
package noppes.npcs.client.gui.select;
import com.google.common.collect.Lists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Texture path selector SubGui with a texture preview panel instead of NPC rendering.
* Reuses the cached texture data from {@link GuiTextureSelection}.
*/
public class GuiTexturePathSelection extends SubGuiInterface implements ICustomScrollListener {
private final String up = "..<" + StatCollector.translateToLocal("gui.up") + ">..";
private GuiCustomScroll scrollCategories;
private GuiCustomScroll scrollTextures;
private String location = "";
private String selectedDomain;
public ResourceLocation selectedResource;
private final HashMap<String, List<GuiTextureSelection.TextureData>> domains = new HashMap<>();
private final HashMap<String, GuiTextureSelection.TextureData> textures = new HashMap<>();
private String catSearch = "";
private String texSearch = "";
// Preview
private static final int PREVIEW_SIZE = 90;
public GuiTexturePathSelection(String texture) {
drawDefaultBackground = false;
title = "";
setBackground("menubg.png");
xSize = 366;
ySize = 226;
// Populate from GuiTextureSelection's cache (trigger a scan if needed)
long now = System.currentTimeMillis();
if (GuiTextureSelection.cachedTextures != null && !GuiTextureSelection.cachedTextures.isEmpty()
&& now - GuiTextureSelection.lastCacheTime() < GuiTextureSelection.CACHE_DURATION_MS) {
domains.putAll(GuiTextureSelection.cachedDomains());
} else {
// Force a scan by creating a temporary GuiTextureSelection
GuiTextureSelection temp = new GuiTextureSelection(null, null);
domains.putAll(GuiTextureSelection.cachedDomains());
}
if (texture != null && !texture.isEmpty()) {
selectedResource = new ResourceLocation(texture);
selectedDomain = selectedResource.getResourceDomain();
if (!domains.containsKey(selectedDomain)) {
selectedDomain = null;
}
int i = selectedResource.getResourcePath().lastIndexOf('/');
location = selectedResource.getResourcePath().substring(0, i + 1);
}
}
@Override
public void initGui() {
super.initGui();
if (selectedDomain != null) {
title = selectedDomain + ":" + location;
} else {
title = "";
}
// Buttons
this.addButton(new GuiNpcButton(2, guiLeft + xSize - 46, guiTop + ySize - 28, 42, 20, "gui.done"));
this.addButton(new GuiNpcButton(1, guiLeft + xSize - 92, guiTop + ySize - 28, 42, 20, "gui.cancel"));
// Category scroll
if (scrollCategories == null) {
scrollCategories = new GuiCustomScroll(this, 0);
scrollCategories.setSize(90, 163);
}
if (selectedDomain == null) {
scrollCategories.setList(getCatSearch());
} else {
List<String> list = new ArrayList<>();
list.add(up);
List<GuiTextureSelection.TextureData> data = domains.get(selectedDomain);
if (data != null) {
for (GuiTextureSelection.TextureData td : data) {
if (location.isEmpty() || td.path.startsWith(location) && !td.path.equals(location)) {
String path = td.path.substring(location.length());
int i = path.indexOf('/');
if (i < 0) continue;
path = path.substring(0, i);
if (!path.isEmpty() && !list.contains(path)) {
list.add(path);
}
}
}
}
scrollCategories.setList(list);
}
scrollCategories.guiLeft = guiLeft + 4;
scrollCategories.guiTop = guiTop + 14;
this.addScroll(scrollCategories);
addTextField(new GuiNpcTextField(55, this, fontRendererObj, guiLeft + 4, guiTop + 179, 90, 20, catSearch));
// Texture scroll
if (scrollTextures == null) {
scrollTextures = new GuiCustomScroll(this, 1);
scrollTextures.setSize(160, 163);
}
if (selectedDomain != null) {
textures.clear();
List<GuiTextureSelection.TextureData> data = domains.get(selectedDomain);
List<String> allList = new ArrayList<>();
String loc = location;
if (scrollCategories.hasSelected() && !scrollCategories.getSelected().equals(up)) {
loc += scrollCategories.getSelected() + '/';
}
if (data != null) {
for (GuiTextureSelection.TextureData td : data) {
if (td.path.equals(loc) && !allList.contains(td.name)) {
allList.add(td.name);
textures.put(td.name, td);
}
}
}
scrollTextures.setList(filterTexSearch(allList));
}
if (selectedResource != null) {
scrollTextures.setSelected(selectedResource.getResourcePath());
}
scrollTextures.guiLeft = guiLeft + 95;
scrollTextures.guiTop = guiTop + 14;
this.addScroll(scrollTextures);
addTextField(new GuiNpcTextField(66, this, fontRendererObj, guiLeft + 95, guiTop + 179, 160, 20, texSearch));
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
drawTexturePreview();
}
private void drawTexturePreview() {
int previewX = guiLeft + 260;
int previewY = guiTop + 14;
// Draw border/background for preview area
drawRect(previewX - 1, previewY - 1, previewX + PREVIEW_SIZE + 1, previewY + PREVIEW_SIZE + 1, 0xFFA0A0A0);
drawRect(previewX, previewY, previewX + PREVIEW_SIZE, previewY + PREVIEW_SIZE, 0xFF000000);
if (selectedResource == null) {
String none = StatCollector.translateToLocal("gui.none");
int w = fontRendererObj.getStringWidth(none);
fontRendererObj.drawString(none, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080);
return;
}
ImageData imageData = ClientCacheHandler.getImageData(selectedResource.toString());
if (imageData == null || !imageData.imageLoaded()) {
String loading = "...";
int w = fontRendererObj.getStringWidth(loading);
fontRendererObj.drawString(loading, previewX + (PREVIEW_SIZE - w) / 2, previewY + PREVIEW_SIZE / 2 - 4, 0xFF808080);
return;
}
int texW = imageData.getTotalWidth();
int texH = imageData.getTotalHeight();
if (texW <= 0 || texH <= 0) return;
// Scale to fit within PREVIEW_SIZE while maintaining aspect ratio
float scale = Math.min((float) PREVIEW_SIZE / texW, (float) PREVIEW_SIZE / texH);
int drawW = (int) (texW * scale);
int drawH = (int) (texH * scale);
int drawX = previewX + (PREVIEW_SIZE - drawW) / 2;
int drawY = previewY + (PREVIEW_SIZE - drawH) / 2;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
imageData.bindTexture();
drawScaledTexture(drawX, drawY, drawW, drawH);
// Draw dimensions label below preview
String dims = texW + " x " + texH;
int dw = fontRendererObj.getStringWidth(dims);
fontRendererObj.drawString(dims, previewX + (PREVIEW_SIZE - dw) / 2, previewY + PREVIEW_SIZE + 4, 0xFFCCCCCC);
// Draw resource path below dimensions
String path = selectedResource.toString();
if (fontRendererObj.getStringWidth(path) > PREVIEW_SIZE + 4) {
// Truncate from the left
while (fontRendererObj.getStringWidth("..." + path) > PREVIEW_SIZE + 4 && path.length() > 1) {
path = path.substring(1);
}
path = "..." + path;
}
int pw = fontRendererObj.getStringWidth(path);
fontRendererObj.drawString(path, previewX + (PREVIEW_SIZE - pw) / 2, previewY + PREVIEW_SIZE + 15, 0xFF999999);
}
private void drawScaledTexture(int x, int y, int width, int height) {
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.addVertexWithUV(x, y + height, zLevel, 0.0, 1.0);
tess.addVertexWithUV(x + width, y + height, zLevel, 1.0, 1.0);
tess.addVertexWithUV(x + width, y, zLevel, 1.0, 0.0);
tess.addVertexWithUV(x, y, zLevel, 0.0, 0.0);
tess.draw();
}
@Override
protected void actionPerformed(GuiButton guibutton) {
super.actionPerformed(guibutton);
if (guibutton.id == 1) {
// Cancel - clear selection
selectedResource = null;
}
close();
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
if (scroll == scrollTextures) {
if (scroll.id == 1) {
GuiTextureSelection.TextureData data = textures.get(scroll.getSelected());
if (data != null) {
selectedResource = new ResourceLocation(selectedDomain, data.absoluteName);
}
}
} else {
initGui();
scrollTextures.resetScroll();
}
}
@Override
public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) {
if (scroll == scrollCategories) {
if (selectedDomain == null) {
selectedDomain = selection;
} else if (selection.equals(up)) {
int i = location.lastIndexOf('/', location.length() - 2);
if (i < 0) {
if (location.isEmpty()) {
selectedDomain = null;
}
location = "";
} else {
location = location.substring(0, i + 1);
}
} else {
location = location + selection + '/';
}
scrollCategories.selected = -1;
scrollTextures.selected = -1;
initGui();
} else {
// Double-click on texture = confirm
close();
}
}
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
if (getTextField(55) != null && getTextField(55).isFocused()) {
if (!catSearch.equals(getTextField(55).getText())) {
catSearch = getTextField(55).getText().toLowerCase();
scrollCategories.resetScroll();
if (selectedDomain == null) {
scrollCategories.setList(getCatSearch());
}
}
}
if (getTextField(66) != null && getTextField(66).isFocused()) {
if (!texSearch.equals(getTextField(66).getText())) {
texSearch = getTextField(66).getText().toLowerCase();
scrollTextures.resetScroll();
initGui();
}
}
}
private List<String> getCatSearch() {
if (catSearch.isEmpty()) {
return new ArrayList<>(domains.keySet());
}
List<String> list = new ArrayList<>();
for (String name : domains.keySet()) {
if (name.toLowerCase().contains(catSearch))
list.add(name);
}
return list;
}
private List<String> filterTexSearch(List<String> source) {
if (texSearch.isEmpty()) {
return source;
}
List<String> list = new ArrayList<>();
for (String name : source) {
if (name.toLowerCase().contains(texSearch))
list.add(name);
}
return list;
}
}
@@ -54,11 +54,21 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol
private final HashMap<String, TextureData> textures = new HashMap<>();
// --- Cache static fields ---
private static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds
static final long CACHE_DURATION = 180000L; // 3 minutes in milliseconds
private static long lastCacheTime = 0;
private static HashMap<String, List<TextureData>> cachedDomains = new HashMap<>();
public static HashMap<String, TextureData> cachedTextures = new HashMap<>();
public static final long CACHE_DURATION_MS = CACHE_DURATION;
public static long lastCacheTime() {
return lastCacheTime;
}
public static HashMap<String, List<TextureData>> cachedDomains() {
return cachedDomains;
}
public GuiTextureSelection(EntityNPCInterface npc, String texture) {
this.npc = npc;
drawDefaultBackground = false;
@@ -145,6 +145,12 @@ public abstract class GuiDirectoryCategorized extends GuiDirectory
protected void drawItemDetails(int x, int y, int w) {}
protected void saveCurrentItem() {}
/**
* Hook for name-based items (e.g. abilities) that don't use numeric IDs.
* Called when a new item needs to be moved to a category but getSelectedItemId() returns -1.
*/
protected void onMoveNewItem(int catId) {}
protected void setPrevItemName(String name) {
this.prevItemName = name;
}
@@ -728,9 +734,13 @@ public abstract class GuiDirectoryCategorized extends GuiDirectory
return;
}
onItemReceived(compound);
if (pendingNewItemCatId > 0 && hasSelectedItem() && getSelectedItemId() >= 0) {
sendMovePacket(getSelectedItemId(), pendingNewItemCatId);
if (selectedCatId >= 0) requestItemsInCategory(selectedCatId);
if (pendingNewItemCatId > 0 && hasSelectedItem()) {
if (getSelectedItemId() >= 0) {
sendMovePacket(getSelectedItemId(), pendingNewItemCatId);
if (selectedCatId >= 0) requestItemsInCategory(selectedCatId);
} else {
onMoveNewItem(pendingNewItemCatId);
}
}
pendingNewItemCatId = -1;
initGui();
@@ -11,6 +11,7 @@ public class ConfigMixin {
public static Configuration config;
public final static String CLIENT = "CLIENT";
public final static String SERVER = "SERVER";
public final static String GENERAL = "GENERAL";
/**
@@ -25,6 +26,9 @@ public class ConfigMixin {
public static Property FirstPersonAnimationMixinProperty;
public static boolean FirstPersonAnimationMixin = true;
public static Property EntitySpawnFixMixinProperty;
public static boolean EntitySpawnFixMixin = true;
public static void init(File configFile) {
config = new Configuration(configFile);
@@ -43,6 +47,9 @@ public class ConfigMixin {
} else {
FirstPersonAnimationMixin = false;
}
EntitySpawnFixMixinProperty = config.get(SERVER, "Entity Spawn Packet Fix", true, "Fixes a Forge race condition where mod entity spawn packets can be lost or sent to the wrong player. This prevents invisible entities on servers with multiple players.");
EntitySpawnFixMixin = EntitySpawnFixMixinProperty.getBoolean(true);
} catch (Exception e) {
FMLLog.log(Level.ERROR, e, "CNPC+ has had a problem loading its mixin configuration");
} finally {
@@ -3,6 +3,7 @@ package noppes.npcs.controllers.data;
import kamkeel.npcs.network.packets.request.script.AbilityScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.janino.EventJaninoScript;
/**
* Script handler for ability scripts.
@@ -35,6 +36,11 @@ public class AbilityScript extends SingleScriptHandler implements IScriptHandler
return ScriptContext.ABILITY;
}
@Override
public IScriptUnit createJaninoScriptUnit() {
return new EventJaninoScript(ScriptContext.ABILITY);
}
@Override
public String noticeString() {
return !abilityId.isEmpty() ? "Ability[" + abilityId + "]" : "Ability";
@@ -14,7 +14,6 @@ import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.packets.data.ChatBubblePacket;
import kamkeel.npcs.network.packets.data.QuestCompletionPacket;
import kamkeel.npcs.network.packets.data.RequestProperSpawnData;
import kamkeel.npcs.network.packets.data.SoundManagementPacket;
import kamkeel.npcs.network.packets.data.npc.UpdateNpcPacket;
import kamkeel.npcs.network.packets.data.npc.WeaponNpcPacket;
@@ -234,10 +233,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
public FlyingMoveHelper flyMoveHelper = new FlyingMoveHelper(this);
public PathNavigate flyNavigator = new PathNavigateFlying(this, worldObj);
// For Client-Side Use Only
public int clientFixAttempts = 0;
public long clientFixLastRequestMillis = 0L;
public EntityNPCInterface(World world) {
super(world);
try {
@@ -1846,7 +1841,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
NBTTagCompound compound = new NBTTagCompound();
display.writeToNBT(compound);
compound.setDouble("MaxHealth", stats.maxHealth);
compound.setFloat("CurrentHealth", getHealth());
compound.setTag("Armor", NBTTags.nbtItemStackList(inventory.getArmor()));
compound.setTag("Weapons", NBTTags.nbtItemStackList(inventory.getWeapons()));
compound.setInteger("Speed", ais.getWalkingSpeed());
@@ -1889,19 +1883,11 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
try {
readSpawnData(ByteBufUtils.readNBT(buf));
} catch (IOException e) {
if (this.worldObj != null && this.worldObj.isRemote) {
RequestProperSpawnData.reportMissingData(this);
}
e.printStackTrace();
}
}
public void readSpawnData(NBTTagCompound compound) {
if (this.worldObj != null && this.worldObj.isRemote) {
if(requestClientFix(compound))
return;
}
float preservedHealth = getHealth();
stats.maxHealth = compound.getDouble("MaxHealth");
ais.setWalkingSpeed(compound.getInteger("Speed"));
stats.hideKilledBody = compound.getBoolean("DeadBody");
@@ -1926,12 +1912,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
ais.bodyOffsetY = compound.getFloat("OffsetY");
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(stats.maxHealth);
if (compound.hasKey("CurrentHealth", Constants.NBT.TAG_FLOAT)) {
setHealth(MathHelper.clamp_float(compound.getFloat("CurrentHealth"), 0.0F, getMaxHealth()));
} else {
// Keep previous client health if packet came from an older sender format.
setHealth(MathHelper.clamp_float(preservedHealth, 0.0F, getMaxHealth()));
}
inventory.setArmor(NBTTags.getItemStackList(compound.getTagList("Armor", 10)));
inventory.setWeapons(NBTTags.getItemStackList(compound.getTagList("Weapons", 10)));
advanced.setRole(compound.getInteger("Role"));
@@ -2000,16 +1980,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti
}
}
public boolean requestClientFix(NBTTagCompound compound){
if((compound.hasNoTags() || !compound.hasKey("MaxHealth", Constants.NBT.TAG_DOUBLE))){
RequestProperSpawnData.reportMissingData(this);
return true;
}
clientFixAttempts = 0;
clientFixLastRequestMillis = 0L;
return false;
}
public boolean canBreatheUnderwater() {
return stats.drowningType != 1;
}
@@ -57,6 +57,14 @@ public class CustomNPCsMixinPlugin implements IMixinConfigPlugin {
mixins.add("MixinItemStack");
}
// Server Only Mixins
if (!client) {
if (ConfigMixin.EntitySpawnFixMixin) {
mixins.add("MixinEntityTrackerEntry");
}
}
return mixins;
}
@@ -0,0 +1,77 @@
package noppes.npcs.mixin;
import cpw.mods.fml.common.network.internal.FMLMessage;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.common.registry.EntityRegistry;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTrackerEntry;
import net.minecraft.network.Packet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.lang.reflect.Method;
/**
* Fixes a race condition in Forge's FMLNetworkHandler.getEntitySpawningPacket.
*
* Forge uses a single static shared EmbeddedChannel to serialize all mod entity
* spawn packets. The channel's generatePacketFrom method does a non-atomic
* write-then-poll, so concurrent calls can swap, lose, or misdeliver packets.
*
* This mixin bypasses the shared channel by serializing directly into a fresh
* ByteBuf per call, eliminating the race condition entirely.
*/
@Mixin(EntityTrackerEntry.class)
public abstract class MixinEntityTrackerEntry {
private static final Logger LOGGER = LogManager.getLogger("CustomNPCs-SpawnFix");
private static Method toBytesMethod;
static {
try {
toBytesMethod = FMLMessage.EntitySpawnMessage.class.getDeclaredMethod("toBytes", ByteBuf.class);
toBytesMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
LOGGER.fatal("Failed to find FMLMessage.EntitySpawnMessage.toBytes - entity spawn fix will not work", e);
}
}
@Shadow
public Entity myEntity;
@Redirect(
method = "func_151260_c",
at = @At(
value = "INVOKE",
target = "Lcpw/mods/fml/common/network/internal/FMLNetworkHandler;getEntitySpawningPacket(Lnet/minecraft/entity/Entity;)Lnet/minecraft/network/Packet;"
),
remap = false
)
private Packet cnpcplus$getEntitySpawningPacket(Entity entity) {
if (toBytesMethod == null) {
return null;
}
EntityRegistry.EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entity.getClass(), false);
if (er == null || er.usesVanillaSpawning()) {
return null;
}
FMLMessage.EntitySpawnMessage message = new FMLMessage.EntitySpawnMessage(er, entity, er.getContainer());
ByteBuf buf = Unpooled.buffer();
buf.writeByte(2);
try {
toBytesMethod.invoke(message, buf);
} catch (Throwable e) {
LOGGER.warn("Failed to serialize entity spawn packet for {}", entity.getClass().getName(), e);
buf.release();
return null;
}
return new FMLProxyPacket(buf, "FML");
}
}
@@ -3,6 +3,7 @@ package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityAbilityBeam;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.api.entity.IEnergyBeam;
import noppes.npcs.api.entity.IEntity;
import noppes.npcs.scripted.constants.EntityType;
public class ScriptEnergyBeam<T extends EntityAbilityBeam> extends ScriptEnergyProjectile<T> implements IEnergyBeam {
@@ -62,4 +63,22 @@ public class ScriptEnergyBeam<T extends EntityAbilityBeam> extends ScriptEnergyP
protected void launchFromOwner(EntityLivingBase target) {
entity.startFiring(target);
}
@Override
public void fireAt(IEntity target) {
entity.setAttachedToOwner(false);
super.fireAt(target);
}
@Override
public void fireAt(double x, double y, double z) {
entity.setAttachedToOwner(false);
super.fireAt(x, y, z);
}
@Override
public void fireDirection(float yaw, float pitch) {
entity.setAttachedToOwner(false);
super.fireDirection(yaw, pitch);
}
}
@@ -3,6 +3,7 @@ package noppes.npcs.scripted.entity;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.entity.EntityLivingBase;
import noppes.npcs.api.entity.IEnergyLaser;
import noppes.npcs.api.entity.IEntity;
import noppes.npcs.scripted.constants.EntityType;
public class ScriptEnergyLaser<T extends EntityAbilityLaser> extends ScriptEnergyProjectile<T> implements IEnergyLaser {
@@ -95,8 +96,15 @@ public class ScriptEnergyLaser<T extends EntityAbilityLaser> extends ScriptEnerg
entity.startMoving(target);
}
@Override
public void fireAt(IEntity target) {
entity.setTrackOwnerOrigin(false);
super.fireAt(target);
}
@Override
public void fireAt(double x, double y, double z) {
entity.setTrackOwnerOrigin(false);
double dx = x - entity.posX;
double dy = y - entity.posY;
double dz = z - entity.posZ;
@@ -106,4 +114,17 @@ public class ScriptEnergyLaser<T extends EntityAbilityLaser> extends ScriptEnerg
}
ensureSpawned();
}
@Override
public void fireDirection(float yaw, float pitch) {
entity.setTrackOwnerOrigin(false);
float yawRad = (float) Math.toRadians(yaw);
float pitchRad = (float) Math.toRadians(pitch);
entity.setDirection(
-Math.sin(yawRad) * Math.cos(pitchRad),
-Math.sin(pitchRad),
Math.cos(yawRad) * Math.cos(pitchRad)
);
ensureSpawned();
}
}