Player Abilities

This commit is contained in:
Kam committed 2026-01-30 05:01:54 -05:00
1 parent 601b0d721e
commit 1b8ad4dd90
92 files changed
+2610 -1025

No files matched your search

@@ -18,6 +18,7 @@ import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import kamkeel.npcs.controllers.SyncController;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
@@ -29,30 +30,46 @@ import java.util.*;
import java.util.function.Supplier;
/**
* Controller for ability types. Allows external mods to register custom ability types.
* Initialize during FMLInitializationEvent.
* Central controller for ability types and presets.
* <p>
* Also manages saved ability presets that can be reused across NPCs.
* Three maps:
* <ul>
* <li>{@code typeFactories} — keyed by typeId (lang key), creates new instances of each ability type</li>
* <li>{@code abilities} — built-in pre-configured abilities, keyed by unique name</li>
* <li>{@code customAbilities} — user-created presets, keyed by UUID</li>
* </ul>
*/
public class AbilityController implements IAbilityHandler {
public static AbilityController Instance;
public static AbilityController Instance = new AbilityController();
private final Map<String, Supplier<Ability>> factories = new LinkedHashMap<>();
private final Map<String, Supplier<Ability>> factoriesByTypeId = new LinkedHashMap<>();
private final Map<String, Ability> savedAbilities = new LinkedHashMap<>();
/** Type factories keyed by typeId (lang key, e.g. "ability.cnpc.slam"). */
private final Map<String, Supplier<Ability>> typeFactories = new LinkedHashMap<>();
/** Built-in pre-configured abilities keyed by unique name. */
private final Map<String, Ability> abilities = new LinkedHashMap<>();
/** User-created custom ability presets keyed by UUID. */
private final Map<String, Ability> customAbilities = new LinkedHashMap<>();
/** Version counter — incremented on any custom ability add/modify/delete.
* Used by AbilitySlot for cache invalidation. */
private int version = 0;
public AbilityController() {
Instance = this;
registerBuiltins();
registerBuiltinTypes();
}
// ═══════════════════════════════════════════════════════════════════════════
// LOADING / SAVING CUSTOM ABILITIES
// ═══════════════════════════════════════════════════════════════════════════
/**
* Load saved abilities from world directory.
* Called when world loads.
* Load custom ability presets from world directory.
* Called when world loads. Files are named {@code <uuid>.json}.
*/
public void load() {
savedAbilities.clear();
customAbilities.clear();
File dir = getDir();
if (!dir.exists()) {
return;
@@ -64,22 +81,22 @@ public class AbilityController implements IAbilityHandler {
for (File file : files) {
if (!file.isFile() || !file.getName().endsWith(".json")) continue;
try {
String filename = file.getName();
String uuid = filename.substring(0, filename.length() - 5); // strip .json
NBTTagCompound nbt = NBTJsonUtil.LoadFile(file);
Ability ability = fromNBT(nbt);
if (ability != null && ability.getName() != null && !ability.getName().isEmpty()) {
savedAbilities.put(ability.getName(), ability);
LogWriter.info("Loaded ability preset: " + ability.getName());
if (ability != null) {
ability.setId(uuid);
customAbilities.put(uuid, ability);
}
} catch (Exception e) {
LogWriter.error("Error loading ability preset: " + file.getAbsolutePath(), e);
LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e);
}
}
LogWriter.info("Loaded " + savedAbilities.size() + " ability presets");
LogWriter.info("Loaded " + customAbilities.size() + " custom abilities");
}
/**
* Get the ability save directory.
*/
private File getDir() {
File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities");
if (!dir.exists()) {
@@ -89,26 +106,26 @@ public class AbilityController implements IAbilityHandler {
}
/**
* Save an ability preset to disk.
*
* @param ability The ability to save
* @return true if successful
* Save a custom ability preset. If the ability has no id, generates a UUID.
* Stores in customAbilities map and writes to disk.
*/
public boolean saveAbility(Ability ability) {
if (ability == null || ability.getName() == null || ability.getName().isEmpty()) {
return false;
public boolean saveCustomAbility(Ability ability) {
if (ability == null) return false;
String uuid = ability.getId();
if (uuid == null || uuid.isEmpty()) {
uuid = UUID.randomUUID().toString();
ability.setId(uuid);
}
File dir = getDir();
String safeName = ability.getName().replaceAll("[^a-zA-Z0-9_-]", "_");
File fileNew = new File(dir, safeName + ".json_new");
File fileCurrent = new File(dir, safeName + ".json");
File fileNew = new File(dir, uuid + ".json_new");
File fileCurrent = new File(dir, uuid + ".json");
try {
NBTTagCompound nbt = ability.writeNBT();
NBTJsonUtil.SaveFile(fileNew, nbt);
// Atomic rename
if (fileCurrent.exists()) {
fileCurrent.delete();
}
@@ -117,76 +134,144 @@ public class AbilityController implements IAbilityHandler {
fileNew.delete();
}
savedAbilities.put(ability.getName(), ability);
LogWriter.info("Saved ability preset: " + ability.getName());
customAbilities.put(uuid, ability);
version++;
LogWriter.info("Saved custom ability: " + ability.getName() + " [" + uuid + "]");
SyncController.syncAllCustomAbilities();
return true;
} catch (Exception e) {
LogWriter.error("Error saving ability preset: " + ability.getName(), e);
LogWriter.error("Error saving custom ability: " + uuid, e);
return false;
}
}
/**
* Delete a saved ability preset.
*
* @param name The name of the ability to delete
* @return true if successful
* Delete a custom ability preset by UUID.
*/
public boolean deleteAbility(String name) {
if (name == null || name.isEmpty()) {
return false;
}
public boolean deleteCustomAbility(String uuid) {
if (uuid == null || uuid.isEmpty()) return false;
Ability removed = savedAbilities.remove(name);
if (removed == null) {
return false;
}
Ability removed = customAbilities.remove(uuid);
if (removed == null) return false;
File dir = getDir();
String safeName = name.replaceAll("[^a-zA-Z0-9_-]", "_");
File file = new File(dir, safeName + ".json");
File file = new File(dir, uuid + ".json");
if (file.exists()) {
file.delete();
}
LogWriter.info("Deleted ability preset: " + name);
version++;
LogWriter.info("Deleted custom ability: " + uuid);
SyncController.syncAllCustomAbilities();
return true;
}
// ═══════════════════════════════════════════════════════════════════════════
// BUILT-IN ABILITY REGISTRY
// ═══════════════════════════════════════════════════════════════════════════
/**
* Get a saved ability preset by name.
* Register a pre-configured built-in ability by name.
* These are looked up by name in {@link #resolveAbility(String)}.
*
* @param name The name of the ability
* @return A copy of the ability, or null if not found
* @param name Unique name (e.g., "Jump Attack", "Ki Blast")
* @param ability Pre-configured ability instance
*/
public Ability getSavedAbility(String name) {
Ability saved = savedAbilities.get(name);
if (saved == null) {
return null;
public void registerAbility(String name, Ability ability) {
if (abilities.containsKey(name)) {
LogWriter.info("AbilityController: Overwriting built-in ability: " + name);
}
// Return a copy so modifications don't affect the saved version
return fromNBT(saved.writeNBT());
ability.setName(name);
abilities.put(name, ability);
LogWriter.info("Registered ability: " + name);
}
// ═══════════════════════════════════════════════════════════════════════════
// RESOLUTION (used by AbilitySlot, PlayerAbilityData, etc.)
// ═══════════════════════════════════════════════════════════════════════════
/**
* Resolve an ability by key. Checks built-in abilities first (by name),
* then custom abilities (by UUID). Returns a copy safe to modify.
*
* @param key The ability name (built-in) or UUID (custom)
* @return A copy of the resolved ability, or null if not found
*/
public Ability resolveAbility(String key) {
if (key == null || key.isEmpty()) return null;
// Check built-in abilities first
Ability builtIn = abilities.get(key);
if (builtIn != null) {
return fromNBT(builtIn.writeNBT());
}
// Check custom abilities
Ability custom = customAbilities.get(key);
if (custom != null) {
return fromNBT(custom.writeNBT());
}
return null;
}
/**
* Check if a saved ability exists.
* Check if an ability key exists (either built-in or custom).
*/
public boolean hasSavedAbility(String name) {
return savedAbilities.containsKey(name);
public boolean hasAbility(String key) {
return abilities.containsKey(key) || customAbilities.containsKey(key);
}
/**
* Get all saved ability names.
*/
public Set<String> getSavedAbilityNames() {
return new LinkedHashSet<>(savedAbilities.keySet());
// ═══════════════════════════════════════════════════════════════════════════
// ACCESSORS
// ═══════════════════════════════════════════════════════════════════════════
/** Get a built-in ability by name. Returns the stored instance (not a copy). */
public Ability getAbility(String name) {
return abilities.get(name);
}
/**
* Get all saved abilities.
*/
public Collection<Ability> getSavedAbilities() {
return savedAbilities.values();
/** Get all built-in ability names. */
public Set<String> getAbilityNames() {
return new LinkedHashSet<>(abilities.keySet());
}
/** Get a custom ability by UUID. Returns the stored instance (not a copy). */
public Ability getCustomAbility(String uuid) {
return customAbilities.get(uuid);
}
/** Check if a custom ability exists by UUID. */
public boolean hasCustomAbility(String uuid) {
return customAbilities.containsKey(uuid);
}
/** Get all custom ability UUIDs. */
public Set<String> getCustomAbilityIds() {
return new LinkedHashSet<>(customAbilities.keySet());
}
/** Get the display name for a custom ability by UUID. */
public String getCustomAbilityName(String uuid) {
Ability a = customAbilities.get(uuid);
return a != null ? a.getName() : null;
}
/** Get the custom abilities map (used by SyncController). */
public Map<String, Ability> getCustomAbilities() {
return customAbilities;
}
/** Replace the custom abilities map (used by client-side sync). */
public void setCustomAbilities(Map<String, Ability> synced) {
customAbilities.clear();
customAbilities.putAll(synced);
version++;
}
/** Get the version counter (incremented on custom ability changes). */
public int getVersion() {
return version;
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -195,28 +280,37 @@ public class AbilityController implements IAbilityHandler {
@Override
public String[] getTypes() {
// Return the ability typeIds (lang keys), not the factory keys
return factoriesByTypeId.keySet().toArray(new String[0]);
return typeFactories.keySet().toArray(new String[0]);
}
@Override
public boolean hasType(String typeId) {
return factories.containsKey(typeId) || factoriesByTypeId.containsKey(typeId);
return typeFactories.containsKey(typeId);
}
@Override
public String[] getSavedNames() {
return savedAbilities.keySet().toArray(new String[0]);
public String[] getAbilityNameArray() {
return abilities.keySet().toArray(new String[0]);
}
@Override
public boolean has(String name) {
return savedAbilities.containsKey(name);
public boolean hasAbilityName(String name) {
return abilities.containsKey(name);
}
@Override
public boolean delete(String name) {
return deleteAbility(name);
public String[] getCustomAbilityIdArray() {
return customAbilities.keySet().toArray(new String[0]);
}
@Override
public boolean hasCustomAbilityId(String uuid) {
return customAbilities.containsKey(uuid);
}
@Override
public boolean deleteCustomAbilityById(String uuid) {
return deleteCustomAbility(uuid);
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -225,26 +319,23 @@ public class AbilityController implements IAbilityHandler {
/**
* Register a new ability type.
* Call during FMLInitializationEvent.
* Extracts the typeId from a temporary instance and stores in typeFactories.
*
* @param factoryKey The factory key (e.g., "cnpc:slam", "mymod:custom_ability")
* @param factoryKey Unused legacy key — the typeId from the created instance is used
* @param factory Factory lambda that creates a new instance
*/
public void registerType(String factoryKey, Supplier<Ability> factory) {
if (factories.containsKey(factoryKey)) {
LogWriter.info("AbilityController: Overwriting existing ability type: " + factoryKey);
}
factories.put(factoryKey, factory);
// Also register by the ability's actual typeId (lang key)
Ability temp = factory.get();
String abilityTypeId = temp.getTypeId();
factoriesByTypeId.put(abilityTypeId, factory);
String typeId = temp.getTypeId();
if (typeFactories.containsKey(typeId)) {
LogWriter.info("AbilityController: Overwriting type: " + typeId);
}
typeFactories.put(typeId, factory);
}
/**
* Create an ability from NBT data.
* Uses the "typeId" field to determine which type to create.
* Uses the "typeId" field to look up in typeFactories.
*/
public Ability fromNBT(NBTTagCompound nbt) {
if (nbt == null || !nbt.hasKey("typeId")) {
@@ -252,11 +343,7 @@ public class AbilityController implements IAbilityHandler {
}
String typeId = nbt.getString("typeId");
Supplier<Ability> factory = factories.get(typeId);
if (factory == null) {
// Try looking up by ability typeId (lang key)
factory = factoriesByTypeId.get(typeId);
}
Supplier<Ability> factory = typeFactories.get(typeId);
if (factory == null) {
LogWriter.info("AbilityController: Unknown ability type: " + typeId);
return null;
@@ -270,15 +357,10 @@ public class AbilityController implements IAbilityHandler {
/**
* Create a new empty ability of the given type.
*
* @param factoryKey The factory key (e.g., "cnpc:slam") or the ability typeId (e.g., "ability.cnpc.slam")
* @param typeId The ability typeId (e.g., "ability.cnpc.slam")
*/
public Ability create(String factoryKey) {
// Try direct lookup first (factory key)
Supplier<Ability> factory = factories.get(factoryKey);
if (factory == null) {
// Try looking up by ability typeId
factory = factoriesByTypeId.get(factoryKey);
}
public Ability create(String typeId) {
Supplier<Ability> factory = typeFactories.get(typeId);
if (factory == null) {
return null;
}
@@ -288,7 +370,7 @@ public class AbilityController implements IAbilityHandler {
/**
* Register built-in ability types.
*/
private void registerBuiltins() {
private void registerBuiltinTypes() {
// Melee/AOE damage abilities
registerType("cnpc:slam", AbilitySlam::new);
registerType("cnpc:heavy_hit", AbilityHeavyHit::new);