diff --git a/build.gradle b/build.gradle index a05d5d7a5..35dede377 100644 --- a/build.gradle +++ b/build.gradle @@ -6,7 +6,7 @@ plugins { id "dts.typescript-generator" } -version = "1.11-beta1" +version = "1.11-beta3" group= "kamkeel.customnpc-plus" archivesBaseName = "CustomNPC-Plus" diff --git a/gradle-plugins b/gradle-plugins new file mode 160000 index 000000000..f1c82c10c --- /dev/null +++ b/gradle-plugins @@ -0,0 +1 @@ +Subproject commit f1c82c10c8c92eaaf55044cf931da5e1c7a2668f diff --git a/gradle-plugins/.gitignore b/gradle-plugins/.gitignore deleted file mode 100644 index 22bff6717..000000000 --- a/gradle-plugins/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -/.gradle -/build -/out -/bin -/.idea -/.vscode -/.settings -.project -.classpath \ No newline at end of file diff --git a/gradle-plugins/README.md b/gradle-plugins/README.md deleted file mode 100644 index 1e0e7fba2..000000000 --- a/gradle-plugins/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# dts-gradle-plugin - -This repo contains the Gradle plugin for generating TypeScript `.d.ts` files for the CustomNPC-Plus API. - -These files are used for the generation of auto-completion suggestions and type/interface documentation when scripting -in the Script Editor in-game. - -### Implementation using JitPack - -Add JitPack to the buildscript and depend on the plugin JAR. Using `main-SNAPSHOT` will build the latest `main` commit; -for reproducible builds use a tag or commit hash instead. - -`settings.gradle` -```gradle -pluginManagement { - resolutionStrategy { - eachPlugin { - if(requested.id.toString() == "dts.typescript-generator") { - useModule("com.github.bigguy345:dts-gradle-plugin:main-SNAPSHOT") - } - } - } - - - repositories { - maven { url "https://jitpack.io" } - gradlePluginPortal() - mavenCentral() - mavenLocal() - } -} -``` - - - - -`build.gradle`: - -```gradle -plugins { - id 'dts.typescript-generator' -} - -// ============================================================================ -// TypeScript Definition Generation Task -// Generates .d.ts files from Java API sources for scripting IDE support -// ============================================================================ -// TypeScript plugin is applied above in the main plugins block - -tasks.named("generateTypeScriptDefinitions").configure { - // Source directories containing the Java API code - sourceDirectories = ['src/main/java'] - - // Packages in source directories to generate .d.ts files for - apiPackages = ['noppes.npcs.api'] as Set - - // Output directory for the generated .d.ts files - // Must be within resources/assets/${modId}/api to be detected by CNPC+ - outputDirectory = "src/main/resources/assets/${modId}/api" - - // Whether to clean old generated files before regenerating - cleanOutputFirst = true - - // Optional: copy external patch .d.ts files into assets//api/patches - patchesDirectory = "dts-patches" -} - - -// Optional: To ensure definitions are generated on processing resources on jar build -// But in most cases, you may want to run the task manually when needed -// processResources.dependsOn generateTypeScriptDefinitions -``` - ---- - -## Patches (optional overrides) - -Use `dts-patches/` to override or refine generated types. Files in this folder are copied to -`assets//api/patches` after generation. - -### Example: override `IPlayer.getDBCPlayer()` to return `IDBCAddon` instead of `IDBCPlayer` - -File: `dts-patches/IPlayer.d.ts` - -```ts -/** - * DBC Addon patch for IPlayer - * @javaFqn noppes.npcs.api.entity.IPlayer - */ -export interface IPlayer { - getDBCPlayer(): IDBCAddon; -} -``` - diff --git a/gradle-plugins/build.gradle b/gradle-plugins/build.gradle deleted file mode 100644 index 0deda7acc..000000000 --- a/gradle-plugins/build.gradle +++ /dev/null @@ -1,50 +0,0 @@ -plugins { - id 'groovy-gradle-plugin' - id 'maven-publish' -} - -group = 'dts' -version = '1.0.0' - -repositories { - mavenCentral() -} - -dependencies { - implementation gradleApi() - implementation localGroovy() -} - -// Configure source sets if building as standalone -sourceSets { - main { - groovy { - srcDirs = ['src/main/groovy'] - } - resources { - srcDirs = ['src/main/resources'] - } - } -} - -gradlePlugin { - plugins { - typescriptGenerator { - id = 'dts.typescript-generator' - implementationClass = 'dts.TypeScriptGeneratorPlugin' - displayName = 'TypeScript Definition Generator' - description = 'Generates TypeScript definition files from Java API sources' - } - } -} - -publishing { - repositories { - mavenLocal() - } -} - -// Handle duplicate resources -tasks.processResources { - duplicatesStrategy = 'include' -} diff --git a/gradle-plugins/settings.gradle b/gradle-plugins/settings.gradle deleted file mode 100644 index 14cad52d4..000000000 --- a/gradle-plugins/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'dts-gradle-plugin' diff --git a/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy b/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy deleted file mode 100644 index b62e6cedc..000000000 --- a/gradle-plugins/src/main/groovy/dts/GenerateTypeScriptTask.groovy +++ /dev/null @@ -1,175 +0,0 @@ -package dts - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.Optional - -/** - * Gradle task that generates TypeScript definition (.d.ts) files from Java API sources. - * - * Usage in build.gradle: - * - * tasks.withType(GenerateTypeScriptTask).configureEach { - * sourceDirectories = ['src/api/java'] // Strings are converted to Files - * outputDirectory = 'src/main/resources/${modid}/api' // String converted to File - * apiPackages = ['noppes.npcs.api', 'kamkeel.npcdbc.api'] - * } - */ -abstract class GenerateTypeScriptTask extends DefaultTask { - - // Accept Object types (String or File) with @Internal annotation - @Internal - List sourceDirectories = [] - - @Internal - Object outputDirectory - - @Input - Set apiPackages = [] - - @Input - Boolean cleanOutputFirst = false - - @Input - List excludePatterns = [] - - @Internal - Object patchesDirectory - - // Provide task input/output properties that Gradle can validate - @InputFiles - protected List getResolvedSourceDirectories() { - return sourceDirectories.collect { obj -> - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - } - - @OutputDirectory - protected File getResolvedOutputDirectory() { - def obj = outputDirectory - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - - @Optional - @InputDirectory - protected File getResolvedDtsPatchesDirectory() { - if (patchesDirectory == null) return null - def obj = patchesDirectory - if (obj instanceof File) return obj - String pathStr = obj.toString() - if (pathStr.contains('${modid}')) { - String modid = project.archivesBaseName ?: 'mod' - pathStr = pathStr.replace('${modid}', modid) - } - File f = new File(pathStr) - if (!f.isAbsolute()) { - f = new File(project.projectDir, pathStr) - } - return f - } - - /** - * Converts a value (String or File) to a File object. - * Supports special tokens like ${modid}. - */ - // conversion logic inlined into getters to avoid calling private helper at configuration time - - GenerateTypeScriptTask() { - group = 'api' - description = 'Generates TypeScript definition files from Java API sources' - } - - @TaskAction - void generate() { - List srcDirs = getResolvedSourceDirectories() - File outDir = getResolvedOutputDirectory() - File patchesDir = getResolvedDtsPatchesDirectory() - - logger.lifecycle("=".multiply(60)) - logger.lifecycle("Generating TypeScript definitions...") - logger.lifecycle("=".multiply(60)) - - if (srcDirs.isEmpty()) { - logger.warn("No source directories specified!") - return - } - - // Validate directories - srcDirs.each { dir -> - if (!dir.exists()) { - logger.warn("Source directory does not exist: ${dir}") - } else { - logger.lifecycle("Source: ${dir}") - } - } - - logger.lifecycle("Output: ${outDir}") - logger.lifecycle("API Packages: ${apiPackages}") - - // Clean output if requested - if (cleanOutputFirst && outDir.exists()) { - logger.lifecycle("Cleaning output directory...") - outDir.eachFileRecurse { file -> - if (file.name.endsWith('.d.ts') && !file.name.equals('minecraft-raw.d.ts') && !file.name.equals('forge-events-raw.d.ts')) { - file.delete() - } - } - } - - // Create converter and process - JavaToTypeScriptConverter converter = new JavaToTypeScriptConverter(outDir, apiPackages) - - List validDirs = srcDirs.findAll { it.exists() } - if (validDirs.isEmpty()) { - logger.error("No valid source directories found!") - return - } - - converter.processDirectories(validDirs, logger) - - if (patchesDir != null) { - if (!patchesDir.exists()) { - logger.lifecycle("Patches directory does not exist: ${patchesDir}") - } else { - File patchOutputDir = new File(outDir, "patches") - if (patchOutputDir.exists()) { - patchOutputDir.deleteDir() - } - project.copy { - from patchesDir - into patchOutputDir - } - logger.lifecycle("Copied .d.ts patches to: ${patchOutputDir}") - } - } - - logger.lifecycle("=".multiply(60)) - logger.lifecycle("TypeScript definition generation complete!") - logger.lifecycle("=".multiply(60)) - } -} diff --git a/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy b/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy deleted file mode 100644 index 9d96633ed..000000000 --- a/gradle-plugins/src/main/groovy/dts/JavaToTypeScriptConverter.groovy +++ /dev/null @@ -1,1353 +0,0 @@ -package dts - -import groovy.transform.TypeChecked -import org.gradle.api.logging.Logger - -import java.util.regex.Pattern -import java.util.regex.Matcher - -/** - * Parses Java source files and converts them to TypeScript definition (.d.ts) files. - * Handles interfaces, classes, nested types, generics, and JavaDoc preservation. - */ -class JavaToTypeScriptConverter { - - // Common Java type mappings to TypeScript - private static final Map PRIMITIVE_MAPPINGS = [ - 'void': 'void', - 'boolean': 'boolean', - 'byte': 'number', - 'short': 'number', - 'int': 'number', - 'long': 'number', - 'float': 'number', - 'double': 'number', - 'char': 'string', - 'String': 'string', - 'Object': 'any', - 'Boolean': 'boolean', - 'Byte': 'number', - 'Short': 'number', - 'Integer': 'number', - 'Long': 'number', - 'Float': 'number', - 'Double': 'number', - 'Character': 'string', - 'Number': 'number', - ] - - // Java functional interface mappings - private static final Map FUNCTIONAL_MAPPINGS = [ - 'Consumer': '(arg: %s) => void', - 'Supplier': '() => %s', - 'Function': '(arg: %s) => %s', - 'Predicate': '(arg: %s) => boolean', - 'BiConsumer': '(arg1: %s, arg2: %s) => void', - 'BiFunction': '(arg1: %s, arg2: %s) => %s', - 'Runnable': '() => void', - 'Callable': '() => %s', - ] - - // Packages that are part of API (generate imports to local .d.ts) - private Set apiPackages = [] as Set - - // Base output directory for generated files - private File outputDir - - // Track all generated types for index.d.ts - private List generatedTypes = [] - - // Track hooks for hooks.d.ts - // Hooks are organized by their parent event type (e.g., INpcEvent, IPlayerEvent) - // The namespace in hooks.d.ts matches the event type name directly - private Map> hooks = [:] - - private Logger logger; - - JavaToTypeScriptConverter(File outputDir, Set apiPackages) { - this.outputDir = outputDir - this.apiPackages = apiPackages - } - - /** - * Process all Java files in the given directories - */ - void processDirectories(List sourceDirs, Logger logger) { - this.logger = logger - sourceDirs.each { dir -> - if (dir.exists()) { - processDirectory(dir, dir) - } - } - - // Generate index.d.ts - generateIndexFile() - - // Generate hooks.d.ts - generateHooksFile() - } - - private void processDirectory(File dir, File baseDir) { - dir.eachFileRecurse { file -> - if (file.name.endsWith('.java') && !file.name.equals('package-info.java')) { - // Early filtering - check if file matches any API package - String relativePath = baseDir.toPath().relativize(file.toPath()).toString() - String packagePath = relativePath.replace('\\', '/').replace('.java', '').replace('/', '.') - - // Only process if the package starts with one of the apiPackages - boolean shouldProcess = apiPackages.any { apiPkg -> packagePath.startsWith(apiPkg) } - - if (shouldProcess) - processJavaFile(file, baseDir) - } - } - } - - - - /** - * Process a single Java file - */ - void processJavaFile(File javaFile, File baseDir) { - String content = javaFile.text - ParsedJavaFile parsed = parseJavaFile(content) - - if (parsed == null) { - logger.warn("Failed to parse ${javaFile.name} - parseJavaFile returned null") - return - } - if (parsed.types.isEmpty()) { - logger.warn("No types extracted from ${javaFile.name} - package: ${parsed.packageName}") - return - } - // logger.lifecycle("Successfully parsed ${javaFile.name}: ${parsed.types.size()} type(s) found: ${parsed.types*.name}") - - // Determine output path - String relativePath = baseDir.toPath().relativize(javaFile.toPath()).toString() - String dtsPath = relativePath.replace('.java', '.d.ts').replace('\\', '/') - File outputFile = new File(outputDir, dtsPath) - - // Generate TypeScript content - String tsContent = generateTypeScript(parsed, dtsPath) - - // Write file - outputFile.parentFile.mkdirs() - outputFile.text = tsContent - - // Track for index generation - parsed.types.each { type -> - generatedTypes << new TypeInfo( - name: type.name, - packageName: parsed.packageName, - filePath: dtsPath, - isClass: type.isClass, - isInterface: type.isInterface, - extendsType: type.extendsType - ) - - // Track nested types - type.nestedTypes.each { nested -> - generatedTypes << new TypeInfo( - name: "${type.name}.${nested.name}", - packageName: parsed.packageName, - filePath: dtsPath, - isClass: nested.isClass, - isInterface: nested.isInterface, - parentType: type.name - ) - } - } - - // Collect hooks from event interfaces - collectHooks(parsed) - } - - /** - * Parse a Java file into structured data - */ - ParsedJavaFile parseJavaFile(String content) { - ParsedJavaFile result = new ParsedJavaFile() - - // Extract package - def packageMatcher = content =~ /package\s+([\w.]+)\s*;/ - if (packageMatcher.find()) { - result.packageName = packageMatcher.group(1) - } - - // Extract imports - def importMatcher = content =~ /import\s+([\w.*]+)\s*;/ - while (importMatcher.find()) { - result.imports << importMatcher.group(1) - } - - // Parse types (interfaces and classes) - parseTypes(content, result) - - return result - } - - private void parseTypes(String content, ParsedJavaFile result) { - // Match ONLY top-level (public) interface or class declarations - // Top-level types MUST have 'public' modifier in Java - // Use a simpler pattern first, then manually extract type parameters - // Handle modifiers like abstract, final, static (in any order) - def typePattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?public\s+(?:(?:abstract|final|static)\s+)*(interface|class)\s+(\w+)/ - - def matcher = content =~ typePattern - while (matcher.find()) { - JavaType type = new JavaType() - type.jsdoc = matcher.group(1)?.trim() - type.isInterface = matcher.group(2) == 'interface' - type.isClass = matcher.group(2) == 'class' - type.name = matcher.group(3) - - // Manually extract type parameters with balanced bracket matching - int afterName = matcher.end() - String remainder = content.substring(afterName) - - // Check if there are type parameters - if (remainder.trim().startsWith('<')) { - int startIndex = remainder.indexOf('<') - int depth = 0 - int endIndex = -1 - - for (int i = startIndex; i < remainder.length(); i++) { - char c = remainder.charAt(i) - if (c == '<') { - depth++ - } else if (c == '>') { - depth-- - if (depth == 0) { - endIndex = i - break - } - } - } - - if (endIndex > startIndex) { - type.typeParams = remainder.substring(startIndex + 1, endIndex).trim() - // Parse type parameters with full class names - type.parsedTypeParams = parseTypeParams(type.typeParams, result) - remainder = remainder.substring(endIndex + 1) - } - } - - // Now parse extends and implements - def extendsPattern = ~/\s+extends\s+([\w.<>,\s]+?)(?:\s+implements|\s*\{)/ - def extendsMatcher = remainder =~ extendsPattern - if (extendsMatcher.find()) { - type.extendsType = extendsMatcher.group(1)?.trim() - } - - def implementsPattern = ~/\s+implements\s+([\w.<>,\s]+?)\s*\{/ - def implementsMatcher = remainder =~ implementsPattern - if (implementsMatcher.find()) { - type.implementsTypes = implementsMatcher.group(1)?.split(',')?.collect { it.trim() } ?: [] - } else { - type.implementsTypes = [] - } - - // Find the opening brace for the body - int braceIndex = content.indexOf('{', afterName) - if (braceIndex == -1) { - continue // No body found, skip this type - } - - // Find the body of this type - int bodyStart = braceIndex - int bodyEnd = findMatchingBrace(content, bodyStart) - if (bodyEnd > bodyStart) { - String body = content.substring(bodyStart + 1, bodyEnd) - - // Parse methods - pass original body for JSDoc extraction - type.methods = parseMethods(body) - - // Parse nested types - type.nestedTypes = parseNestedTypes(body, type.name) - - // Parse fields (for classes) - if (type.isClass) { - type.fields = parseFields(body) - } - } - - result.types << type - } - } - - /** - * Remove nested type bodies from a string so we only parse top-level methods - */ - private String removeNestedTypeBodies(String body) { - StringBuilder result = new StringBuilder() - int depth = 0 - boolean inNestedType = false - int nestedStart = -1 - - // Find nested type declarations and remove their bodies - def nestedPattern = ~/(?:public\s+)?(?:static\s+)?(interface|class)\s+\w+/ - - int i = 0 - while (i < body.length()) { - char c = body.charAt(i) - - if (c == '{') { - if (!inNestedType) { - // Check if this brace starts a nested type - String before = body.substring(Math.max(0, i - 100), i) - if (before =~ /(?:public\s+)?(?:static\s+)?(?:interface|class)\s+\w+[^{]*$/) { - inNestedType = true - nestedStart = i - depth = 1 - i++ - continue - } - } - if (inNestedType) { - depth++ - } - } else if (c == '}') { - if (inNestedType) { - depth-- - if (depth == 0) { - inNestedType = false - // Don't add the nested type body to result - i++ - continue - } - } - } - - if (!inNestedType) { - result.append(c) - } - i++ - } - - return result.toString() - } - - private List parseMethods(String body) { - List methods = [] - - // Remove nested type bodies first to only get top-level methods - String topLevelBody = removeNestedTypeBodies(body) - - // Match method signatures - handles complex generics - // Anchored with (?m)^ to prevent matching inside // comment lines - // Capture JSDoc in group 1, returnType in group 2, methodName in group 3, params in group 4 - def methodPattern = ~/(?m)^\s*(\/\*\*[\s\S]*?\*\/\s*)?(?:@\w+(?:\([^)]*\))?\s*)*(?:public\s+|protected\s+|private\s+)?(?:static\s+)?(?:abstract\s+)?(?:default\s+)?(?:synchronized\s+)?(?:final\s+)?(?:<[^>]+>\s+)?(\w[\w.<>,\[\]\s]*?)\s+(\w+)\s*\(([^)]*)\)\s*(?:throws\s+[\w,\s]+)?[;{]/ - - def matcher = topLevelBody =~ methodPattern - while (matcher.find()) { - String jsdoc = matcher.group(1)?.trim() - String returnType = matcher.group(2).trim() - String methodName = matcher.group(3) - - // Skip constructors - where return type is a visibility modifier - // or the method name matches the class name (which we'd need to track) - if (['public', 'protected', 'private', 'abstract', 'static', 'final', 'synchronized', 'native', 'strictfp'].contains(returnType)) { - continue - } - - JavaMethod method = new JavaMethod() - method.returnType = returnType - method.name = methodName - method.parameters = parseParameters(matcher.group(4)) - method.jsdoc = jsdoc - - methods << method - } - - return methods - } - - private List parseFields(String body) { - List fields = [] - - // Remove nested type bodies first - String topLevelBody = removeNestedTypeBodies(body) - - // Capture JSDoc in group 1, visibility in group 2, fieldType in group 3, fieldName in group 4 - def fieldPattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?(public\s+|protected\s+|private\s+)(?:static\s+)?(?:final\s+)?(\w[\w.<>,\[\]]*)\s+(\w+)\s*[;=]/ - - def matcher = topLevelBody =~ fieldPattern - while (matcher.find()) { - String jsdoc = matcher.group(1)?.trim() - String fieldType = matcher.group(3).trim() - String fieldName = matcher.group(4) - - // Skip Java keywords that might be mismatched - if (['return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue', 'throw', 'try', 'catch', 'finally', 'new', 'this', 'super'].contains(fieldType)) { - continue - } - - JavaField field = new JavaField() - field.type = fieldType - field.name = fieldName - field.jsdoc = jsdoc - - fields << field - } - - return fields - } - - private List parseNestedTypes(String body, String parentName) { - List nestedTypes = [] - - // Capture JSDoc in group 1, interface/class in group 2, name in group 3, typeParams in group 4, extends in group 5 - def nestedPattern = ~/(\/\*\*[\s\S]*?\*\/\s*)?(?:@\w+(?:\([^)]*\))?\s*)*(?:public\s+)?(?:static\s+)?(interface|class)\s+(\w+)(?:<([^>]+)>)?(?:\s+extends\s+([\w.<>,\s]+))?\s*\{/ - - // We need to track position and skip over bodies of found types to avoid finding nested-nested types - int searchStart = 0 - def matcher = nestedPattern.matcher(body) - - while (matcher.find(searchStart)) { - JavaType nested = new JavaType() - nested.jsdoc = matcher.group(1)?.trim() - nested.isInterface = matcher.group(2) == 'interface' - nested.isClass = matcher.group(2) == 'class' - nested.name = matcher.group(3) - nested.typeParams = matcher.group(4) - nested.extendsType = matcher.group(5)?.trim() - - int bodyStart = matcher.end() - 1 - int bodyEnd = findMatchingBrace(body, bodyStart) - if (bodyEnd > bodyStart) { - String nestedBody = body.substring(bodyStart + 1, bodyEnd) - nested.methods = parseMethods(nestedBody) - // Recursively parse nested types within this nested type - nested.nestedTypes = parseNestedTypes(nestedBody, nested.name) - - // Skip past the entire body of this type for the next search - searchStart = bodyEnd + 1 - } else { - // If we couldn't find the matching brace, move past this match - searchStart = matcher.end() - } - - nestedTypes << nested - } - - return nestedTypes - } - - private List parseParameters(String paramsStr) { - List params = [] - if (paramsStr == null || paramsStr.trim().isEmpty()) return params - - // Handle complex generic parameters - List paramParts = splitParameters(paramsStr) - - paramParts.each { part -> - part = part.trim() - if (part.isEmpty()) return - - // Handle varargs - boolean isVarargs = part.contains('...') - part = part.replace('...', '[]') - - // Split type and name - int lastSpace = part.lastIndexOf(' ') - if (lastSpace > 0 && lastSpace < part.length() - 1) { - JavaParameter param = new JavaParameter() - param.type = part.substring(0, lastSpace).trim() - param.name = part.substring(lastSpace + 1).trim() - param.isVarargs = isVarargs - params << param - } else if (lastSpace == -1 && !part.isEmpty()) { - // No space found - might be a single token, skip it - // This can happen with malformed or unusual parameter declarations - } - } - - return params - } - - /** - * Split parameters handling nested generics - */ - private List splitParameters(String params) { - List result = [] - int depth = 0 - StringBuilder current = new StringBuilder() - - params.each { ch -> - if (ch == '<') depth++ - else if (ch == '>') depth-- - else if (ch == ',' && depth == 0) { - result << current.toString() - current = new StringBuilder() - return - } - current.append(ch) - } - - if (current.length() > 0) { - result << current.toString() - } - - return result - } - - private String extractJsDocBefore(String content, int position) { - // Look backwards for JSDoc - String before = content.substring(0, position) - def jsdocMatcher = before =~ /\/\*\*[\s\S]*?\*\/\s*$/ - if (jsdocMatcher.find()) { - return jsdocMatcher.group(0).trim() - } - return null - } - - private int findMatchingBrace(String content, int start) { - int depth = 0 - for (int i = start; i < content.length(); i++) { - char c = content.charAt(i) - if (c == '{') depth++ - else if (c == '}') { - depth-- - if (depth == 0) return i - } - } - return -1 - } - - private String removeBlockComments(String content) { - // Remove JSDoc and block comments for structure parsing - return content.replaceAll(/\/\*[\s\S]*?\*\//, '') - } - - /** - * Generate TypeScript content from parsed Java - */ - String generateTypeScript(ParsedJavaFile parsed, String currentPath) { - StringBuilder sb = new StringBuilder() - - // Header comment - sb.append('/**\n') - sb.append(' * Generated from Java file for CustomNPC+ Minecraft Mod 1.7.10\n') - sb.append(" * Package: ${parsed.packageName}\n") - sb.append(' */\n\n') - - parsed.types.each { type -> - generateType(sb, type, parsed, currentPath, '') - } - - return sb.toString() - } - - private void generateType(StringBuilder sb, JavaType type, ParsedJavaFile parsed, String currentPath, String indent) { - // Build a set of type parameter names for this type (e.g., "T", "U", etc.) - Set typeParamNames = type.parsedTypeParams?.collect { it.name }?.toSet() ?: [] as Set - - // JSDoc - String javaFqn = buildJavaFqn(parsed.packageName, type.name) - String typeJsDoc = ensureJavaFqnTag(type.jsdoc, javaFqn, indent) - if (typeJsDoc) { - sb.append(typeJsDoc) - sb.append('\n') - } - - // Type declaration - String keyword = type.isClass ? 'export class' : 'export interface' - sb.append("${indent}${keyword} ${type.name}") - - // Type parameters with full class name bounds in JSDoc comment - if (type.typeParams) { - sb.append("<${convertTypeParams(type.typeParams, type.parsedTypeParams)}>") - } - - // Extends - skip if extending itself - if (type.extendsType && type.extendsType != type.name) { - sb.append(" extends ${convertType(type.extendsType, parsed, currentPath, typeParamNames)}") - } - - sb.append(' {\n') - - // Methods - compact format, no comments - type.methods.each { method -> - generateMethod(sb, method, parsed, currentPath, indent + ' ', typeParamNames) - } - - // Fields (for classes) - type.fields.each { field -> - generateField(sb, field, parsed, currentPath, indent + ' ', typeParamNames) - } - - sb.append("${indent}}\n") - - // Nested types as namespace - if (!type.nestedTypes.isEmpty()) { - sb.append("\n${indent}export namespace ${type.name} {\n") - type.nestedTypes.each { nested -> - // Always generate as interface, even if empty - // Empty interfaces with extends are important for type hierarchy - generateNestedType(sb, nested, type.name, type.name, parsed, currentPath, indent + ' ') - } - sb.append("${indent}}\n") - } - sb.append('\n') - } - - /** - * Generate a nested type (interface/class within a namespace) - * Recursively handles nested types that themselves have nested types - */ - private void generateNestedType(StringBuilder sb, JavaType type, String parentTypeName, String parentTypeChain, ParsedJavaFile parsed, String currentPath, String indent) { - // Build a set of type parameter names for this nested type - Set typeParamNames = type.parsedTypeParams?.collect { it.name }?.toSet() ?: [] as Set - - // JSDoc - String nestedChain = parentTypeChain ? "${parentTypeChain}.${type.name}" : type.name - String javaFqn = buildJavaFqn(parsed.packageName, nestedChain) - String nestedJsDoc = ensureJavaFqnTag(type.jsdoc, javaFqn, indent) - if (nestedJsDoc) { - sb.append(nestedJsDoc) - sb.append('\n') - } - - // Type declaration - String keyword = type.isClass ? 'export class' : 'export interface' - sb.append("${indent}${keyword} ${type.name}") - - // Type parameters with full class name bounds - if (type.typeParams) { - sb.append("<${convertTypeParams(type.typeParams, type.parsedTypeParams)}>") - } - - // Extends - handle parent type reference specially, skip if extending itself - if (type.extendsType && type.extendsType != type.name) { - String extendsRef = convertTypeForNested(type.extendsType, parentTypeName, parsed, currentPath, typeParamNames) - sb.append(" extends ${extendsRef}") - } - - sb.append(' {\n') - - // Methods - compact format, no comments - type.methods.each { method -> - generateMethod(sb, method, parsed, currentPath, indent + ' ', typeParamNames) - } - - sb.append("${indent}}\n") - - // If this nested type also has nested types, create a namespace for them - if (!type.nestedTypes.isEmpty()) { - sb.append("${indent}export namespace ${type.name} {\n") - type.nestedTypes.each { nested -> - // Always generate as interface, even if empty - // Empty interfaces with extends are important for type hierarchy - generateNestedType(sb, nested, type.name, nestedChain, parsed, currentPath, indent + ' ') - } - sb.append("${indent}}\n") - } - } - - /** - * Convert type reference for nested types - handle parent type specially - */ - private String convertTypeForNested(String javaType, String parentTypeName, ParsedJavaFile parsed, String currentPath, Set typeParamNames) { - if (javaType == null || javaType.isEmpty()) return 'any' - - javaType = javaType.trim() - - // If the type is the parent type name, use it directly (not as import from same file) - if (javaType == parentTypeName) { - return parentTypeName - } - - // Otherwise use normal conversion - return convertType(javaType, parsed, currentPath, typeParamNames) - } - - private void generateMethod(StringBuilder sb, JavaMethod method, ParsedJavaFile parsed, String currentPath, String indent, Set typeParamNames) { - // JSDoc - if (method.jsdoc) { - sb.append(convertJsDoc(method.jsdoc, indent)) - sb.append('\n') - } - - sb.append("${indent}${method.name}(") - - // Parameters - List paramStrs = method.parameters.collect { param -> - String tsType = convertType(param.type, parsed, currentPath, typeParamNames) - if (param.isVarargs) { - return "...${param.name}: ${tsType}" - } - return "${param.name}: ${tsType}" - } - sb.append(paramStrs.join(', ')) - - sb.append('): ') - sb.append(convertType(method.returnType, parsed, currentPath, typeParamNames)) - sb.append(';\n') - } - - private void generateField(StringBuilder sb, JavaField field, ParsedJavaFile parsed, String currentPath, String indent, Set typeParamNames) { - if (field.jsdoc) { - sb.append(convertJsDoc(field.jsdoc, indent)) - sb.append('\n') - } - sb.append("${indent}${field.name}: ${convertType(field.type, parsed, currentPath, typeParamNames)};\n") - } - - /** - * Convert Java type to TypeScript type - * @param typeParamNames Set of type parameter names from the enclosing type (e.g., "T", "U") - */ - String convertType(String javaType, ParsedJavaFile parsed, String currentPath, Set typeParamNames = [] as Set) { - if (javaType == null || javaType.isEmpty()) return 'any' - - javaType = javaType.trim() - - // Check if it's a type parameter (like T, U, etc.) - if (typeParamNames.contains(javaType)) { - return javaType - } - - // Check primitives first - if (PRIMITIVE_MAPPINGS.containsKey(javaType)) { - return PRIMITIVE_MAPPINGS[javaType] - } - - // Handle arrays - if (javaType.endsWith('[]') && javaType.length() > 2) { - String baseType = javaType.substring(0, javaType.length() - 2) - return convertType(baseType, parsed, currentPath, typeParamNames) + '[]' - } - - // Handle generics - if (javaType.contains('<')) { - return convertGenericType(javaType, parsed, currentPath, typeParamNames) - } - - // Check if it is an API type (needs import) - String importPath = resolveImportPath(javaType, parsed, currentPath) - if (importPath != null) { - return "import('${importPath}').${javaType}" - } - - // Check if it is a java.* type - String fullType = resolveFullType(javaType, parsed) - if (fullType != null && fullType.startsWith('java.')) { - return "Java.${fullType}" - } - - // Default - return as is (might be a type parameter like T, or unknown type) - return javaType - } - - private String convertGenericType(String type, ParsedJavaFile parsed, String currentPath, Set typeParamNames = [] as Set) { - int ltIndex = type.indexOf('<') - int gtIndex = type.lastIndexOf('>') - if (ltIndex == -1 || gtIndex == -1 || ltIndex >= gtIndex) { - // Malformed generic, return as-is - return type - } - String baseType = type.substring(0, ltIndex).trim() - String genericPart = type.substring(ltIndex + 1, gtIndex).trim() - - // Handle common collections - switch (baseType) { - case 'List': - case 'ArrayList': - case 'LinkedList': - case 'Collection': - case 'Set': - case 'HashSet': - case 'Queue': - return convertType(genericPart, parsed, currentPath, typeParamNames) + '[]' - - case 'Map': - case 'HashMap': - case 'LinkedHashMap': - List parts = splitGenericParams(genericPart) - if (parts.size() >= 2) { - String keyType = convertType(parts[0], parsed, currentPath, typeParamNames) - String valueType = convertType(parts[1], parsed, currentPath, typeParamNames) - return "Record<${keyType}, ${valueType}>" - } - return 'Record' - - case 'Optional': - return convertType(genericPart, parsed, currentPath, typeParamNames) + ' | null' - - // Functional interfaces - case 'Consumer': - return "(arg: ${convertType(genericPart, parsed, currentPath, typeParamNames)}) => void" - - case 'Supplier': - return "() => ${convertType(genericPart, parsed, currentPath, typeParamNames)}" - - case 'Function': - List funcParts = splitGenericParams(genericPart) - if (funcParts.size() >= 2) { - return "(arg: ${convertType(funcParts[0], parsed, currentPath, typeParamNames)}) => ${convertType(funcParts[1], parsed, currentPath, typeParamNames)}" - } - return '(arg: any) => any' - - case 'Predicate': - return "(arg: ${convertType(genericPart, parsed, currentPath, typeParamNames)}) => boolean" - - case 'BiConsumer': - List biParts = splitGenericParams(genericPart) - if (biParts.size() >= 2) { - return "(arg1: ${convertType(biParts[0], parsed, currentPath, typeParamNames)}, arg2: ${convertType(biParts[1], parsed, currentPath, typeParamNames)}) => void" - } - return '(arg1: any, arg2: any) => void' - - case 'BiFunction': - List biFuncParts = splitGenericParams(genericPart) - if (biFuncParts.size() >= 3) { - return "(arg1: ${convertType(biFuncParts[0], parsed, currentPath, typeParamNames)}, arg2: ${convertType(biFuncParts[1], parsed, currentPath, typeParamNames)}) => ${convertType(biFuncParts[2], parsed, currentPath, typeParamNames)}" - } - return '(arg1: any, arg2: any) => any' - - default: - // Regular generic type - String convertedBase = convertType(baseType, parsed, currentPath, typeParamNames) - List convertedParams = splitGenericParams(genericPart).collect { - convertType(it, parsed, currentPath, typeParamNames) - } - // For import types, we cannot add generics easily, so simplify - if (convertedBase.startsWith('import(')) { - return convertedBase - } - return "${convertedBase}<${convertedParams.join(', ')}>" - } - } - - private List splitGenericParams(String params) { - List result = [] - int depth = 0 - StringBuilder current = new StringBuilder() - - params.each { ch -> - if (ch == '<') depth++ - else if (ch == '>') depth-- - else if (ch == ',' && depth == 0) { - result << current.toString().trim() - current = new StringBuilder() - return - } - current.append(ch) - } - - if (current.length() > 0) { - result << current.toString().trim() - } - - return result - } - - /** - * Convert Java type parameters to TypeScript - * Outputs format like: T extends EntityPlayerMP /`*` net.minecraft.entity.player.EntityPlayerMP `*`/ - * This allows runtime parsing to extract the full Java class name for the type bound. - */ - private String convertTypeParams(String typeParams, List parsedParams) { - if (typeParams == null || typeParams.isEmpty()) return typeParams - if (parsedParams == null || parsedParams.isEmpty()) return typeParams - - // Build result by iterating over parsed params - List convertedParams = [] - for (TypeParamInfo info in parsedParams) { - StringBuilder sb = new StringBuilder() - sb.append(info.name) - - if (info.boundType != null) { - sb.append(" extends ") - sb.append(info.boundType) - - // Add full class name as JSDoc-style comment if available - if (info.fullBoundType != null) { - sb.append(" /* ${info.fullBoundType} */") - } - } - - convertedParams << sb.toString() - } - - return convertedParams.join(', ') - } - - private String resolveImportPath(String typeName, ParsedJavaFile parsed, String currentPath) { - // Check imports for this type - String fullType = resolveFullType(typeName, parsed) - - if (fullType == null) return null - - // Check if it is an API type - int lastDotIndex = fullType.lastIndexOf('.') - if (lastDotIndex == -1) return null - String packagePrefix = fullType.substring(0, lastDotIndex) - if (apiPackages.any { fullType.startsWith(it) }) { - // Calculate relative path - String typeFilePath = fullType.replace('.', '/') + '.d.ts' - return calculateRelativePath(currentPath, typeFilePath) - } - - return null - } - - private String resolveFullType(String typeName, ParsedJavaFile parsed) { - // Check explicit imports - String explicitImport = parsed.imports.find { it.endsWith(".${typeName}") } - if (explicitImport) return explicitImport - - // Check wildcard imports - parsed.imports.each { imp -> - if (imp.endsWith('.*')) { - // Would need classpath to resolve, skip for now - } - } - - // Same package - return "${parsed.packageName}.${typeName}" - } - - /** - * Parse type parameters like "T extends EntityPlayerMP" into structured TypeParamInfo - * with full class names resolved from imports - */ - private List parseTypeParams(String typeParams, ParsedJavaFile parsed) { - List result = [] - if (typeParams == null || typeParams.isEmpty()) return result - - // Split by comma, but respect nested angle brackets - List params = splitGenericParams(typeParams) - - for (String param in params) { - param = param.trim() - TypeParamInfo info = new TypeParamInfo() - - // Check for "T extends BoundType" pattern - def extendsMatcher = param =~ /(\w+)\s+extends\s+(.+)/ - if (extendsMatcher.find()) { - info.name = extendsMatcher.group(1).trim() - String boundType = extendsMatcher.group(2).trim() - - // Handle generic bounds like "Comparable" - extract base type - int angleIndex = boundType.indexOf('<') - String baseBoundType = angleIndex > 0 ? boundType.substring(0, angleIndex) : boundType - - info.boundType = baseBoundType - info.fullBoundType = resolveFullType(baseBoundType, parsed) - } else { - // Just a type param like "T" with no explicit bound - info.name = param - info.boundType = null - info.fullBoundType = null - } - - result << info - } - - return result - } - - private String calculateRelativePath(String fromPath, String toPath) { - // Calculate relative path between two .d.ts files - String[] fromParts = fromPath.split('/') - String[] toParts = toPath.split('/') - - // Find common prefix - int common = 0 - while (common < fromParts.length - 1 && common < toParts.length && fromParts[common] == toParts[common]) { - common++ - } - - // Build relative path - StringBuilder result = new StringBuilder() - - // Go up from current location - int ups = fromParts.length - common - 1 - if (ups == 0) { - result.append('./') - } else { - for (int i = 0; i < ups; i++) { - result.append('../') - } - } - - // Go down to target - for (int i = common; i < toParts.length; i++) { - if (i > common) result.append('/') - result.append(toParts[i]) - } - - // Remove .d.ts extension for imports - String path = result.toString() - if (path.endsWith('.d.ts')) { - path = path.substring(0, path.length() - 5) - } - - return path - } - - /** - * Convert JavaDoc to JSDoc format - */ - private String convertJsDoc(String jsdoc, String indent) { - if (jsdoc == null) return '' - - // Already in JSDoc format, just fix indentation - String[] lines = jsdoc.split('\n') - return lines.collect { line -> - String trimmed = line.trim() - if (trimmed.startsWith('*')) { - return "${indent} ${trimmed}" - } else if (trimmed.startsWith('/**') || trimmed.startsWith('*/')) { - return "${indent}${trimmed}" - } else { - return "${indent}${trimmed}" - } - }.join('\n') - } - - private String ensureJavaFqnTag(String jsdoc, String javaFqn, String indent) { - if (javaFqn == null || javaFqn.isEmpty()) { - return convertJsDoc(jsdoc, indent) - } - - if (jsdoc != null && jsdoc.contains('@javaFqn')) { - return convertJsDoc(jsdoc, indent) - } - - if (jsdoc == null || jsdoc.trim().isEmpty()) { - return "${indent}/**\n${indent} * @javaFqn ${javaFqn}\n${indent} */" - } - - String converted = convertJsDoc(jsdoc, indent) - int endIndex = converted.lastIndexOf('*/') - if (endIndex >= 0) { - String insert = "${indent} * @javaFqn ${javaFqn}\n" - return converted.substring(0, endIndex) + insert + converted.substring(endIndex) - } - - return converted + "\n${indent} * @javaFqn ${javaFqn}" - } - - private String buildJavaFqn(String packageName, String typeName) { - if (typeName == null || typeName.isEmpty()) return null - if (packageName == null || packageName.isEmpty()) return typeName - return packageName + '.' + typeName - } - - /** - * Extract @hookName value from a JSDoc comment. - * - * @param jsdoc The JSDoc comment string (may be null) - * @return The hook name if @hookName tag is present, null otherwise - */ - private String extractHookNameFromJsDoc(String jsdoc) { - if (jsdoc == null || jsdoc.isEmpty()) return null - - // Match @hookName followed by the hook name value - // Examples: @hookName animationStart, @hookName customGuiButton - def matcher = jsdoc =~ /@hookName\s+(\w+)/ - if (matcher.find()) { - return matcher.group(1) - } - return null - } - - /** - * Collect hook information from event interfaces. - * - * Looks for interfaces that: - * 1. End with 'Event' (e.g., IPlayerEvent, IDBCEvent) - * 2. Are in an 'event' package - * 3. Have nested types that are also events - * - * Hook names are determined by: - * 1. @hookName JSDoc tag if present (e.g., @hookName animationStart) - * 2. Otherwise derived from the event class name (e.g., InitEvent -> init) - * - * The parent event type name (e.g., "INpcEvent", "IPlayerEvent") is used directly - * as the namespace in hooks.d.ts. This allows any mod to register event interfaces - * and have them automatically organized by their type name. - */ - private void collectHooks(ParsedJavaFile parsed) { - boolean isEventPackage = parsed.packageName.contains('.event') - - parsed.types.each { type -> - // Check if this is an event interface: - // - Must be an interface - // - Either ends with 'Event' OR is in an event package - boolean isEventType = type.isInterface && ( - type.name.endsWith('Event') || type.name.endsWith('Events') || - isEventPackage - ) - - if (isEventType && !type.nestedTypes.isEmpty()) { - collectHooksFromNestedTypes(type.nestedTypes, type.name, parsed.packageName, isEventPackage) - } - } - } - - /** - * Recursively collect hooks from nested types. - * This handles deeply nested event types like IAnimationEvent.IFrameEvent.Entered - */ - private void collectHooksFromNestedTypes(List nestedTypes, String parentTypeName, String packageName, boolean isEventPackage) { - nestedTypes.each { nested -> - // Check if this nested type should be processed as a hook - boolean isNestedEvent = nested.isInterface && ( - nested.name.endsWith('Event') || - nested.name.endsWith('Events') || - isEventPackage || - // Also include simple names like "Started", "Ended", "Entered", "Exited" - // if they're inside an event interface - parentTypeName.endsWith('Event') - ) - - if (isNestedEvent) { - // Check for @hookName in JSDoc first, otherwise derive from class name - String hookName = extractHookNameFromJsDoc(nested.jsdoc) - if (hookName == null) { - hookName = deriveHookName(nested.name) - } - - if (!hooks.containsKey(hookName)) { - hooks[hookName] = [] - } - - // Use the root event type name as the namespace - // Extract the root type (e.g., "IAnimationEvent" from "IAnimationEvent.IFrameEvent") - String rootType = parentTypeName.contains('.') ? - parentTypeName.substring(0, parentTypeName.indexOf('.')) : parentTypeName - - hooks[hookName] << new HookInfo( - eventType: rootType, - subEvent: nested.name, - fullType: "${parentTypeName}.${nested.name}", - packageName: packageName, - contextNamespace: rootType - ) - - // Recursively process any nested types within this nested type - if (!nested.nestedTypes.isEmpty()) { - collectHooksFromNestedTypes(nested.nestedTypes, "${parentTypeName}.${nested.name}", packageName, isEventPackage) - } - } - } - } - - private String deriveHookName(String eventName) { - // Convert event names to hook function names - // e.g., "InitEvent" -> "init", "DamagedEvent" -> "damaged" - String name = eventName - if (name.endsWith('Event') && name.length() > 5) { - name = name.substring(0, name.length() - 5) - } - // Convert to camelCase - if (name.isEmpty()) return 'event' - String hookName = name.length() > 1 ? (name.substring(0, 1).toLowerCase() + name.substring(1)) : name.toLowerCase() - - // Handle JavaScript reserved words - Set reservedWords = ['break', 'case', 'catch', 'continue', 'debugger', 'default', 'delete', - 'do', 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof', - 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var', - 'void', 'while', 'with', 'class', 'const', 'enum', 'export', 'extends', - 'import', 'super', 'implements', 'interface', 'let', 'package', 'private', - 'protected', 'public', 'static', 'yield'] as Set - - if (reservedWords.contains(hookName)) { - // Prefix with 'on' for reserved words - hookName = 'on' + name - } - - return hookName - } - - /** - * Generate index.d.ts with all type aliases - */ - private void generateIndexFile() { - StringBuilder sb = new StringBuilder() - - sb.append('/**\n') - sb.append(' * Centralized global declarations for CustomNPC+ scripting.\n') - sb.append(' * Auto-generated - do not edit manually.\n') - sb.append(' */\n\n') - - sb.append('declare global {\n') - sb.append(' // ============================================================================\n') - sb.append(' // TYPE ALIASES - Make all interfaces available globally\n') - sb.append(' // ============================================================================\n\n') - - generatedTypes.sort { a, b -> a.name <=> b.name } - - generatedTypes.each { type -> - if (!type.name.contains('.')) { // Skip nested types here - sb.append(" type ${type.name} = import('./${type.filePath.replace('.d.ts', '')}').${type.name};\n") - } - } - - // Collect all parent types that have nested types (for namespace declarations) - Map> parentToNested = [:] - generatedTypes.each { type -> - if (type.parentType) { - if (!parentToNested.containsKey(type.parentType)) { - parentToNested[type.parentType] = [] - } - parentToNested[type.parentType] << type - } - } - - // Generate namespace declarations for types with nested interfaces - if (!parentToNested.isEmpty()) { - sb.append('\n // ============================================================================\n') - sb.append(' // NESTED INTERFACES - Allow autocomplete like INpcEvent.InitEvent\n') - sb.append(' // ============================================================================\n\n') - - parentToNested.sort { a, b -> a.key <=> b.key }.each { parentName, nestedTypes -> - sb.append(" namespace ${parentName} {\n") - nestedTypes.sort { a, b -> a.name <=> b.name }.each { nested -> - // Extract just the nested type name (e.g., "InitEvent" from "IPlayerEvent.InitEvent") - String nestedName = nested.name.contains('.') ? - nested.name.substring(nested.name.lastIndexOf('.') + 1) : nested.name - sb.append(" interface ${nestedName} extends ${parentName} {}\n") - } - sb.append(" }\n\n") - } - } - - sb.append('}\n\n') - sb.append('export {};\n') - - new File(outputDir, 'index.d.ts').text = sb.toString() - } - - /** - * Generate hooks.d.ts with event hook function declarations. - * - * Hooks are organized by their parent event interface type, using the type name - * directly as the namespace. This provides context-aware autocomplete where - * the same hook name (e.g., "interact") can have different event types depending - * on the script context. - * - * Output format example: - * declare namespace INpcEvent { - * function interact(event: INpcEvent.InteractEvent): void; - * function init(event: INpcEvent.InitEvent): void; - * } - * - * declare namespace IPlayerEvent { - * function interact(event: IPlayerEvent.InteractEvent): void; - * function init(event: IPlayerEvent.InitEvent): void; - * } - * - * The namespace name matches the event interface type exactly, making it easy - * for the runtime parser to match hooks to their correct context. - */ - private void generateHooksFile() { - StringBuilder sb = new StringBuilder() - - sb.append('/**\n') - sb.append(' * CustomNPC+ Event Hook Declarations\n') - sb.append(' *\n') - sb.append(' * Hooks are organized by their parent event interface (e.g., INpcEvent, IPlayerEvent).\n') - sb.append(' * This allows the same hook name to have different event types per script context.\n') - sb.append(' *\n') - sb.append(' * Auto-generated from Java event interfaces - do not edit manually.\n') - sb.append(' */\n\n') - - sb.append("import './minecraft-raw.d.ts';\n") - sb.append("import './forge-events-raw.d.ts';\n\n") - - // Group hooks by their parent event type (contextNamespace = type.name) - Map>> hooksByEventType = [:].withDefault { [:].withDefault { [] } } - - hooks.each { hookName, hookInfos -> - hookInfos.each { info -> - hooksByEventType[info.contextNamespace][hookName] << info - } - } - - // Output each event type as a namespace - hooksByEventType.sort { a, b -> a.key <=> b.key }.each { eventTypeName, eventHooks -> - sb.append("declare namespace ${eventTypeName} {\n") - - // Output all hooks for this event type, sorted alphabetically - eventHooks.sort { a, b -> a.key <=> b.key }.each { hookName, hookInfos -> - hookInfos.each { info -> - sb.append(" function ${hookName}(event: ${info.fullType}): void;\n") - } - } - - sb.append('}\n\n') - } - - sb.append('export {};\n') - - new File(outputDir, 'hooks.d.ts').text = sb.toString() - } - - // Data classes - static class ParsedJavaFile { - String packageName = '' - List imports = [] - List types = [] - } - - static class JavaType { - String name - String typeParams // Raw string like "T extends EntityPlayerMP" - List parsedTypeParams = [] // Parsed type parameters with full class names - String extendsType - List implementsTypes = [] - boolean isInterface - boolean isClass - String jsdoc - List methods = [] - List fields = [] - List nestedTypes = [] - } - - static class JavaMethod { - String name - String returnType - List parameters = [] - String jsdoc - } - - static class JavaParameter { - String name - String type - boolean isVarargs - } - - static class JavaField { - String name - String type - String jsdoc - } - - static class TypeParamInfo { - String name // e.g., "T" - String boundType // e.g., "EntityPlayerMP" - String fullBoundType // e.g., "net.minecraft.entity.player.EntityPlayerMP" - } - - static class TypeInfo { - String name - String packageName - String filePath - boolean isClass - boolean isInterface - String extendsType - String parentType - } - - static class HookInfo { - String eventType // Parent event interface name (e.g., "INpcEvent") - String subEvent // Nested event type name (e.g., "InteractEvent") - String fullType // Full type path (e.g., "INpcEvent.InteractEvent") - String packageName // Java package (e.g., "noppes.npcs.api.event") - String contextNamespace // Namespace in hooks.d.ts (same as eventType, e.g., "INpcEvent") - } -} diff --git a/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy b/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy deleted file mode 100644 index 3165e3744..000000000 --- a/gradle-plugins/src/main/groovy/dts/TypeScriptGeneratorPlugin.groovy +++ /dev/null @@ -1,17 +0,0 @@ -package dts - -import org.gradle.api.Plugin -import org.gradle.api.Project - -/** - * Gradle plugin for generating TypeScript definition files from Java API sources. - */ -class TypeScriptGeneratorPlugin implements Plugin { - - @Override - void apply(Project project) { - if (project.tasks.findByName('generateTypeScriptDefinitions') == null) { - project.tasks.register('generateTypeScriptDefinitions', GenerateTypeScriptTask) - } - } -} \ No newline at end of file diff --git a/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties b/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties deleted file mode 100644 index f27cbecea..000000000 --- a/gradle-plugins/src/main/resources/META-INF/gradle-plugins/dts.typescript-generator.properties +++ /dev/null @@ -1 +0,0 @@ -implementation-class=dts.TypeScriptGeneratorPlugin diff --git a/src/api b/src/api index f383fc303..efa8721d3 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit f383fc3037221791e2f22a272580df9be013810f +Subproject commit efa8721d3658b45146d58d6731a0b83c4860f02e diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java index 20486d70e..8cb8cdaad 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java @@ -43,7 +43,16 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { GL11.glPushMatrix(); GL11.glScalef(scale, scale, scale); - // Apply ONLY Y-axis rotation for flat spin + if (disc.isVertical()) { + // Vertical mode: thin edge faces direction of travel (like a saw blade) + // 1. Spin in local space (Y-axis) + // 2. Tilt 90° to stand up (X-axis) + // 3. Orient to face travel direction (Y-axis world yaw) + GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + } + + // Apply Y-axis rotation for spin GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); // Inner scale defines the core size diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java index 2ba840aec..96e8e7b08 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java @@ -31,7 +31,7 @@ public abstract class RenderAbilityProjectile extends Render { */ protected void setupRenderState() { GL11.glPushMatrix(); - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_ALPHA_TEST); diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java new file mode 100644 index 000000000..e9775c542 --- /dev/null +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityZone.java @@ -0,0 +1,747 @@ +package kamkeel.npcs.client.renderer; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle; +import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneType; +import noppes.npcs.client.fx.CustomFX; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.entity.Render; +import net.minecraft.entity.Entity; +import net.minecraft.util.ResourceLocation; +import noppes.npcs.client.fx.ZoneParticleFX; +import org.lwjgl.opengl.GL11; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +@SideOnly(Side.CLIENT) +public class RenderAbilityZone extends Render { + + private static final int CIRCLE_SEGMENTS = 32; + private static final int ACCENT_LINE_COUNT = 12; + private static final Random RANDOM = new Random(); + + private final Map lastParticleTick = new HashMap<>(); + private final Map lightningStates = new HashMap<>(); + + private static final int TRIGGER_REVEAL_TICKS = 10; + + private static class Ctx { + EntityAbilityZone zone; + ZoneShape shape; + float radius, height; + float ir, ig, ib; + float outerR, outerG, outerB; + boolean outerEnabled; + float time, pulse, rotation, brightness; + boolean flash, newTick; + float particleDensity, particleScale, animSpeed, lightningDensity; + boolean groundFill, rings, border, accents, lightning, particles; + float groundAlpha, borderSpeed; + int ringCount, accentStyle, particleMotion, particleSize; + boolean particleGlow; + String particleDir; + boolean trapVisible; + boolean triggerReveal; + float revealFade; + } + + @Override + public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { + EntityAbilityZone zone = (EntityAbilityZone) entity; + + Ctx c = new Ctx(); + c.zone = zone; + c.shape = zone.getShape(); + c.radius = zone.getRadius(); + c.height = zone.getZoneHeight(); + + int inner = zone.getInnerColor(); + c.ir = ((inner >> 16) & 0xFF) / 255.0f; + c.ig = ((inner >> 8) & 0xFF) / 255.0f; + c.ib = (inner & 0xFF) / 255.0f; + + int outer = zone.getOuterColor(); + c.outerR = ((outer >> 16) & 0xFF) / 255.0f; + c.outerG = ((outer >> 8) & 0xFF) / 255.0f; + c.outerB = (outer & 0xFF) / 255.0f; + c.outerEnabled = zone.isOuterColorEnabled(); + + c.particleDensity = zone.getParticleDensity(); + c.particleScale = zone.getParticleScale(); + c.animSpeed = zone.getAnimSpeed(); + c.lightningDensity = zone.getLightningDensity(); + + c.groundFill = zone.isGroundFill(); + c.groundAlpha = zone.getGroundAlpha(); + c.rings = zone.isRings(); + c.ringCount = zone.getRingCount(); + c.border = zone.isBorder(); + c.borderSpeed = zone.getBorderSpeed(); + c.accents = zone.isAccents(); + c.accentStyle = zone.getAccentStyle(); + c.lightning = zone.isLightning(); + c.particles = zone.isParticles(); + c.particleMotion = zone.getParticleMotion(); + c.particleDir = zone.getParticleDir(); + c.particleSize = zone.getParticleSize(); + c.particleGlow = zone.isParticleGlow(); + + c.time = zone.ticksExisted + partialTicks; + c.pulse = c.time * 0.1f * c.animSpeed; + c.rotation = c.time * 1.5f * c.animSpeed; + + c.brightness = 1.0f; + c.trapVisible = true; + c.triggerReveal = false; + c.revealFade = 0.0f; + + if (zone.getZoneType() == ZoneType.TRAP) { + c.trapVisible = zone.isVisible(); + + // Trigger reveal: 10-tick full visual burst that fades out + if (zone.getTriggerFlashTick() >= 0) { + float ticksSinceTrigger = zone.ticksExisted - zone.getTriggerFlashTick() + partialTicks; + if (ticksSinceTrigger < TRIGGER_REVEAL_TICKS) { + c.triggerReveal = true; + c.revealFade = Math.max(0.0f, 1.0f - ticksSinceTrigger / TRIGGER_REVEAL_TICKS); + } + } + + // Skip render entirely if invisible and not in reveal + if (!c.trapVisible && !c.triggerReveal) { + return; + } + + if (!zone.isArmed()) { + c.brightness = 0.4f; + } else { + c.pulse = c.time * 0.2f; + } + } + + // White flash during first 2 ticks of reveal + c.flash = c.triggerReveal && c.revealFade > 0.8f; + + c.newTick = isNewTick(zone); + + setupRenderState(); + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + GL11.glDepthMask(false); + + renderZone(c); + + GL11.glDepthMask(true); + GL11.glPopMatrix(); + restoreRenderState(); + } + + private boolean isNewTick(EntityAbilityZone zone) { + int id = zone.getEntityId(); + int tick = zone.ticksExisted; + Integer last = lastParticleTick.get(id); + if (last == null || last != tick) { + lastParticleTick.put(id, tick); + return true; + } + return false; + } + + private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityZone zone) { + int id = zone.getEntityId(); + AttachedLightningRenderer.LightningState state = lightningStates.get(id); + if (state == null) { + state = new AttachedLightningRenderer.LightningState(); + lightningStates.put(id, state); + } + return state; + } + + private void renderZone(Ctx c) { + // During trigger reveal, override visual layers for dramatic burst + if (c.triggerReveal) { + c.brightness = c.revealFade; + c.groundFill = true; + c.groundAlpha = 0.35f * c.revealFade; + c.rings = true; + c.ringCount = 3; + c.accents = true; + c.accentStyle = 2; // FLICKERING + c.border = true; + } + + float rR = ringR(c), rG = ringG(c), rB = ringB(c); + + if (c.groundFill) { + if (c.flash) { + renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f); + } else { + renderShapeFill(c.shape, c.radius, + c.ir, c.ig, c.ib, c.groundAlpha * c.brightness); + } + } + + if (c.rings) { + int count = Math.max(1, Math.min(5, c.ringCount)); + for (int i = 0; i < count; i++) { + float frac = (i + 1.0f) / (count + 1); + float ra = (0.4f + 0.3f * sin(c.pulse + i * Math.PI / 3)) * c.brightness; + float yOff = 0.02f + i * 0.01f; + renderRingLine(c.shape, c.radius * frac, + rR, rG, rB, ra, yOff); + } + float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness; + renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f); + } + + if (c.border) { + renderRotatingBorder(c.shape, c.radius, rR, rG, rB, + 0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f); + } + + if (c.accents) { + float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f)); + AccentStyle style = AccentStyle.values()[Math.min(c.accentStyle, AccentStyle.values().length - 1)]; + switch (style) { + case SWAYING: + renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height); + break; + case FLICKERING: + renderFlickeringAccents(c, c.ir, c.ig, c.ib, aa, c.height); + break; + default: + renderVerticalAccents(c.shape, c.radius, c.ir, c.ig, c.ib, aa, c.height, c.rotation * 0.3f); + break; + } + } + + if (c.lightning) { + int innerColor = c.zone.getInnerColor(); + int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor; + AttachedLightningRenderer.LightningState state = getLightningState(c.zone); + if (c.newTick) { + state.tick(); + float density = 0.4f * c.brightness * c.lightningDensity; + if (RANDOM.nextFloat() < density) { + double[] p1 = randomPosInZone(c); + double[] p2 = randomPosInZone(c); + double y1 = RANDOM.nextDouble() * c.height * 0.4; + double y2 = RANDOM.nextDouble() * c.height * 0.4; + float disp = c.radius * 0.15f; + state.addArc(AttachedLightningRenderer.createArcBetween( + p1[0], y1, p1[2], p2[0], y2, p2[2], disp, outerColor, innerColor, 6)); + } + if (RANDOM.nextFloat() < density * 0.5f * c.lightningDensity) { + double[] edgePos = randomEdgePos(c); + double ex = edgePos[0]; + double ez = edgePos[1]; + float disp = c.radius * 0.12f; + state.addArc(AttachedLightningRenderer.createArcBetween( + ex, 0, ez, ex + (RANDOM.nextDouble() - 0.5) * 0.5, + c.height * (0.3 + RANDOM.nextDouble() * 0.4), + ez + (RANDOM.nextDouble() - 0.5) * 0.5, + disp, outerColor, innerColor, 5)); + } + } + state.render(); + GL11.glDepthMask(false); + } + + if (c.particles && c.newTick && c.particleDensity > 0) { + if (c.particleDir != null && !c.particleDir.isEmpty()) { + if (c.particleDir.startsWith("mc:")) { + spawnVanillaParticle(c); + } else { + spawnCustomFXParticle(c); + } + } else { + spawnDefaultParticles(c); + } + } + } + + private void spawnVanillaParticle(Ctx c) { + String particleName = c.particleDir.substring(3); + int count = Math.round(3 * c.particleDensity); + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double[] motion = getMotionForStyle(c.particleMotion); + c.zone.worldObj.spawnParticle(particleName, + c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2], + motion[0], motion[1], motion[2]); + } + } + + private void spawnCustomFXParticle(Ctx c) { + int count = Math.round(3 * c.particleDensity); + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double[] motion = getMotionForStyle(c.particleMotion); + CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir, + c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2], + 0, 0, 0); + fx.motionX = motion[0]; + fx.motionY = motion[1]; + fx.motionZ = motion[2]; + fx.setMaxAge(20 + RANDOM.nextInt(20)); + fx.width = -1; + fx.height = -1; + fx.scaleX1 = c.particleScale * 10.0f; + fx.scaleY1 = c.particleScale * 10.0f; + fx.scaleX2 = fx.scaleX1; + fx.scaleY2 = fx.scaleY1; + fx.scaleXRate = 0; + fx.scaleYRate = 0; + fx.HEXColor = c.zone.getInnerColor(); + fx.facePlayer = true; + fx.glows = c.particleGlow; + fx.noClip = true; + fx.alpha1 = 0.8f; + fx.alpha2 = 0.0f; + fx.alphaRate = -0.04f; + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + + private void spawnDefaultParticles(Ctx c) { + int count = Math.round(3 * c.particleDensity); + ParticleMotion motion = ParticleMotion.values()[Math.min(c.particleMotion, ParticleMotion.values().length - 1)]; + for (int i = 0; i < count; i++) { + double[] pos = randomPosInZone(c); + double mx, my, mz; + float gravity; + int age; + switch (motion) { + case DRIFTING: + mx = (RANDOM.nextDouble() - 0.5) * 0.005; + my = 0.005 + RANDOM.nextDouble() * 0.01; + mz = (RANDOM.nextDouble() - 0.5) * 0.005; + gravity = 0; + age = 40 + RANDOM.nextInt(20); + break; + case SPARKS: + mx = (RANDOM.nextDouble() - 0.5) * 0.08; + my = RANDOM.nextDouble() * 0.06; + mz = (RANDOM.nextDouble() - 0.5) * 0.08; + gravity = 0; + age = 4 + RANDOM.nextInt(6); + break; + default: // RISING + mx = (RANDOM.nextDouble() - 0.5) * 0.01; + my = 0.01 + RANDOM.nextDouble() * 0.02; + mz = (RANDOM.nextDouble() - 0.5) * 0.01; + gravity = -0.01f; + age = 30 + RANDOM.nextInt(20); + break; + } + float scale = (1.5f + RANDOM.nextFloat() * 1.0f) * c.particleScale; + spawnParticle(c.zone, pos[0], pos[1], pos[2], mx, my, mz, + c.ir, c.ig, c.ib, 0.7f, scale, age, gravity, c.particleGlow); + } + } + + private double[] getMotionForStyle(int motionOrdinal) { + ParticleMotion motion = ParticleMotion.values()[Math.min(motionOrdinal, ParticleMotion.values().length - 1)]; + switch (motion) { + case DRIFTING: + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.005, + 0.005 + RANDOM.nextDouble() * 0.01, + (RANDOM.nextDouble() - 0.5) * 0.005 + }; + case SPARKS: + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.08, + RANDOM.nextDouble() * 0.06, + (RANDOM.nextDouble() - 0.5) * 0.08 + }; + default: // RISING + return new double[]{ + (RANDOM.nextDouble() - 0.5) * 0.01, + 0.01 + RANDOM.nextDouble() * 0.02, + (RANDOM.nextDouble() - 0.5) * 0.01 + }; + } + } + + private float ringR(Ctx c) { return c.outerEnabled ? c.outerR : c.ir; } + private float ringG(Ctx c) { return c.outerEnabled ? c.outerG : c.ig; } + private float ringB(Ctx c) { return c.outerEnabled ? c.outerB : c.ib; } + + private static float sin(double v) { return (float) Math.sin(v); } + + private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) { + if (height <= 0.1f) return; + float rotRad = (float) Math.toRadians(c.rotation * 0.2f); + Tessellator tess = Tessellator.instance; + + if (c.shape == ZoneShape.SQUARE) { + renderSquareSwayingAccents(c, r, g, b, a, height, rotRad, tess); + } else { + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(baseAngle) * c.radius; + double lz = Math.sin(baseAngle) * c.radius; + + float swayX = 0.15f * sin(c.time * 0.08f + i * 1.7f); + float swayZ = 0.15f * sin(c.time * 0.06f + i * 2.3f); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx + swayX, height, lz + swayZ); + tess.draw(); + } + } + } + + private void renderSquareSwayingAccents(Ctx c, float r, float g, float b, float a, float height, float rotRad, Tessellator tess) { + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + int idx = 0; + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -c.radius + frac * 2 * c.radius; lz = -c.radius; break; + case 1: lx = c.radius; lz = -c.radius + frac * 2 * c.radius; break; + case 2: lx = c.radius - frac * 2 * c.radius; lz = c.radius; break; + default: lx = -c.radius; lz = c.radius - frac * 2 * c.radius; break; + } + float swayX = 0.15f * sin(c.time * 0.08f + idx * 1.7f); + float swayZ = 0.15f * sin(c.time * 0.06f + idx * 2.3f); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx + swayX, height, lz + swayZ); + tess.draw(); + idx++; + } + } + } + + private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) { + if (height <= 0.1f) return; + float rotRad = (float) Math.toRadians(c.rotation * 0.4f); + Tessellator tess = Tessellator.instance; + + if (c.shape == ZoneShape.SQUARE) { + renderSquareFlickeringAccents(c, r, g, b, baseAlpha, height, tess); + } else { + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(baseAngle) * c.radius; + double lz = Math.sin(baseAngle) * c.radius; + + float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + i * 3.14f)); + float lineAlpha = baseAlpha * flicker; + float lineHeight = height * (0.6f + 0.4f * flicker); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, lineAlpha); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, lineHeight, lz); + tess.draw(); + } + } + } + + private void renderSquareFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height, Tessellator tess) { + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + int idx = 0; + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -c.radius + frac * 2 * c.radius; lz = -c.radius; break; + case 1: lx = c.radius; lz = -c.radius + frac * 2 * c.radius; break; + case 2: lx = c.radius - frac * 2 * c.radius; lz = c.radius; break; + default: lx = -c.radius; lz = c.radius - frac * 2 * c.radius; break; + } + float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + idx * 3.14f)); + float lineAlpha = baseAlpha * flicker; + float lineHeight = height * (0.6f + 0.4f * flicker); + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, lineAlpha); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, lineHeight, lz); + tess.draw(); + idx++; + } + } + } + + private double[] randomPosInZone(Ctx c) { + if (c.shape == ZoneShape.SQUARE) { + double px = (RANDOM.nextDouble() * 2 - 1) * c.radius; + double pz = (RANDOM.nextDouble() * 2 - 1) * c.radius; + return new double[]{px, 0, pz}; + } else { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = Math.sqrt(RANDOM.nextDouble()) * c.radius; + double px = Math.cos(angle) * dist; + double pz = Math.sin(angle) * dist; + return new double[]{px, 0, pz}; + } + } + + private double[] randomEdgePos(Ctx c) { + if (c.shape == ZoneShape.SQUARE) { + int side = RANDOM.nextInt(4); + double frac = RANDOM.nextDouble() * 2 - 1; + switch (side) { + case 0: return new double[]{frac * c.radius, -c.radius}; + case 1: return new double[]{frac * c.radius, c.radius}; + case 2: return new double[]{-c.radius, frac * c.radius}; + default: return new double[]{c.radius, frac * c.radius}; + } + } else { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = c.radius * (0.5 + RANDOM.nextDouble() * 0.5); + return new double[]{Math.cos(angle) * dist, Math.sin(angle) * dist}; + } + } + + private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ, + double mx, double my, double mz, + float r, float g, float b, float alpha, + float scale, int maxAge, float gravity, boolean glow) { + ZoneParticleFX particle = new ZoneParticleFX( + zone.worldObj, + zone.posX + offsetX, zone.posY + offsetY, zone.posZ + offsetZ, + mx, my, mz, r, g, b, alpha, scale, maxAge, gravity, glow); + Minecraft.getMinecraft().effectRenderer.addEffect(particle); + } + + private void setupRenderState() { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glShadeModel(GL11.GL_SMOOTH); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f); + } + + private void restoreRenderState() { + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glPopAttrib(); + } + + private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) { + GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL); + GL11.glPolygonOffset(-1.0f, -1.0f); + switch (shape) { + case CIRCLE: + renderCircleFill(radius, r, g, b, a); + break; + case SQUARE: + renderSquareFill(radius, r, g, b, a); + break; + } + GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL); + } + + private void renderCircleFill(float radius, float r, float g, float b, float a) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_TRIANGLE_FAN); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(0, 0, 0); + for (int i = 0; i <= CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + tess.addVertex(Math.cos(angle) * radius, 0, Math.sin(angle) * radius); + } + tess.draw(); + } + + private void renderSquareFill(float radius, float r, float g, float b, float a) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_QUADS); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(-radius, 0, -radius); + tess.addVertex(radius, 0, -radius); + tess.addVertex(radius, 0, radius); + tess.addVertex(-radius, 0, radius); + tess.draw(); + } + + private void renderRingLine(ZoneShape shape, float radius, + float r, float g, float b, float a, float yOffset) { + switch (shape) { + case CIRCLE: + renderCircleRingLine(radius, r, g, b, a, yOffset); + break; + case SQUARE: + renderSquareRingLine(radius, r, g, b, a, yOffset); + break; + } + } + + private void renderCircleRingLine(float radius, float r, float g, float b, float a, float yOffset) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_LINE_LOOP); + tess.setColorRGBA_F(r, g, b, a); + for (int i = 0; i < CIRCLE_SEGMENTS; i++) { + double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS; + tess.addVertex(Math.cos(angle) * radius, yOffset, Math.sin(angle) * radius); + } + tess.draw(); + } + + private void renderSquareRingLine(float radius, float r, float g, float b, float a, float yOffset) { + Tessellator tess = Tessellator.instance; + tess.startDrawing(GL11.GL_LINE_LOOP); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(-radius, yOffset, -radius); + tess.addVertex(radius, yOffset, -radius); + tess.addVertex(radius, yOffset, radius); + tess.addVertex(-radius, yOffset, radius); + tess.draw(); + } + + private void renderRotatingBorder(ZoneShape shape, float radius, + float r, float g, float b, float a, + float rotationDeg, float yOffset) { + int dashCount = 16; + + if (shape == ZoneShape.SQUARE) { + float perimeter = radius * 8; + float dashLen = perimeter / dashCount; + float offset = (rotationDeg % 360.0f) / 360.0f * perimeter; + + Tessellator tess = Tessellator.instance; + for (int i = 0; i < dashCount; i += 2) { + float startDist = (i * dashLen + offset) % perimeter; + float endDist = startDist + dashLen; + + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.setColorRGBA_F(r, g, b, a); + int steps = 4; + for (int s = 0; s <= steps; s++) { + float d = startDist + (endDist - startDist) * s / steps; + double[] pos = perimeterPos(d % perimeter, radius); + tess.addVertex(pos[0], yOffset, pos[1]); + } + tess.draw(); + } + } else { + float dashAngle = (float) (Math.PI * 2) / dashCount; + float rotRad = (float) Math.toRadians(rotationDeg); + + Tessellator tess = Tessellator.instance; + for (int i = 0; i < dashCount; i += 2) { + float startAngle = i * dashAngle + rotRad; + float endAngle = startAngle + dashAngle; + + tess.startDrawing(GL11.GL_LINE_STRIP); + tess.setColorRGBA_F(r, g, b, a); + int steps = 4; + for (int s = 0; s <= steps; s++) { + float segAngle = startAngle + (endAngle - startAngle) * s / steps; + tess.addVertex(Math.cos(segAngle) * radius, yOffset, Math.sin(segAngle) * radius); + } + tess.draw(); + } + } + } + + private double[] perimeterPos(float dist, float radius) { + float sideLen = radius * 2; + if (dist < sideLen) { + // Bottom edge: (-radius, -radius) to (radius, -radius) + return new double[]{-radius + dist, -radius}; + } + dist -= sideLen; + if (dist < sideLen) { + // Right edge: (radius, -radius) to (radius, radius) + return new double[]{radius, -radius + dist}; + } + dist -= sideLen; + if (dist < sideLen) { + // Top edge: (radius, radius) to (-radius, radius) + return new double[]{radius - dist, radius}; + } + dist -= sideLen; + // Left edge: (-radius, radius) to (-radius, -radius) + return new double[]{-radius, radius - dist}; + } + + private void renderVerticalAccents(ZoneShape shape, float radius, + float r, float g, float b, float a, + float height, float rotationDeg) { + if (height <= 0.1f) return; + + Tessellator tess = Tessellator.instance; + + if (shape == ZoneShape.SQUARE) { + int perSide = Math.max(1, ACCENT_LINE_COUNT / 4); + for (int side = 0; side < 4; side++) { + for (int j = 0; j < perSide; j++) { + float frac = (j + 0.5f) / perSide; + double lx, lz; + switch (side) { + case 0: lx = -radius + frac * 2 * radius; lz = -radius; break; + case 1: lx = radius; lz = -radius + frac * 2 * radius; break; + case 2: lx = radius - frac * 2 * radius; lz = radius; break; + default: lx = -radius; lz = radius - frac * 2 * radius; break; + } + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, height, lz); + tess.draw(); + } + } + float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}}; + for (float[] corner : corners) { + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(corner[0], 0.01, corner[1]); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(corner[0], height, corner[1]); + tess.draw(); + } + } else { + float rotRad = (float) Math.toRadians(rotationDeg); + for (int i = 0; i < ACCENT_LINE_COUNT; i++) { + float angle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad; + double lx = Math.cos(angle) * radius; + double lz = Math.sin(angle) * radius; + + tess.startDrawing(GL11.GL_LINES); + tess.setColorRGBA_F(r, g, b, a); + tess.addVertex(lx, 0.01, lz); + tess.setColorRGBA_F(r, g, b, 0.0f); + tess.addVertex(lx, height, lz); + tess.draw(); + } + } + } + + @Override + protected ResourceLocation getEntityTexture(Entity entity) { + return null; + } +} diff --git a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java index 3b5e49e2d..78ba58aed 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java @@ -110,6 +110,9 @@ public class TelegraphRenderer { case POINT: renderPoint(red, green, blue, alpha); break; + case SQUARE: + renderSquare(telegraph.getRadius(), red, green, blue, alpha); + break; default: break; } @@ -258,6 +261,30 @@ public class TelegraphRenderer { tessellator.draw(); } + private void renderSquare(float radius, float r, float g, float b, float a) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(r, g, b, a); + + tessellator.addVertex(-radius, 0, -radius); + tessellator.addVertex(radius, 0, -radius); + tessellator.addVertex(radius, 0, radius); + tessellator.addVertex(-radius, 0, radius); + + tessellator.draw(); + + // Draw border + tessellator.startDrawing(GL11.GL_LINE_LOOP); + tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2)); + + tessellator.addVertex(-radius, 0.01, -radius); + tessellator.addVertex(radius, 0.01, -radius); + tessellator.addVertex(radius, 0.01, radius); + tessellator.addVertex(-radius, 0.01, radius); + + tessellator.draw(); + } + // ==================== GUI PREVIEW RENDERING ==================== /** @@ -322,6 +349,9 @@ public class TelegraphRenderer { case POINT: renderPoint(red, green, blue, alpha); break; + case SQUARE: + renderSquare(telegraph.getRadius(), red, green, blue, alpha); + break; default: break; } diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java index 4fa28cda8..2910a9566 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -85,20 +85,39 @@ public class AttachedLightningRenderer { } } + /** + * Age existing arcs and remove dead ones without spawning new arcs. + * Use with addArc() for custom arc generation. + */ + public void tick() { + Iterator iter = arcs.iterator(); + while (iter.hasNext()) { + LightningArc arc = iter.next(); + arc.tick(); + if (arc.isDead()) { + iter.remove(); + } + } + } + + /** + * Add a custom arc to the state. + */ + public void addArc(LightningArc arc) { + arcs.add(arc); + } + /** * Render all active arcs in local space. * Call this after glTranslated to entity position. + * Note: Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). This avoids nesting + * glPushAttrib calls which can overflow the GL attrib stack (depth 16) when + * other mods also push attribs during entity rendering. */ public void render() { if (arcs.isEmpty()) return; - // Setup GL state - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -114,7 +133,6 @@ public class AttachedLightningRenderer { } GL11.glDepthMask(true); - GL11.glPopAttrib(); } public int getArcCount() { @@ -235,10 +253,23 @@ public class AttachedLightningRenderer { } } + /** + * Create a lightning arc between two arbitrary points. + */ + public static LightningArc createArcBetween(double x1, double y1, double z1, + double x2, double y2, double z2, + float displacement, int outerColor, int innerColor, int maxAge) { + int segments = 4 + rand.nextInt(3); + List points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement); + return new LightningArc(points, maxAge, outerColor, innerColor); + } + // ==================== INSTANT RENDERING (no persistence) ==================== /** * Render a single instant lightning arc (no fading, drawn this frame only). + * Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). */ public static void renderInstantArc(float radius, int outerColor, int innerColor) { double theta = rand.nextDouble() * Math.PI * 2; @@ -254,12 +285,6 @@ public class AttachedLightningRenderer { List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement); - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -267,7 +292,6 @@ public class AttachedLightningRenderer { renderBoltPath(tess, points, innerColor, 0.012f, 0.7f); GL11.glDepthMask(true); - GL11.glPopAttrib(); } /** diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java index d5b9420cc..90d20ea1e 100644 --- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -2,7 +2,12 @@ package kamkeel.npcs.command; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; import java.util.ArrayList; import java.util.Collections; @@ -122,5 +127,192 @@ public class AbilityCommand extends CommandKamkeelBase { } sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange()); sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No")); + sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name()); + } + + @SubCommand( + desc = "List all built-in abilities available for players" + ) + public void prebuilts(ICommandSender sender, String[] args) { + Set names = AbilityController.Instance.getAbilityNames(); + if (names.isEmpty()) { + sendResult(sender, "No built-in abilities found."); + return; + } + + List playerAbilities = new ArrayList<>(); + for (String name : names) { + Ability ability = AbilityController.Instance.getAbility(name); + if (ability != null && ability.getAllowedBy().allowsPlayer()) { + playerAbilities.add(name); + } + } + + if (playerAbilities.isEmpty()) { + sendResult(sender, "No player-usable built-in abilities found."); + return; + } + + Collections.sort(playerAbilities); + sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):"); + for (String name : playerAbilities) { + Ability ability = AbilityController.Instance.getAbility(name); + String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]"; + sendResult(sender, " - \u00A7b" + name + " " + userType); + } + } + + @SubCommand( + desc = "Unlock an ability for a player", + usage = " " + ) + public void unlock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability unlock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; + } + + // Use the ability's canonical ID for storage (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId(); + if (canonicalKey == null || canonicalKey.isEmpty()) { + canonicalKey = abilityKey; // Fallback to user-provided key + } + String displayName = ability.getName() != null ? ability.getName() : canonicalKey; + + // Check if ability allows players + if (!ability.getAllowedBy().allowsPlayer()) { + sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players."); + return; + } + + // Get player data and unlock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player already has ability: " + displayName); + return; + } + + data.abilityData.unlockAbility(canonicalKey); + sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Lock (revoke) an ability from a player", + usage = " " + ) + public void lock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability lock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability to get canonical key + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + String canonicalKey = abilityKey; + String displayName = abilityKey; + if (ability != null) { + canonicalKey = ability.getId() != null ? ability.getId() : abilityKey; + displayName = ability.getName() != null ? ability.getName() : canonicalKey; + } + + // Get player data and lock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (!data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player doesn't have ability: " + displayName); + return; + } + + data.abilityData.lockAbility(canonicalKey); + sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName); + } + + @SubCommand( + desc = "List abilities unlocked for a player", + usage = "" + ) + public void player(ICommandSender sender, String[] args) { + if (args.length < 1) { + sendError(sender, "Usage: /kam ability player "); + return; + } + + String playerName = args[0]; + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + String[] abilityKeys = data.abilityData.getUnlockedAbilities(); + + if (abilityKeys.length == 0) { + sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities."); + return; + } + + sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):"); + int selected = data.abilityData.getSelectedIndex(); + for (int i = 0; i < abilityKeys.length; i++) { + String key = abilityKeys[i]; + Ability ability = AbilityController.Instance.resolveAbility(key); + String displayName = ability != null && ability.getName() != null ? ability.getName() : key; + String prefix = (i == selected) ? "\u00A7e> " : " "; + // Show display name and key if different + if (!displayName.equals(key)) { + sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]"); + } else { + sendResult(sender, prefix + "\u00A7b" + displayName); + } + } + } + + private String joinArgs(String[] args, int startIndex) { + StringBuilder sb = new StringBuilder(); + for (int i = startIndex; i < args.length; i++) { + if (i > startIndex) sb.append(" "); + sb.append(args[i]); + } + return sb.toString(); + } + + /** + * Get list of player-usable ability names (for tab completion). + * Uses registry keys for built-in abilities and display names for custom abilities. + * Used by CommandKamkeel for usage token. + */ + public static List getPlayerAbilityNames() { + List keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys()); + Collections.sort(keys); + return keys; } } diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java index d0341f211..91356c825 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames; import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames; public class CommandKamkeel extends CommandBase { @@ -135,6 +136,9 @@ public class CommandKamkeel extends CommandBase { } else if (usage.equals("")) { List keys = getSortedEffectNames(); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); + } else if (usage.equals("")) { + List keys = getPlayerAbilityNames(); + return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 03faf42d5..11ceffea8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -7,6 +7,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.AxisAlignedBB; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; @@ -32,6 +33,7 @@ import noppes.npcs.scripted.event.player.PlayerAbilityEvent; import noppes.npcs.client.gui.builder.FieldDef; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import net.minecraft.entity.Entity; @@ -67,7 +69,8 @@ public abstract class Ability implements IAbility { // Feedback protected LockMovementType lockMovement = LockMovementType.WINDUP; - protected LockType lockType = LockType.BOTH; + protected RotationMode rotationMode = RotationMode.FREE; + protected LockMovementType rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; protected int windUpColor = 0x80FF4400; // Telegraph color during wind up protected int activeColor = 0xC0FF0000; // Telegraph warning/active color @@ -100,6 +103,13 @@ public abstract class Ability implements IAbility { // Configurable potion effects protected List effects = new ArrayList<>(); + // Burst + protected boolean burstEnabled = false; + protected int burstAmount = 0; // number of EXTRA repetitions + protected int burstDelay = 0; // ticks between bursts + protected boolean burstReplayAnimations = true; + protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts + // ═══════════════════════════════════════════════════════════════════ // EXECUTION STATE (not saved, reset each combat) // ═══════════════════════════════════════════════════════════════════ @@ -108,21 +118,41 @@ public abstract class Ability implements IAbility { protected transient int currentTick = 0; protected transient EntityLivingBase currentTarget; protected transient long executionStartTime; - protected transient TelegraphInstance telegraphInstance; + protected transient List telegraphInstances = new ArrayList<>(); + + // Burst execution state + protected transient int burstIndex = 0; + protected transient List burstEntities = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // PREVIEW STATE (client-side only, not saved) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean previewMode = false; + protected transient PreviewEntityHandler previewEntityHandler; + + // ═══════════════════════════════════════════════════════════════════ + // GUI CONTEXT (client-side only, not saved) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean npcInlineEdit = false; // ═══════════════════════════════════════════════════════════════════ // ABSTRACT METHODS // ═══════════════════════════════════════════════════════════════════ /** - * Called first tick of ACTIVE phase + * Called first tick of ACTIVE phase. + * For burst without replay (burstReplayAnimations=false), this is called directly + * after BURST_DELAY without a preceding windup. Check isBurstRefire() or null-check + * entity state to detect and handle the burst refire case. */ - public abstract void onExecute(EntityLivingBase caster, EntityLivingBase target, World world); + public abstract void onExecute(EntityLivingBase caster, EntityLivingBase target); /** * Called every tick of ACTIVE phase */ - public abstract void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick); + public abstract void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick); /** * Write type-specific config to NBT @@ -148,7 +178,49 @@ public abstract class Ability implements IAbility { return true; } - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + /** + * Override to provide variant templates for this ability type. + * When a user creates this ability type, they will be shown a selection dialog + * with the returned variants. If empty or single-entry, the dialog is skipped. + */ + public List getVariants() { + return Collections.emptyList(); + } + + /** + * Whether this ability type supports the burst system. + * Override to return false for abilities that shouldn't repeat (Guard, Heal, Sweeper, etc.). + */ + public boolean allowBurst() { + return true; + } + + /** + * Whether this ability supports overlap mode for burst (entities from previous bursts keep flying). + * Override to return true for entity-spawning projectile abilities (Orb, Beam, Disc, LaserShot). + */ + public boolean allowOverlap() { + return false; + } + + /** + * Whether this ability is ready for auto-completion during burst overlap mode. + * Override to delay auto-completion until all staggered projectiles have been fired. + * @param activeTick the current tick within the ACTIVE phase + */ + public boolean isReadyForBurstCompletion(int activeTick) { + return true; + } + + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + } + + /** + * Whether this execution is a burst refire (not the first execution). + * Useful in onExecute() to detect when windup was skipped and entities need fresh creation. + */ + public boolean isBurstRefire() { + return burstEnabled && burstIndex > 0; } public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { @@ -257,13 +329,10 @@ public abstract class Ability implements IAbility { // Apply damage if (damage > 0) { - // Check for external damage handler first (e.g., DBC Addon) - IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); - boolean handled = false; - if (handler != null) { - handled = handler.handleDamage(this, caster, hitEntity, damage, knockback, knockbackUp, - knockbackDirX, knockbackDirZ); - } + // Check for ability extenders (e.g., DBC Addon damage routing) + boolean handled = AbilityController.Instance.fireOnAbilityDamage( + this, caster, hitEntity, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ); if (!handled) { // Default damage path if (caster instanceof EntityNPCInterface) { @@ -328,6 +397,28 @@ public abstract class Ability implements IAbility { return 45.0f; } + /** + * Returns true if the caster is a player (not an NPC). + * Use this instead of checking {@code target != null} to make NPC/Player + * code paths explicit and readable. + *

+ * NPCs always have an aggro target passed to ability methods. + * Players never do — they use look direction for aiming instead. + */ + protected final boolean isPlayerCaster(EntityLivingBase caster) { + return caster instanceof EntityPlayer; + } + + /** + * Whether the telegraph should remain visible during the ACTIVE phase. + * Default: false (telegraph removed at WINDUP→ACTIVE transition). + * Override for abilities where the active phase IS the attack (e.g., sweeping/spinning attacks) + * so the telegraph stays visible while damage is being dealt. + */ + public boolean keepTelegraphDuringActive() { + return false; + } + /** * Returns true if this ability controls NPC movement during ACTIVE phase. * When true, AI pathfinding will be blocked during ability execution. @@ -411,26 +502,33 @@ public abstract class Ability implements IAbility { defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) .tab("General").range(0, 10000)); defs.add(FieldDef.section("ability.section.movement").tab("General")); - defs.add(FieldDef.row( - FieldDef.stringEnumField("ability.lockPosition", LockMovementType.getDisplayKeys(), + defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), () -> this.getLockMovement().getDisplayKey(), v -> { - String[] keys = LockMovementType.getDisplayKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].equals(v)) { this.setLockMovement(LockMovementType.fromOrdinal(i)); break; } + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setLockMovement(t); break; } } }) - .hover("ability.hover.lockPosition"), - FieldDef.stringEnumField("ability.lockType", LockType.getDisplayKeys(), - () -> this.getLockType().getDisplayKey(), + .hover("ability.hover.lockMovement") + .tab("General")); + defs.add(FieldDef.row( + FieldDef.stringEnumField("ability.rotationMode", RotationMode.getDisplayKeys(), + () -> this.getRotationMode().getDisplayKey(), v -> { - String[] keys = LockType.getDisplayKeys(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].equals(v)) { this.setLockType(LockType.fromOrdinal(i)); break; } + for (RotationMode m : RotationMode.values()) { + if (m.getDisplayKey().equals(v)) { this.setRotationMode(m); break; } } }) - .hover("ability.hover.lockType") - .visibleWhen(() -> this.lockMovement != LockMovementType.NO) + .hover("ability.hover.rotationMode"), + FieldDef.stringEnumField("ability.rotationPhase", getRotationPhaseKeys(), + () -> this.getRotationPhase().getDisplayKey(), + v -> { + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setRotationPhase(t); break; } + } + }) + .hover("ability.hover.rotationPhase") + .visibleWhen(() -> this.rotationMode != RotationMode.FREE) ).tab("General")); defs.add(FieldDef.row( FieldDef.boolField("ability.interruptible", this::isInterruptible, this::setInterruptible) @@ -439,6 +537,25 @@ public abstract class Ability implements IAbility { .range(0, 1000).visibleWhen(this::isInterruptible) ).tab("General")); + // ── Burst section ──────────────────────────────────────────── + if (allowBurst()) { + defs.add(FieldDef.section("ability.section.burst").tab("General")); + defs.add(FieldDef.boolField("ability.burstEnabled", this::isBurstEnabled, this::setBurstEnabled) + .tab("General")); + defs.add(FieldDef.row( + FieldDef.intField("ability.burstAmount", this::getBurstAmount, this::setBurstAmount).range(1, 100), + FieldDef.intField("ability.burstDelay", this::getBurstDelay, this::setBurstDelay).range(0, 1000) + ).tab("General").visibleWhen(this::isBurstEnabled)); + defs.add(FieldDef.boolField("ability.burstReplayAnimations", this::isBurstReplayAnimations, this::setBurstReplayAnimations) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstReplay")); + if (allowOverlap()) { + defs.add(FieldDef.boolField("ability.burstOverlap", this::isBurstOverlap, this::setBurstOverlap) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstOverlap")); + } + } + // ── Target tab ─────────────────────────────────────────────── defs.add(FieldDef.row( FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100), @@ -580,6 +697,9 @@ public abstract class Ability implements IAbility { case POINT: telegraph = new Telegraph("", TelegraphType.POINT); break; + case SQUARE: + telegraph = Telegraph.square(getTelegraphRadius()); + break; default: return null; } @@ -599,12 +719,12 @@ public abstract class Ability implements IAbility { instance.setEntityIdToFollow(caster.getEntityId()); // For LINE/CONE telegraphs: track target direction during windup - // Only track if movement is NOT locked during windup (locked = NPC can't rotate) + // Only track if rotation is NOT locked during windup (NPC can still turn) if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { - if (!lockMovement.locksWindup()) { + if (!isRotationLockedDuringWindup()) { instance.setTargetEntityId(target.getEntityId()); } - // If windup is locked, yaw stays fixed at creation time + // If rotation is locked, yaw stays fixed at creation time } } else if (target != null) { // AOE_TARGET abilities: telegraph follows target during windup @@ -614,6 +734,17 @@ public abstract class Ability implements IAbility { return instance; } + /** + * Create all telegraph instances for this ability. + * Override for abilities that need multiple telegraphs (e.g., zone abilities). + * Default wraps createTelegraph() in a singleton list. + */ + public List createTelegraphs(EntityLivingBase caster, EntityLivingBase target) { + TelegraphInstance instance = createTelegraph(caster, target); + if (instance == null) return new ArrayList<>(); + return new ArrayList<>(Collections.singletonList(instance)); + } + /** * Find the ground level at a given position. * Searches downward from the given Y to find a solid block. @@ -682,17 +813,17 @@ public abstract class Ability implements IAbility { } /** - * Get the current telegraph instance. + * Get the current telegraph instances. */ - public TelegraphInstance getTelegraphInstance() { - return telegraphInstance; + public List getTelegraphInstances() { + return telegraphInstances; } /** - * Set the telegraph instance (called by DataAbilities). + * Set the telegraph instances (called by DataAbilities). */ - public void setTelegraphInstance(TelegraphInstance instance) { - this.telegraphInstance = instance; + public void setTelegraphInstances(List instances) { + this.telegraphInstances = instances != null ? instances : new ArrayList<>(); } // ═══════════════════════════════════════════════════════════════════ @@ -707,6 +838,8 @@ public abstract class Ability implements IAbility { this.currentTick = 0; this.currentTarget = target; this.executionStartTime = System.currentTimeMillis(); + this.burstIndex = 0; + this.burstEntities.clear(); if (windUpTicks <= 0) { this.phase = AbilityPhase.ACTIVE; @@ -749,6 +882,19 @@ public abstract class Ability implements IAbility { return true; } break; + + case BURST_DELAY: + // Waiting between burst repetitions - free movement/rotation + if (currentTick >= burstDelay) { + if (burstReplayAnimations && getWindUpTicks() > 0) { + phase = AbilityPhase.WINDUP; + } else { + phase = AbilityPhase.ACTIVE; + } + currentTick = 0; + return true; + } + break; } return false; } @@ -762,6 +908,19 @@ public abstract class Ability implements IAbility { */ public boolean signalCompletion() { if (phase == AbilityPhase.ACTIVE) { + // Check if more burst iterations remain + if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { + // Don't cleanup here - entities may still be in flight + // For non-overlap: cleaned up when next burst starts (in onExecute) + // For overlap: entities continue flying indefinitely + burstIndex++; + phase = AbilityPhase.BURST_DELAY; + currentTick = 0; + return true; + } + + // Final completion - let burst entities die naturally (don't force-kill) + burstEntities.clear(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; @@ -775,9 +934,10 @@ public abstract class Ability implements IAbility { * Called when NPC takes direct damage during WINDUP. */ public void interrupt() { + cleanupBurstEntities(); cleanup(); - if (interruptible && phase == AbilityPhase.WINDUP) { - // Interrupted during windup - go to dazed state + if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) { + // Interrupted during windup or burst delay - go to dazed state phase = AbilityPhase.DAZED; currentTick = 0; } else { @@ -785,8 +945,9 @@ public abstract class Ability implements IAbility { phase = AbilityPhase.IDLE; currentTick = 0; } + burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); } /** @@ -805,7 +966,7 @@ public abstract class Ability implements IAbility { * @return true if the ability should be interrupted */ public boolean canInterrupt(DamageSource source) { - if (!interruptible || phase != AbilityPhase.WINDUP) { + if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) { return false; } @@ -832,11 +993,15 @@ public abstract class Ability implements IAbility { * Reset all execution state (called on combat end, NPC death, target lost, etc.) */ public void reset() { + cleanupBurstEntities(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; + burstIndex = 0; currentTarget = null; - telegraphInstance = null; + telegraphInstances.clear(); + previewMode = false; + previewEntityHandler = null; } /** @@ -848,91 +1013,73 @@ public abstract class Ability implements IAbility { // Override in subclasses to clean up spawned entities, etc. } + /** + * Kill all entities tracked during burst overlap and clear the list. + */ + protected void cleanupBurstEntities() { + for (Entity e : burstEntities) { + if (e != null && !e.isDead) { + killAbilityEntity(e); + } + } + burstEntities.clear(); + } + // ═══════════════════════════════════════════════════════════════════ - // CLIENT-SIDE PREVIEW METHODS + // PREVIEW MODE SUPPORT // ═══════════════════════════════════════════════════════════════════ /** - * Get total active phase duration for preview (in ticks). - * Override in subclasses to provide accurate preview duration. - * - * @return Duration of active phase in ticks (default: 40 = 2 seconds) + * Whether this ability is running in preview mode (GUI preview). + * When true, abilities should skip damage, effects, sounds, and particles + * but still run their core logic (entity spawning, movement, timing). */ - public int getPreviewActiveDuration() { - return 40; + public boolean isPreview() { + return previewMode; + } + + public void setPreviewMode(boolean preview) { + this.previewMode = preview; + } + + public void setPreviewEntityHandler(PreviewEntityHandler handler) { + this.previewEntityHandler = handler; } /** - * Called during preview windup tick (client-side only). - * Override for visual updates during windup preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within windup phase + * Spawn an entity during ability execution. + * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). */ - @SideOnly(Side.CLIENT) - public void onPreviewWindUpTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void spawnAbilityEntity(Entity entity) { + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntitySpawned(entity); + } else { + entity.worldObj.spawnEntityInWorld(entity); + } + if (burstEnabled && burstOverlap) { + burstEntities.add(entity); + } } /** - * Called during preview active tick (client-side only). - * Override for visual updates during active preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within active phase + * Kill an entity spawned by this ability. + * In preview mode, notifies PreviewEntityHandler of removal. */ - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void killAbilityEntity(Entity entity) { + if (entity == null) return; + entity.setDead(); + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntityRemoved(entity); + } } /** - * Create a preview entity for GUI display (client-side only). - * The entity should be in preview mode and not apply damage. - * Override in abilities that spawn entities (Beam, Orb, Disc, etc.) - * - * @param npc The preview NPC - * @return Preview entity, or null if ability doesn't spawn entities + * Maximum duration (in ticks) for preview before auto-stopping. + * Override in movement abilities that have variable duration. + * Default: 200 ticks (10 seconds). */ - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - return null; // Override in entity-spawning abilities - } - - /** - * Whether to spawn preview entity during WINDUP phase (true) or ACTIVE phase (false). - * Most abilities (Orb, Beam, Disc) spawn during windup for charging effect. - * Laser spawns at active phase since it has no charging state. - */ - public boolean spawnPreviewDuringWindup() { - return true; // Default: spawn during windup for charging - } - - // ── Preview target (set by executor for abilities that need targeting) ── - - protected transient EntityLivingBase previewTarget; - - /** - * Set the fake target entity for preview mode. - * Called by AbilityPreviewExecutor before starting preview. - */ - public void setPreviewTarget(EntityLivingBase target) { - this.previewTarget = target; - } - - public EntityLivingBase getPreviewTarget() { - return previewTarget; - } - - /** - * Called once when transitioning from WINDUP to ACTIVE in preview mode. - * Override in movement-based abilities to initiate movement. - */ - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - // Default: no-op. Override in movement abilities. + public int getMaxPreviewDuration() { + return 200; } // ═══════════════════════════════════════════════════════════════════ @@ -978,7 +1125,8 @@ public abstract class Ability implements IAbility { nbt.setInteger("recovery", dazedTicks); nbt.setBoolean("interruptible", interruptible); nbt.setInteger("lockMovement", lockMovement.ordinal()); - nbt.setInteger("lockType", lockType.ordinal()); + nbt.setInteger("rotationMode", rotationMode.ordinal()); + nbt.setInteger("rotationPhase", rotationPhase.ordinal()); nbt.setInteger("windUpColor", windUpColor); nbt.setInteger("activeColor", activeColor); nbt.setString("windUpSound", windUpSound); @@ -990,10 +1138,17 @@ public abstract class Ability implements IAbility { nbt.setBoolean("showTelegraph", showTelegraph); nbt.setString("telegraphType", telegraphType.name()); nbt.setFloat("telegraphHeightOffset", telegraphHeightOffset); - nbt.setTag("customData", customData); + nbt.setTag("customData", (NBTTagCompound) customData.copy()); nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + // Burst + nbt.setBoolean("burstEnabled", burstEnabled); + nbt.setInteger("burstAmount", burstAmount); + nbt.setInteger("burstDelay", burstDelay); + nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); + nbt.setBoolean("burstOverlap", burstOverlap); + // Conditions NBTTagList condList = new NBTTagList(); for (Condition c : conditions) condList.appendTag(c.writeNBT()); @@ -1025,31 +1180,37 @@ public abstract class Ability implements IAbility { maxRange = nbt.getFloat("maxRange"); cooldownTicks = nbt.getInteger("cooldown"); windUpTicks = nbt.getInteger("windUp"); - syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup"); + syncWindupWithAnimation = nbt.getBoolean("syncWindup"); dazedTicks = nbt.getInteger("recovery"); interruptible = nbt.getBoolean("interruptible"); lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); - lockType = nbt.hasKey("lockType") ? LockType.fromOrdinal(nbt.getInteger("lockType")) : LockType.BOTH; + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); windUpColor = nbt.getInteger("windUpColor"); activeColor = nbt.getInteger("activeColor"); windUpSound = nbt.getString("windUpSound"); activeSound = nbt.getString("activeSound"); - windUpAnimationId = nbt.hasKey("windUpAnimationId") ? nbt.getInteger("windUpAnimationId") : -1; - activeAnimationId = nbt.hasKey("activeAnimationId") ? nbt.getInteger("activeAnimationId") : -1; + windUpAnimationId = nbt.getInteger("windUpAnimationId"); + activeAnimationId = nbt.getInteger("activeAnimationId"); windUpAnimationName = nbt.getString("windUpAnimationName"); activeAnimationName = nbt.getString("activeAnimationName"); - showTelegraph = !nbt.hasKey("showTelegraph") || nbt.getBoolean("showTelegraph"); - if (nbt.hasKey("telegraphType")) { - try { - telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); - } catch (Exception e) { - telegraphType = TelegraphType.CIRCLE; - } + showTelegraph = nbt.getBoolean("showTelegraph"); + try { + telegraphType = TelegraphType.valueOf(nbt.getString("telegraphType")); + } catch (Exception e) { + telegraphType = TelegraphType.CIRCLE; } - telegraphHeightOffset = nbt.hasKey("telegraphHeightOffset") ? nbt.getFloat("telegraphHeightOffset") : 0.1f; + telegraphHeightOffset = nbt.getFloat("telegraphHeightOffset"); customData = nbt.getCompoundTag("customData"); - allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; - ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); + allowedBy = UserType.fromOrdinal(nbt.getInteger("allowedBy")); + ignoreCooldown = nbt.getBoolean("ignoreCooldown"); + + // Burst + burstEnabled = nbt.getBoolean("burstEnabled"); + burstAmount = nbt.getInteger("burstAmount"); + burstDelay = nbt.getInteger("burstDelay"); + burstReplayAnimations = nbt.getBoolean("burstReplayAnimations"); + burstOverlap = nbt.getBoolean("burstOverlap"); // Conditions conditions.clear(); @@ -1098,6 +1259,22 @@ public abstract class Ability implements IAbility { return typeId; } + public boolean isBuiltIn() { + return false; + } + + public Ability deepCopy() { + return AbilityController.Instance.fromNBT(this.writeNBT()); + } + + public boolean isNpcInlineEdit() { + return npcInlineEdit; + } + + public void setNpcInlineEdit(boolean npcInlineEdit) { + this.npcInlineEdit = npcInlineEdit; + } + public int getWeight() { return weight; } @@ -1194,12 +1371,20 @@ public abstract class Ability implements IAbility { this.lockMovement = lockMovement; } - public LockType getLockType() { - return lockType; + public RotationMode getRotationMode() { + return rotationMode; } - public void setLockType(LockType lockType) { - this.lockType = lockType; + public void setRotationMode(RotationMode rotationMode) { + this.rotationMode = rotationMode; + } + + public LockMovementType getRotationPhase() { + return rotationPhase; + } + + public void setRotationPhase(LockMovementType rotationPhase) { + this.rotationPhase = rotationPhase; } /** @@ -1221,21 +1406,39 @@ public abstract class Ability implements IAbility { } /** - * API method: Get lock type as integer. - * @return 0=MOVEMENT, 1=ROTATION, 2=BOTH + * API method: Get rotation mode as integer. + * @return 0=FREE, 1=LOCKED, 2=TRACK */ @Override - public int getLockTypeOrdinal() { - return lockType.ordinal(); + public int getRotationModeType() { + return rotationMode.ordinal(); } /** - * API method: Set lock type from integer. - * @param type 0=MOVEMENT, 1=ROTATION, 2=BOTH + * API method: Set rotation mode from integer. + * @param type 0=FREE, 1=LOCKED, 2=TRACK */ @Override - public void setLockTypeOrdinal(int type) { - this.lockType = LockType.fromOrdinal(type); + public void setRotationModeType(int type) { + this.rotationMode = RotationMode.fromOrdinal(type); + } + + /** + * API method: Get rotation phase as integer. + * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public int getRotationPhaseType() { + return rotationPhase.ordinal(); + } + + /** + * API method: Set rotation phase from integer. + * @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public void setRotationPhaseType(int type) { + this.rotationPhase = LockMovementType.fromOrdinal(type); } /** @@ -1243,7 +1446,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isMovementLockedDuringWindup() { - return lockMovement.locksWindup() && lockType.locksMovement(); + return lockMovement.locksWindup(); } /** @@ -1251,7 +1454,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isMovementLockedDuringActive() { - return lockMovement.locksActive() && lockType.locksMovement(); + return lockMovement.locksActive(); } /** @@ -1259,7 +1462,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isRotationLockedDuringWindup() { - return lockMovement.locksWindup() && lockType.locksRotation(); + return rotationMode == RotationMode.LOCKED && rotationPhase.locksWindup(); } /** @@ -1267,7 +1470,7 @@ public abstract class Ability implements IAbility { */ @Override public boolean isRotationLockedDuringActive() { - return lockMovement.locksActive() && lockType.locksRotation(); + return rotationMode == RotationMode.LOCKED && rotationPhase.locksActive(); } /** @@ -1279,6 +1482,8 @@ public abstract class Ability implements IAbility { return isMovementLockedDuringWindup(); case ACTIVE: return isMovementLockedDuringActive(); + case BURST_DELAY: + return false; // Free movement during burst delay default: return false; } @@ -1293,6 +1498,25 @@ public abstract class Ability implements IAbility { return isRotationLockedDuringWindup(); case ACTIVE: return isRotationLockedDuringActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay + default: + return false; + } + } + + /** + * Check if hit scan (force face target) is active during the current phase. + */ + public boolean isHitScanForCurrentPhase() { + if (rotationMode != RotationMode.TRACK) return false; + switch (phase) { + case WINDUP: + return rotationPhase.locksWindup(); + case ACTIVE: + return rotationPhase.locksActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay default: return false; } @@ -1481,6 +1705,63 @@ public abstract class Ability implements IAbility { effects.clear(); } + // Burst getters/setters + + public boolean isBurstEnabled() { + return burstEnabled; + } + + public void setBurstEnabled(boolean burstEnabled) { + this.burstEnabled = burstEnabled; + } + + public int getBurstAmount() { + return burstAmount; + } + + public void setBurstAmount(int burstAmount) { + this.burstAmount = Math.max(0, burstAmount); + } + + public int getBurstDelay() { + return burstDelay; + } + + public void setBurstDelay(int burstDelay) { + this.burstDelay = Math.max(0, burstDelay); + } + + public boolean isBurstReplayAnimations() { + return burstReplayAnimations; + } + + public void setBurstReplayAnimations(boolean burstReplayAnimations) { + this.burstReplayAnimations = burstReplayAnimations; + } + + public boolean isBurstOverlap() { + return burstOverlap; + } + + public void setBurstOverlap(boolean burstOverlap) { + this.burstOverlap = burstOverlap; + } + + public int getBurstIndex() { + return burstIndex; + } + + /** + * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). + */ + private static String[] getRotationPhaseKeys() { + return new String[]{ + "ability.lockMove.windup", + "ability.lockMove.active", + "ability.lockMove.both" + }; + } + // ═══════════════════════════════════════════════════════════════════ // SHIT FROM THE ASS // ═══════════════════════════════════════════════════════════════════ @@ -1518,6 +1799,52 @@ public abstract class Ability implements IAbility { return totalDuration; } + // ═══════════════════════════════════════════════════════════════════ + // MOVEMENT COLLISION UTILITY + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check if a caster's movement in a given direction is blocked by walls/blocks. + * Used by Charge and Dash abilities to detect wall collision. + * + * @param caster The entity moving + * @param dirX X component of normalized movement direction + * @param dirZ Z component of normalized movement direction + * @param speed Movement speed (blocks per tick) + * @return true if movement is blocked + */ + protected static boolean isMovementBlocked(EntityLivingBase caster, double dirX, double dirZ, double speed) { + double nextX = dirX * speed; + double nextZ = dirZ * speed; + AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); + double stepThreshold = nextBox.minY + Math.max(caster.stepHeight, 0.5); + + int x1 = (int) Math.floor(nextBox.minX); + int x2 = (int) Math.floor(nextBox.maxX + 1.0); + int y1 = (int) Math.floor(nextBox.minY) - 1; + int y2 = (int) Math.floor(nextBox.maxY + 1.0); + int z1 = (int) Math.floor(nextBox.minZ); + int z2 = (int) Math.floor(nextBox.maxZ + 1.0); + + java.util.ArrayList collisionBoxes = new java.util.ArrayList<>(); + for (int bx = x1; bx < x2; bx++) { + for (int bz = z1; bz < z2; bz++) { + for (int by = y1; by < y2; by++) { + Block block = caster.worldObj.getBlock(bx, by, bz); + if (!block.getMaterial().blocksMovement()) continue; + collisionBoxes.clear(); + block.addCollisionBoxesToList(caster.worldObj, bx, by, bz, nextBox, collisionBoxes, caster); + for (AxisAlignedBB box : collisionBoxes) { + if (box.maxY > stepThreshold) { + return true; + } + } + } + } + } + return false; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 213c1a214..c492cf50b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -2,102 +2,172 @@ package kamkeel.npcs.controllers.data.ability; import kamkeel.npcs.controllers.data.ability.type.*; import kamkeel.npcs.controllers.SyncController; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; import noppes.npcs.LogWriter; import noppes.npcs.api.handler.IAbilityHandler; import noppes.npcs.util.NBTJsonUtil; +import net.minecraft.entity.player.EntityPlayer; + import java.io.File; import java.util.*; +import java.util.function.Predicate; import java.util.function.Supplier; -/** - * Central controller for ability types and presets. - *

- * Three maps: - *

    - *
  • {@code typeFactories} — keyed by typeId (lang key), creates new instances of each ability type
  • - *
  • {@code abilities} — built-in pre-configured abilities, keyed by unique name
  • - *
  • {@code customAbilities} — user-created presets, keyed by UUID
  • - *
- */ public class AbilityController implements IAbilityHandler { public static AbilityController Instance = new AbilityController(); - /** Type factories keyed by typeId (lang key, e.g. "ability.cnpc.slam"). */ - private final Map> typeFactories = new LinkedHashMap<>(); - - /** Built-in pre-configured abilities keyed by unique name. */ - private final Map abilities = new LinkedHashMap<>(); - - /** User-created custom ability presets keyed by UUID. */ + // ── Core Registries ────────────────────────────────────────────────────── + private final Map> abilityTypes = new LinkedHashMap<>(); + private final Map builtAbilities = new LinkedHashMap<>(); private final Map customAbilities = new LinkedHashMap<>(); - /** Version counter — incremented on any custom ability add/modify/delete. - * Used by AbilitySlot for cache invalidation. */ - private int version = 0; - - /** External damage handler (e.g., DBC Addon). */ - private IAbilityDamageHandler damageHandler = null; - - /** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */ + // ── Extension Points ───────────────────────────────────────────────────── + private final Map> externalVariants = new LinkedHashMap<>(); private final List fieldProviders = new ArrayList<>(); + private final List extenders = new ArrayList<>(); + private final List> flightCheckers = new ArrayList<>(); + + // ── Derived State ──────────────────────────────────────────────────────── + private final Set builtInTypeIds = new HashSet<>(); public AbilityController() { registerBuiltinTypes(); } // ═══════════════════════════════════════════════════════════════════════════ - // LOADING / SAVING CUSTOM ABILITIES + // TYPE REGISTRATION // ═══════════════════════════════════════════════════════════════════════════ - /** - * Load custom ability presets from world directory. - * Called when world loads. Files are named {@code .json}. - */ - public void load() { - customAbilities.clear(); - File dir = getDir(); - if (!dir.exists()) { - return; + public void registerType(String factoryKey, Supplier factory) { + Ability temp = factory.get(); + String typeId = temp.getTypeId(); + if (abilityTypes.containsKey(typeId)) { + LogWriter.info("AbilityController: Overwriting type: " + typeId); + } + abilityTypes.put(typeId, factory); + if (temp.isBuiltIn()) { + builtInTypeIds.add(typeId); + } + } + + public Ability create(String typeId) { + Supplier factory = abilityTypes.get(typeId); + return factory != null ? factory.get() : null; + } + + public Ability fromNBT(NBTTagCompound nbt) { + if (nbt == null || !nbt.hasKey("typeId")) { + return null; } - File[] files = dir.listFiles(); - if (files == null) return; + String typeId = nbt.getString("typeId"); + Supplier factory = abilityTypes.get(typeId); + if (factory == null) { + LogWriter.info("AbilityController: Unknown ability type: " + typeId); + return null; + } - 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 + Ability ability = factory.get(); + ability.readNBT(nbt); + return ability; + } - NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); - Ability ability = fromNBT(nbt); - if (ability != null) { - ability.setId(uuid); - customAbilities.put(uuid, ability); - } - } catch (Exception e) { - LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); + private void registerBuiltinTypes() { + registerType("cnpc:slam", AbilitySlam::new); + registerType("cnpc:heavy_hit", AbilityHeavyHit::new); + registerType("cnpc:cutter", AbilityCutter::new); + + registerType("cnpc:sweeper", AbilitySweeper::new); + registerType("cnpc:projectile", AbilityProjectile::new); + registerType("cnpc:orb", AbilityOrb::new); + registerType("cnpc:disc", AbilityDisc::new); + registerType("cnpc:laser_shot", AbilityLaserShot::new); + registerType("cnpc:beam", AbilityBeam::new); + + registerType("cnpc:charge", AbilityCharge::new); + registerType("cnpc:dash", AbilityDash::new); + registerType("cnpc:teleport", AbilityTeleport::new); + registerType("cnpc:vortex", AbilityVortex::new); + registerType("cnpc:shockwave", AbilityShockwave::new); + + registerType("cnpc:guard", AbilityGuard::new); + registerType("cnpc:heal", AbilityHeal::new); + + registerType("cnpc:hazard", AbilityHazard::new); + registerType("cnpc:trap", AbilityTrap::new); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // BUILT-IN ABILITIES + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerAbility(String name, Ability ability) { + if (builtAbilities.containsKey(name)) { + LogWriter.info("AbilityController: Overwriting built-in ability: " + name); + } + if (!ability.isBuiltIn()) { + ability.setName(name); + } + builtAbilities.put(name, ability); + LogWriter.info("Registered ability: " + name); + } + + public Ability getAbility(String name) { + return builtAbilities.get(name); + } + + public Ability getAbilityByDisplayName(String displayName) { + for (Ability ability : builtAbilities.values()) { + if (ability.getName().equals(displayName)) { + return ability; } } + return null; + } + + public Set getAbilityNames() { + return new LinkedHashSet<>(builtAbilities.keySet()); + } + + // ═══════════════════════════════════════════════════════════════════════════ + // CUSTOM ABILITIES + // ═══════════════════════════════════════════════════════════════════════════ + + // Incremented on any custom ability change; used by AbilitySlot for cache invalidation + private int customAbilityRevision = 0; + + public void load() { + customAbilities.clear(); + + File dir = getDir(); + File[] files = dir.exists() ? dir.listFiles() : null; + if (files != null) { + 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); + + NBTTagCompound nbt = NBTJsonUtil.LoadFile(file); + Ability ability = fromNBT(nbt); + if (ability != null) { + ability.setId(uuid); + customAbilities.put(uuid, ability); + } + } catch (Exception e) { + LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e); + } + } + } + + customAbilityRevision++; LogWriter.info("Loaded " + customAbilities.size() + " custom abilities"); } - private File getDir() { - File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities"); - if (!dir.exists()) { - dir.mkdirs(); - } - return dir; - } - - /** - * Save a custom ability preset. If the ability has no id, generates a UUID. - * Stores in customAbilities map and writes to disk. - */ public boolean saveCustomAbility(Ability ability) { if (ability == null) return false; @@ -124,7 +194,7 @@ public class AbilityController implements IAbilityHandler { } customAbilities.put(uuid, ability); - version++; + customAbilityRevision++; LogWriter.info("Saved custom ability: " + ability.getName() + " [" + uuid + "]"); SyncController.syncAllCustomAbilities(); return true; @@ -134,9 +204,6 @@ public class AbilityController implements IAbilityHandler { } } - /** - * Delete a custom ability preset by UUID. - */ public boolean deleteCustomAbility(String uuid) { if (uuid == null || uuid.isEmpty()) return false; @@ -149,142 +216,295 @@ public class AbilityController implements IAbilityHandler { file.delete(); } - version++; + customAbilityRevision++; LogWriter.info("Deleted custom ability: " + uuid); SyncController.syncAllCustomAbilities(); return true; } - // ═══════════════════════════════════════════════════════════════════════════ - // BUILT-IN ABILITY REGISTRY - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register a pre-configured built-in ability by name. - * These are looked up by name in {@link #resolveAbility(String)}. - * - * @param name Unique name (e.g., "Jump Attack", "Ki Blast") - * @param ability Pre-configured ability instance - */ - public void registerAbility(String name, Ability ability) { - if (abilities.containsKey(name)) { - LogWriter.info("AbilityController: Overwriting built-in ability: " + name); - } - 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 an ability key exists (either built-in or custom). - */ - public boolean hasAbility(String key) { - return abilities.containsKey(key) || customAbilities.containsKey(key); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // 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 built-in ability names. */ - public Set 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 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 getCustomAbilities() { return customAbilities; } - /** Replace the custom abilities map (used by client-side sync). */ public void setCustomAbilities(Map synced) { customAbilities.clear(); customAbilities.putAll(synced); - version++; + customAbilityRevision++; } - /** Get the version counter (incremented on custom ability changes). */ - public int getVersion() { - return version; + public int getCustomAbilityRevision() { + return customAbilityRevision; + } + + private File getDir() { + File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities"); + if (!dir.exists()) { + dir.mkdirs(); + } + return dir; } // ═══════════════════════════════════════════════════════════════════════════ - // IAbilityHandler INTERFACE IMPLEMENTATION + // RESOLUTION + // ═══════════════════════════════════════════════════════════════════════════ + + public Ability resolveAbility(String key) { + if (key == null || key.isEmpty()) return null; + + // Built-in: exact name + Ability builtIn = builtAbilities.get(key); + if (builtIn != null) return builtIn.deepCopy(); + + // Built-in: case-insensitive name + for (Map.Entry entry : builtAbilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue().deepCopy(); + } + } + + // Built-in: registry key / ID + for (Ability ability : builtAbilities.values()) { + if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { + return ability.deepCopy(); + } + } + + // Custom: exact UUID + Ability custom = customAbilities.get(key); + if (custom != null) return custom.deepCopy(); + + // Custom: case-insensitive name + for (Ability ability : customAbilities.values()) { + if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { + return ability.deepCopy(); + } + } + + return null; + } + + public Set getAbilityKeys() { + Set keys = new LinkedHashSet<>(); + for (Ability ability : builtAbilities.values()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + // Use ability names for custom abilities (instead of UUIDs) for readable tab completion + for (Ability ability : customAbilities.values()) { + String name = ability.getName(); + if (name != null && !name.isEmpty()) { + keys.add(name); + } + } + return keys; + } + + public Set getPlayerAbilityKeys() { + Set keys = new LinkedHashSet<>(); + for (Ability ability : builtAbilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + } + // Use ability names for custom abilities (instead of UUIDs) for readable tab completion + for (Ability ability : customAbilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String name = ability.getName(); + if (name != null && !name.isEmpty()) { + keys.add(name); + } + } + } + return keys; + } + + public boolean hasAbility(String key) { + return builtAbilities.containsKey(key) || customAbilities.containsKey(key); + } + + /** + * Check if a key can be resolved to a valid ability without creating a deep copy. + * Uses the same lookup chain as {@link #resolveAbility(String)}. + */ + public boolean canResolveAbility(String key) { + if (key == null || key.isEmpty()) return false; + + // Built-in: exact name + if (builtAbilities.containsKey(key)) return true; + + // Built-in: case-insensitive name + for (String name : builtAbilities.keySet()) { + if (name.equalsIgnoreCase(key)) return true; + } + + // Built-in: registry key / ID + for (Ability ability : builtAbilities.values()) { + if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) return true; + } + + // Custom: exact UUID + if (customAbilities.containsKey(key)) return true; + + // Custom: case-insensitive name + for (Ability ability : customAbilities.values()) { + if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) return true; + } + + return false; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // EXTENSION POINTS + // ═══════════════════════════════════════════════════════════════════════════ + + public void registerVariant(String typeId, AbilityVariant variant) { + externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); + } + + public List getVariantsForType(String typeId) { + List result = new ArrayList<>(); + Ability temp = create(typeId); + if (temp != null) { + result.addAll(temp.getVariants()); + } + List ext = externalVariants.get(typeId); + if (ext != null) { + // If no built-in variants exist but external ones do, + // inject a "Base" variant so the user always gets a choice + if (result.isEmpty()) { + result.add(new AbilityVariant("ability.variant.base", a -> {})); + } + result.addAll(ext); + } + return result; + } + + public void registerFieldProvider(IAbilityFieldProvider provider) { + fieldProviders.add(provider); + } + + public List getFieldProviders() { + return fieldProviders; + } + + public void registerExtender(IAbilityExtender extender) { + extenders.add(extender); + } + + public List getExtenders() { + return extenders; + } + + public void registerFlightChecker(Predicate checker) { + flightCheckers.add(checker); + } + + public boolean isPlayerFlying(EntityPlayer player) { + if (player.capabilities.isFlying) return true; + for (Predicate checker : flightCheckers) { + if (checker.test(player)) return true; + } + return false; + } + + /** + * Fire onAbilityStart on all extenders. Returns false if ANY extender cancels. + */ + public boolean fireOnAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) { + for (IAbilityExtender ext : extenders) { + if (!ext.onAbilityStart(ability, caster, target)) { + return false; + } + } + return true; + } + + /** + * Fire onAbilityTick on all extenders. Returns false if ANY extender says to interrupt. + */ + public boolean fireOnAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target, + AbilityPhase phase, int tick) { + for (IAbilityExtender ext : extenders) { + if (!ext.onAbilityTick(ability, caster, target, phase, tick)) { + return false; + } + } + return true; + } + + /** + * Fire onAbilityComplete on all extenders. + */ + public void fireOnAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target, + boolean interrupted) { + for (IAbilityExtender ext : extenders) { + ext.onAbilityComplete(ability, caster, target, interrupted); + } + } + + /** + * Fire onAbilityDamage on all extenders. Chain of responsibility — first true wins. + */ + public boolean fireOnAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ) { + for (IAbilityExtender ext : extenders) { + if (ext.onAbilityDamage(ability, caster, target, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ)) { + return true; + } + } + return false; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // IAbilityHandler // ═══════════════════════════════════════════════════════════════════════════ @Override public String[] getTypes() { - return typeFactories.keySet().toArray(new String[0]); + return abilityTypes.keySet().toArray(new String[0]); + } + + public boolean isBuiltInType(String typeId) { + return builtInTypeIds.contains(typeId); } @Override public boolean hasType(String typeId) { - return typeFactories.containsKey(typeId); + return abilityTypes.containsKey(typeId); } @Override public String[] getAbilityNameArray() { - return abilities.keySet().toArray(new String[0]); + return builtAbilities.keySet().toArray(new String[0]); } @Override public boolean hasAbilityName(String name) { - return abilities.containsKey(name); + return builtAbilities.containsKey(name); } @Override @@ -301,130 +521,4 @@ public class AbilityController implements IAbilityHandler { public boolean deleteCustomAbilityById(String uuid) { return deleteCustomAbility(uuid); } - - // ═══════════════════════════════════════════════════════════════════════════ - // TYPE REGISTRATION - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register a new ability type. - * Extracts the typeId from a temporary instance and stores in typeFactories. - * - * @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 factory) { - Ability temp = factory.get(); - 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 look up in typeFactories. - */ - public Ability fromNBT(NBTTagCompound nbt) { - if (nbt == null || !nbt.hasKey("typeId")) { - return null; - } - - String typeId = nbt.getString("typeId"); - Supplier factory = typeFactories.get(typeId); - if (factory == null) { - LogWriter.info("AbilityController: Unknown ability type: " + typeId); - return null; - } - - Ability ability = factory.get(); - ability.readNBT(nbt); - return ability; - } - - /** - * Create a new empty ability of the given type. - * - * @param typeId The ability typeId (e.g., "ability.cnpc.slam") - */ - public Ability create(String typeId) { - Supplier factory = typeFactories.get(typeId); - if (factory == null) { - return null; - } - return factory.get(); - } - - /** - * Register built-in ability types. - */ - private void registerBuiltinTypes() { - // Melee/AOE damage abilities - registerType("cnpc:slam", AbilitySlam::new); - registerType("cnpc:heavy_hit", AbilityHeavyHit::new); - registerType("cnpc:cutter", AbilityCutter::new); - - // Ranged/Projectile abilities - registerType("cnpc:sweeper", AbilitySweeper::new); - registerType("cnpc:projectile", AbilityProjectile::new); - registerType("cnpc:orb", AbilityOrb::new); - registerType("cnpc:dual_orb", AbilityOrbDual::new); - registerType("cnpc:orb_barrage", AbilityOrbBarrage::new); - registerType("cnpc:dual_disc", AbilityDisc::new); - registerType("cnpc:dual_disc", AbilityDiscDual::new); - registerType("cnpc:laser_shot", AbilityLaserShot::new); - registerType("cnpc:beam", AbilityBeam::new); - registerType("cnpc:dual_beam", AbilityBeamDual::new); - - // Movement abilities - registerType("cnpc:charge", AbilityCharge::new); - registerType("cnpc:dash", AbilityDash::new); - registerType("cnpc:teleport", AbilityTeleport::new); - registerType("cnpc:vortex", AbilityVortex::new); - registerType("cnpc:shockwave", AbilityShockwave::new); - - // Defensive abilities - registerType("cnpc:guard", AbilityGuard::new); - registerType("cnpc:heal", AbilityHeal::new); - - // Zone/Trap abilities - registerType("cnpc:hazard", AbilityHazard::new); - registerType("cnpc:trap", AbilityTrap::new); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL DAMAGE HANDLER - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external damage handler for abilities. - * When set, the handler is called before default damage application. - * If the handler returns true, default damage is skipped. - */ - public void registerDamageHandler(IAbilityDamageHandler handler) { - this.damageHandler = handler; - } - - /** Get the registered damage handler, or null if none. */ - public IAbilityDamageHandler getDamageHandler() { - return damageHandler; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EXTERNAL FIELD PROVIDERS - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Register an external field provider for ability GUIs. - * Providers are called during getAllDefinitions() to inject custom tabs/fields. - */ - public void registerFieldProvider(IAbilityFieldProvider provider) { - fieldProviders.add(provider); - } - - /** Get all registered field providers. */ - public List getFieldProviders() { - return fieldProviders; - } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java index 57f0cbf17..e2c1da87d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java @@ -2,66 +2,24 @@ package kamkeel.npcs.controllers.data.ability; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; +import noppes.npcs.constants.EnumPotionType; /** * Represents a configurable potion effect that can be applied by abilities. - * Provides a unified system for managing debuffs like slowness, weakness, poison, etc. + * Uses the unified EnumPotionType enum shared across melee, ranged, and ability systems. */ public class AbilityEffect { - public enum EffectType { - NONE("gui.none", -1), - SLOWNESS("potion.moveSlowdown", Potion.moveSlowdown.id), - WEAKNESS("potion.weakness", Potion.weakness.id), - POISON("potion.poison", Potion.poison.id), - WITHER("potion.wither", Potion.wither.id), - BLINDNESS("potion.blindness", Potion.blindness.id), - NAUSEA("potion.confusion", Potion.confusion.id), - HUNGER("potion.hunger", Potion.hunger.id), - MINING_FATIGUE("potion.digSlowDown", Potion.digSlowdown.id); - - private final String langKey; - private final int potionId; - - EffectType(String langKey, int potionId) { - this.langKey = langKey; - this.potionId = potionId; - } - - public String getLangKey() { - return langKey; - } - - public int getPotionId() { - return potionId; - } - - public static String[] getLangKeys() { - EffectType[] types = values(); - String[] keys = new String[types.length]; - for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; - return keys; - } - - public static EffectType fromOrdinal(int ordinal) { - EffectType[] values = values(); - if (ordinal >= 0 && ordinal < values.length) { - return values[ordinal]; - } - return NONE; - } - } - - private EffectType type = EffectType.NONE; + private EnumPotionType type = EnumPotionType.None; + private int manualPotionId = 0; private int durationTicks = 60; private int amplifier = 0; // 0-10 public AbilityEffect() { } - public AbilityEffect(EffectType type, int durationTicks, int amplifier) { + public AbilityEffect(EnumPotionType type, int durationTicks, int amplifier) { this.type = type; this.durationTicks = Math.max(1, durationTicks); this.amplifier = Math.max(0, Math.min(10, amplifier)); @@ -71,20 +29,27 @@ public class AbilityEffect { * Creates a copy of this effect. */ public AbilityEffect copy() { - return new AbilityEffect(type, durationTicks, amplifier); + AbilityEffect copy = new AbilityEffect(type, durationTicks, amplifier); + copy.manualPotionId = this.manualPotionId; + return copy; } /** * Applies this effect to the given entity. - * Does nothing if type is NONE. + * Does nothing if type is None. Validates potion IDs before applying. */ public void apply(EntityLivingBase entity) { - if (entity == null || type == EffectType.NONE) { + if (entity == null || type == EnumPotionType.None) { return; } - int potionId = type.getPotionId(); - if (potionId >= 0) { + if (type == EnumPotionType.Fire) { + entity.setFire(Math.max(1, durationTicks / 20)); + return; + } + + int potionId = type.getResolvedPotionId(manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { entity.addPotionEffect(new PotionEffect(potionId, durationTicks, amplifier)); } } @@ -94,9 +59,12 @@ public class AbilityEffect { */ public NBTTagCompound writeNBT() { NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("type", type.ordinal()); + nbt.setInteger("potionType", type.ordinal()); nbt.setInteger("duration", durationTicks); nbt.setInteger("amplifier", amplifier); + if (type == EnumPotionType.Manual) { + nbt.setInteger("manualPotionId", manualPotionId); + } return nbt; } @@ -104,9 +72,12 @@ public class AbilityEffect { * Reads this effect from NBT. */ public void readNBT(NBTTagCompound nbt) { - this.type = EffectType.fromOrdinal(nbt.getInteger("type")); - this.durationTicks = nbt.hasKey("duration") ? nbt.getInteger("duration") : 60; - this.amplifier = nbt.hasKey("amplifier") ? nbt.getInteger("amplifier") : 0; + this.type = EnumPotionType.fromOrdinal(nbt.getInteger("potionType")); + this.durationTicks = nbt.getInteger("duration"); + this.amplifier = nbt.getInteger("amplifier"); + if (type == EnumPotionType.Manual) { + this.manualPotionId = nbt.getInteger("manualPotionId"); + } } /** @@ -120,12 +91,20 @@ public class AbilityEffect { // Getters & Setters - public EffectType getType() { + public EnumPotionType getType() { return type; } - public void setType(EffectType type) { - this.type = type != null ? type : EffectType.NONE; + public void setType(EnumPotionType type) { + this.type = type != null ? type : EnumPotionType.None; + } + + public int getManualPotionId() { + return manualPotionId; + } + + public void setManualPotionId(int manualPotionId) { + this.manualPotionId = Math.max(0, manualPotionId); } public int getDurationTicks() { @@ -145,9 +124,9 @@ public class AbilityEffect { } /** - * Returns true if this effect is configured (not NONE). + * Returns true if this effect is configured (not None). */ public boolean isValid() { - return type != EffectType.NONE; + return type != EnumPotionType.None; } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java index 0611a0274..af1bd8d30 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java @@ -4,5 +4,6 @@ public enum AbilityPhase { IDLE, // Not executing WINDUP, // Charging up (telegraph visible) ACTIVE, // Executing (damage happens) - DAZED // Stunned after interrupt during WINDUP (cannot attack) + DAZED, // Stunned after interrupt during WINDUP (cannot attack) + BURST_DELAY // Waiting between burst repetitions (free movement/rotation) } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java index ca4e7471e..4849e4dd4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilitySlot.java @@ -14,6 +14,9 @@ public class AbilitySlot { private Ability inlineAbility; private String referenceId; + /** Per-slot enabled override for reference slots (null = use master's default). */ + private Boolean enabledOverride; + private transient Ability cachedAbility; private transient int cachedVersion = -1; @@ -61,16 +64,38 @@ public class AbilitySlot { AbilityController controller = AbilityController.Instance; if (controller == null) return null; - int currentVersion = controller.getVersion(); + int currentVersion = controller.getCustomAbilityRevision(); if (cachedAbility != null && cachedVersion == currentVersion) { return cachedAbility; } cachedAbility = controller.resolveAbility(referenceId); + // Apply per-slot enabled override so NPC-specific enable/disable persists + if (cachedAbility != null && enabledOverride != null) { + cachedAbility.setEnabled(enabledOverride); + } cachedVersion = currentVersion; return cachedAbility; } + /** + * Set the per-slot enabled override for reference slots. + * For inline slots, delegates directly to the ability. + */ + public void setEnabled(boolean enabled) { + if (!isReference()) { + if (inlineAbility != null) { + inlineAbility.setEnabled(enabled); + } + } else { + this.enabledOverride = enabled; + // Also update the cached ability immediately if present + if (cachedAbility != null) { + cachedAbility.setEnabled(enabled); + } + } + } + /** * Get the inline ability directly (null for reference slots). */ @@ -104,6 +129,9 @@ public class AbilitySlot { if (isReference()) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setString("Reference", referenceId); + if (enabledOverride != null) { + nbt.setBoolean("RefEnabled", enabledOverride); + } return nbt; } return inlineAbility != null ? inlineAbility.writeNBT() : new NBTTagCompound(); @@ -113,7 +141,11 @@ public class AbilitySlot { if (nbt == null) return null; if (nbt.hasKey("Reference")) { - return reference(nbt.getString("Reference")); + AbilitySlot slot = reference(nbt.getString("Reference")); + if (nbt.hasKey("RefEnabled")) { + slot.enabledOverride = nbt.getBoolean("RefEnabled"); + } + return slot; } // Inline ability diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java new file mode 100644 index 000000000..797e6b20b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -0,0 +1,54 @@ +package kamkeel.npcs.controllers.data.ability; + +import java.util.function.Consumer; + +/** + * Represents a variant/template for an ability type. + * When a user creates an ability that has registered variants, + * they are presented with a selection dialog before the ability is created. + * + * Each variant has a display name (lang key) and a configurator that + * applies preset values to the newly created ability. + */ +public class AbilityVariant { + + private final String displayKey; + private final String group; + private final Consumer configurator; + + /** + * @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, Consumer configurator) { + this(displayKey, null, configurator); + } + + /** + * @param displayKey Lang key for the variant display name + * @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, String group, Consumer configurator) { + this.displayKey = displayKey; + this.group = group; + this.configurator = configurator; + } + + public String getDisplayKey() { + return displayKey; + } + + public String getGroup() { + return group; + } + + /** + * Apply this variant's preset configuration to the given ability. + */ + public void apply(Ability ability) { + if (configurator != null) { + configurator.accept(ability); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java index 1c308493c..58e54b5aa 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java @@ -10,7 +10,8 @@ public enum AnchorPoint { RIGHT_HAND("Right Hand"), // Right arm/hand position LEFT_HAND("Left Hand"), // Left arm/hand position ABOVE_HEAD("Above Head"), // Above the entity - CHEST("Chest"); // Chest level, centered + CHEST("Chest"), // Chest level, centered + EYE("Eye"); // Eye level, centered private final String displayName; @@ -55,6 +56,7 @@ public enum AnchorPoint { case LEFT_HAND: return "ability.anchor.leftHand"; case ABOVE_HEAD: return "ability.anchor.aboveHead"; case CHEST: return "ability.anchor.chest"; + case EYE: return "ability.anchor.eye"; default: return name(); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java index 904fad0b9..36344e9e5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java @@ -21,7 +21,13 @@ public abstract class BuiltInAbility extends Ability { this.registryKey = registryKey; this.id = registryKey; this.name = registryKey; - this.typeId = registryKey; + // Convert "namespace:name" to "ability.namespace.name" for GUI filter compatibility + this.typeId = "ability." + registryKey.replace(':', '.'); + } + + @Override + public boolean isBuiltIn() { + return true; } /** diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java deleted file mode 100644 index 9a7f353c1..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package kamkeel.npcs.controllers.data.ability; - -import net.minecraft.entity.EntityLivingBase; - -/** - * External damage handler for abilities. - * When registered, called AFTER script events but BEFORE default attackEntityFrom. - * If handleDamage returns true, default damage is skipped. - */ -public interface IAbilityDamageHandler { - /** - * Handle damage from an ability. - * - * @param ability The ability dealing damage - * @param caster The entity executing the ability - * @param target The entity being hit - * @param damage The damage amount (after script event modifications) - * @param knockback The horizontal knockback - * @param knockbackUp The vertical knockback - * @param knockbackDirX The X component of knockback direction - * @param knockbackDirZ The Z component of knockback direction - * @return true if damage was handled (skip default), false to use default damage - */ - boolean handleDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, - float damage, float knockback, float knockbackUp, - double knockbackDirX, double knockbackDirZ); -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java new file mode 100644 index 000000000..e3e7e5c0b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityExtender.java @@ -0,0 +1,76 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; + +/** + * General-purpose extension point for abilities. Multiple extenders can be registered. + * Covers lifecycle hooks (start/tick/complete) and damage handling. + *

+ * All methods have no-op defaults so extenders only override what they need. + */ +public interface IAbilityExtender { + + /** + * Called before an ability starts executing. + * Return false to cancel the ability (e.g., insufficient resources). + * + * @param ability The ability about to start + * @param caster The entity executing the ability (NPC or Player) + * @param target The target entity (may be null for player self-cast) + * @return true to allow, false to cancel + */ + default boolean onAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) { + return true; + } + + /** + * Called each tick during ability execution. + * Return false to interrupt the ability (e.g., resource depleted). + * + * @param ability The executing ability + * @param caster The entity executing the ability + * @param target The target entity (may be null) + * @param phase The current ability phase (WINDUP, ACTIVE, DAZED, BURST_DELAY) + * @param tick The current tick within the phase + * @return true to continue, false to interrupt + */ + default boolean onAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target, + AbilityPhase phase, int tick) { + return true; + } + + /** + * Called when an ability completes (normally or via interruption). + * + * @param ability The completed ability + * @param caster The entity that was executing the ability + * @param target The target entity (may be null) + * @param interrupted true if the ability was interrupted, false if it completed normally + */ + default void onAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target, + boolean interrupted) { + } + + /** + * Called when an ability deals damage, AFTER script events but BEFORE default attackEntityFrom. + * Return true to handle the damage (skips default damage application). + *

+ * Chain of responsibility: extenders are called in registration order. + * The first extender returning true claims the damage; remaining extenders are skipped. + * + * @param ability The ability dealing damage + * @param caster The entity executing the ability + * @param target The entity being hit + * @param damage The damage amount (after script event modifications) + * @param knockback The horizontal knockback + * @param knockbackUp The vertical knockback + * @param knockbackDirX The X component of knockback direction + * @param knockbackDirZ The Z component of knockback direction + * @return true if damage was handled (skip default), false to pass to next extender or default + */ + default boolean onAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ) { + return false; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java new file mode 100644 index 000000000..77fae9774 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java @@ -0,0 +1,13 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.Entity; + +/** + * Interface for routing entity spawn/kill calls during preview mode. + * In preview mode, entities are not added to the world but instead + * tracked by the GUI for rendering in the 3D viewport. + */ +public interface PreviewEntityHandler { + void onEntitySpawned(Entity entity); + void onEntityRemoved(Entity entity); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java new file mode 100644 index 000000000..e1142b571 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java @@ -0,0 +1,53 @@ +package kamkeel.npcs.controllers.data.ability; + +/** + * Defines what happens to NPC rotation during ability phases. + * Used with a LockMovementType to control WHEN it applies. + */ +public enum RotationMode { + /** + * NPC rotates normally via AI look helper. + */ + FREE, + + /** + * Freeze rotation at the moment the phase starts. + * NPC stays facing the direction it was looking when the phase began. + */ + LOCKED, + + /** + * Force NPC to continuously face its target (hit scan). + * Overrides AI look helper every tick for precise aiming. + */ + TRACK; + + public String getDisplayKey() { + switch (this) { + case FREE: + return "ability.rotation.free"; + case LOCKED: + return "ability.rotation.locked"; + case TRACK: + return "ability.rotation.track"; + default: + return "ability.rotation.free"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.rotation.free", + "ability.rotation.locked", + "ability.rotation.track" + }; + } + + public static RotationMode fromOrdinal(int ordinal) { + RotationMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return FREE; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java index 2187802a5..99c51b23c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java @@ -91,10 +91,10 @@ public class EnergyAnchorData implements IEnergyAnchorData { } public void readNBT(NBTTagCompound nbt) { - this.anchorPoint = nbt.hasKey("anchorPoint") ? AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")) : AnchorPoint.FRONT; - this.anchorOffsetX = nbt.hasKey("anchorOffsetX") ? nbt.getFloat("anchorOffsetX") : 0; - this.anchorOffsetY = nbt.hasKey("anchorOffsetY") ? nbt.getFloat("anchorOffsetY") : 0; - this.anchorOffsetZ = nbt.hasKey("anchorOffsetZ") ? nbt.getFloat("anchorOffsetZ") : 0; + this.anchorPoint = AnchorPoint.fromOrdinal(nbt.getInteger("anchorPoint")); + this.anchorOffsetX = nbt.getFloat("anchorOffsetX"); + this.anchorOffsetY = nbt.getFloat("anchorOffsetY"); + this.anchorOffsetZ = nbt.getFloat("anchorOffsetZ"); } public EnergyAnchorData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java index 52f5368f0..e6ccf15a1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java @@ -97,12 +97,12 @@ public class EnergyCombatData implements IEnergyCombatData { } public void readNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.0f; - knockbackUp = nbt.hasKey("knockbackUp") ? nbt.getFloat("knockbackUp") : 0.1f; - explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 3.0f; - explosionDamageFalloff = nbt.hasKey("explosionDamageFalloff") ? nbt.getFloat("explosionDamageFalloff") : 0.5f; + damage = nbt.getFloat("damage"); + knockback = nbt.getFloat("knockback"); + knockbackUp = nbt.getFloat("knockbackUp"); + explosive = nbt.getBoolean("explosive"); + explosionRadius = nbt.getFloat("explosionRadius"); + explosionDamageFalloff = nbt.getFloat("explosionDamageFalloff"); } public EnergyCombatData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java index 0d91e1012..559be77f4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java @@ -102,12 +102,12 @@ public class EnergyDisplayData implements IEnergyDisplayData { } public void readNBT(NBTTagCompound nbt) { - innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; - outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); - outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; - outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; - rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; + innerColor = nbt.getInteger("innerColor"); + outerColor = nbt.getInteger("outerColor"); + outerColorEnabled = nbt.getBoolean("outerColorEnabled"); + outerColorWidth = nbt.getFloat("outerColorWidth"); + outerColorAlpha = nbt.getFloat("outerColorAlpha"); + rotationSpeed = nbt.getFloat("rotationSpeed"); } public EnergyDisplayData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java index 1e81882c7..d385c06e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java @@ -71,10 +71,10 @@ public class EnergyHomingData implements IEnergyHomingData { } public void readNBT(NBTTagCompound nbt) { - speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 0.5f; - homing = !nbt.hasKey("homing") || nbt.getBoolean("homing"); - homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.15f; - homingRange = nbt.hasKey("homingRange") ? nbt.getFloat("homingRange") : 20.0f; + speed = nbt.getFloat("speed"); + homing = nbt.getBoolean("homing"); + homingStrength = nbt.getFloat("homingStrength"); + homingRange = nbt.getFloat("homingRange"); } public EnergyHomingData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java index 9e017e2a5..f320acdb0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java @@ -44,8 +44,8 @@ public class EnergyLifespanData implements IEnergyLifespanData { } public void readNBT(NBTTagCompound nbt) { - maxDistance = nbt.hasKey("maxDistance") ? nbt.getFloat("maxDistance") : 30.0f; - maxLifetime = nbt.hasKey("maxLifetime") ? nbt.getInteger("maxLifetime") : 200; + maxDistance = nbt.getFloat("maxDistance"); + maxLifetime = nbt.getInteger("maxLifetime"); } public EnergyLifespanData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java index 00d0eaa96..66786a14a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java @@ -71,10 +71,10 @@ public class EnergyLightningData implements IEnergyLightningData { } public void readNBT(NBTTagCompound nbt) { - lightningEffect = nbt.hasKey("lightningEffect") && nbt.getBoolean("lightningEffect"); - lightningDensity = nbt.hasKey("lightningDensity") ? nbt.getFloat("lightningDensity") : 0.15f; - lightningRadius = nbt.hasKey("lightningRadius") ? nbt.getFloat("lightningRadius") : 0.5f; - lightningFadeTime = nbt.hasKey("lightningFadeTime") ? nbt.getInteger("lightningFadeTime") : 6; + lightningEffect = nbt.getBoolean("lightningEffect"); + lightningDensity = nbt.getFloat("lightningDensity"); + lightningRadius = nbt.getFloat("lightningRadius"); + lightningFadeTime = nbt.getInteger("lightningFadeTime"); } public EnergyLightningData copy() { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java index 7cc15a706..15adb3062 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java @@ -184,7 +184,7 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0; + this.currentPath = nbt.getInteger("currentPath"); int i = 0; while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { @@ -275,8 +275,8 @@ public class EnergyTrajectoryData implements IEnergyTrajectoryData { } public void readNBT(NBTTagCompound nbt) { - this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0; - this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded"); + this.delayTicks = nbt.getInteger("delay"); + this.concluded = nbt.getBoolean("concluded"); double x = nbt.getDouble("X"); double y = nbt.getDouble("Y"); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java new file mode 100644 index 000000000..94850470f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -0,0 +1,60 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Per-projectile data: anchor point + optional color override. + * All projectiles share the primary EnergyDisplayData; this class + * allows individual projectiles to override just the inner/outer colors. + */ +public class ProjectileData { + public EnergyAnchorData anchor; + public boolean colorOverride = false; + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + + public ProjectileData(AnchorPoint defaultAnchor) { + this.anchor = new EnergyAnchorData(defaultAnchor); + } + + /** + * Returns the display data to use for this projectile. + * If colorOverride is false, returns the primary display data directly. + * If colorOverride is true, returns a copy with overridden inner/outer colors. + */ + public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) { + if (!colorOverride) return primary; + EnergyDisplayData resolved = primary.copy(); + resolved.innerColor = this.innerColor; + resolved.outerColor = this.outerColor; + return resolved; + } + + public void writeNBT(NBTTagCompound nbt) { + anchor.writeNBT(nbt); + nbt.setBoolean("colorOverride", colorOverride); + if (colorOverride) { + nbt.setInteger("overrideInnerColor", innerColor); + nbt.setInteger("overrideOuterColor", outerColor); + } + } + + public void readNBT(NBTTagCompound nbt) { + anchor.readNBT(nbt); + colorOverride = nbt.getBoolean("colorOverride"); + if (colorOverride) { + innerColor = nbt.getInteger("overrideInnerColor"); + outerColor = nbt.getInteger("overrideOuterColor"); + } + } + + public ProjectileData copy() { + ProjectileData copy = new ProjectileData(anchor.anchorPoint); + copy.anchor = anchor.copy(); + copy.colorOverride = colorOverride; + copy.innerColor = innerColor; + copy.outerColor = outerColor; + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java index 5edd0a718..219479614 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java @@ -12,6 +12,7 @@ import noppes.npcs.client.gui.util.GuiNPCInterface; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.constants.EnumPotionType; import java.util.ArrayList; import java.util.HashMap; @@ -26,7 +27,7 @@ import java.util.Map; public class AbilityFieldBuilder extends GuiFieldBuilder { // Effects list metadata: widgetId -> [effectIndex, action] - // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add + // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add, 5=manualId(text) private final Map effectWidgetMeta = new HashMap<>(); public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { @@ -57,15 +58,15 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { List effects = (List) def.getValue(); if (effects == null) effects = new ArrayList<>(); - String[] typeNames = AbilityEffect.EffectType.getLangKeys(); + String[] typeNames = EnumPotionType.getLangKeysNoNone(); String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; for (int e = 0; e < effects.size() && e < 5; e++) { AbilityEffect effect = effects.get(e); - // Type selector button - int typeIdx = effect.getType().ordinal(); - GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx); + // Type selector button (index offset by -1 since None is excluded) + int typeIdx = effect.getType().ordinal() - 1; + GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, Math.max(0, typeIdx)); sw.addButton(typeBtn); buttonFieldMap.put(widgetId, def); effectWidgetMeta.put(widgetId, new int[]{e, 0}); @@ -81,12 +82,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { effectWidgetMeta.put(widgetId, new int[]{e, 1}); widgetId++; - // Amplifier selector (0-10) - GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); - sw.addButton(ampBtn); - buttonFieldMap.put(widgetId, def); - effectWidgetMeta.put(widgetId, new int[]{e, 2}); - widgetId++; + if (effect.getType() != EnumPotionType.Fire) { + // Amplifier selector (0-10) — not applicable to Fire + GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); + sw.addButton(ampBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + } else { + widgetId++; // keep widgetId in sync + } // Delete button GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); @@ -96,6 +101,20 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { clearId++; y += rowHeight; + + // Manual potion ID field (shown on next row when type is Manual) + if (effect.getType() == EnumPotionType.Manual) { + sw.addLabel(new GuiNpcLabel(labelId++, "effect.potionid", colLLabel, y + 5, 0xFFFFFF)); + GuiNpcTextField idField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 80, y, 50, 20, String.valueOf(effect.getManualPotionId())); + idField.setIntegersOnly(); + idField.setMinMaxDefault(0, Integer.MAX_VALUE, 0); + sw.addTextField(idField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 5}); + widgetId++; + y += rowHeight; + } } // Add button (if < 5 effects) @@ -133,7 +152,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { switch (action) { case 0: // Type changed if (effectIdx < effects.size()) { - effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue())); + effects.get(effectIdx).setType(EnumPotionType.fromIndexNoNone(((GuiNpcButton) button).getValue())); } return true; case 2: // Amp changed @@ -148,7 +167,7 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { return true; case 4: // Add if (effects.size() < 5) { - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); + effects.add(new AbilityEffect(EnumPotionType.Slowness, 60, 0)); } return true; } @@ -162,12 +181,16 @@ public class AbilityFieldBuilder extends GuiFieldBuilder { @SuppressWarnings("unchecked") public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { int[] meta = effectWidgetMeta.get(textFieldId); - if (meta != null && meta[1] == 1) { // duration field + if (meta != null) { FieldDef def = textFieldMap.get(textFieldId); if (def != null && def.getType() == FieldType.EFFECTS_LIST) { List effects = (List) def.getValue(); if (effects != null && meta[0] < effects.size()) { - effects.get(meta[0]).setDurationTicks(field.getInteger()); + if (meta[1] == 1) { // duration field + effects.get(meta[0]).setDurationTicks(field.getInteger()); + } else if (meta[1] == 5) { // manual potion ID field + effects.get(meta[0]).setManualPotionId(field.getInteger()); + } } return true; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java index bc1dc9ab8..6e419b943 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java @@ -23,4 +23,5 @@ public class AbilityFieldDefs { () -> getter.get(), v -> setter.accept((List) v)); } + } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java index 5157eea01..45772eedb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -2,53 +2,41 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityEnergyBeam; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** * Energy Beam ability: A homing head with a trailing path. - * The beam stays attached to the origin and curves as it homes in on target. - * Cannot cross over itself (self-intersection prevention). + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ -public class AbilityBeam extends Ability implements IAbilityEnergyBeam { +public class AbilityBeam extends AbstractEnergyProjectileAbility implements IAbilityEnergyBeam { - // Shape properties (standalone) private float beamWidth = 0.4f; private float headSize = 0.6f; - // Data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); - private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for beam entity (used during windup charging) - private transient EntityAbilityBeam beamEntity = null; - public AbilityBeam() { + super( + new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f), + new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f), + new EnergyHomingData(0.4f, true, 0.1f, 15.0f), + new EnergyLifespanData(25.0f, 200) + ); this.typeId = "ability.cnpc.beam"; this.name = "Beam"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -57,291 +45,143 @@ public class AbilityBeam extends Ability implements IAbilityEnergyBeam { this.cooldownTicks = 0; this.windUpTicks = 40; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Beam_Windup"; this.activeAnimationName = "Ability_Beam_Active"; } + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + @Override - public boolean isTargetingModeLocked() { - return true; + protected EntityAbilityBeam createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityBeam( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + beamWidth, headSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + lockMovement.locksActive()); } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start firing the beam that was spawned during windup - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.startFiring(target); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn beam in charging mode on first tick of windup - if (tick == 1) { - float offsetDist = 1.0f; - - // Create beam in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData, offsetDist); - beamEntity = new EntityAbilityBeam( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - beamWidth, headSize, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, - lockMovement.locksActive()); - beamEntity.setupCharging(anchorData, windUpTicks, offsetDist); - - beamEntity.setEffects(this.effects); - beamEntity.setSourceAbility(this); - world.spawnEntityInWorld(beamEntity); + protected void fireEntity(EntityAbilityBeam beam, EntityLivingBase target) { + if (isPreview()) { + beam.startPreviewFiring(); + } else { + beam.startFiring(target); } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (beamEntity == null || beamEntity.isDead) { - beamEntity = null; - signalCompletion(); - } + protected void setupEntityCharging(EntityAbilityBeam beam, ProjectileData projData, int index) { + beam.setupCharging(projData.anchor, windUpTicks, 1.0f); } @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + protected void setupEntityPreview(EntityAbilityBeam beam, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + beam.setupPreview(caster, beamWidth, headSize, resolved, lightningData, projData.anchor, windUpTicks, 1.0f); } @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); + protected EntityAbilityBeam[] createEntityArray(int size) { + return new EntityAbilityBeam[size]; } @Override - public void cleanup() { - // Despawn beam entity if still alive - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.setDead(); - } - beamEntity = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(headSize * 2.0f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { + protected float getProjectileTelegraphRadius() { return headSize * 2.0f; } @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected Vec3 getSpawnPosition(EntityLivingBase caster, int index) { + return AnchorPointHelper.calculateAnchorPosition(caster, projectiles[index].anchor, 1.0f); + } + + // ==================== VARIANTS ==================== + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Beam"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityBeam beam = (AbilityBeam) a; + a.setName("Dual Beam"); + beam.setProjectileCount(2); + beam.setFireDelay(0); + beam.projectiles[1].colorOverride = true; + beam.projectiles[1].innerColor = 0xFFFFFF; + beam.projectiles[1].outerColor = 0xFF0000; + a.setWindUpTicks(80); + a.setWindUpAnimationName("Ability_BeamDual_Windup"); + a.setActiveAnimationName("Ability_BeamDual_Active"); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("beamWidth", beamWidth); nbt.setFloat("headSize", headSize); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.beamWidth = nbt.getFloat("beamWidth"); + this.headSize = nbt.getFloat("headSize"); } - // Getters & Setters - Standalone fields + // ==================== TYPE-SPECIFIC GETTERS ==================== + + public float getSpeed() { return homingData.speed; } + public void setSpeed(float speed) { homingData.speed = speed; } + public float getBeamWidth() { return beamWidth; } public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } + public float getHeadSize() { return headSize; } public void setHeadSize(float headSize) { this.headSize = headSize; } - // Getters & Setters - Color data - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { this.colorData.rotationSpeed = rotationSpeed; } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Getters & Setters - Homing data - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Anchor point - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - - @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } - - @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj); - beam.setupPreview(npc, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, 1.0f); - return beam; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), - FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.row( - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange) - .visibleWhen(this::isHoming) - ), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + protected void addTypeDefinitions(List defs) { + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), + FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), + FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange).visibleWhen(this::isHoming) + )); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java deleted file mode 100644 index 762145fc4..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeamDual.java +++ /dev/null @@ -1,517 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBeam; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityBeamDual extends Ability { - private float beamWidth = 0.4f; - private float headSize = 0.6f; - private boolean dualFire= true; - private int dualFireDelay = 0; - - // Data classes - private final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f), - new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 6.0f), - }; - private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private final EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for beam entity (used during windup charging) - private transient EntityAbilityBeam beamEntity = null; - private transient EntityAbilityBeam beamEntity2 = null; - - public AbilityBeamDual() { - this.typeId = "ability.cnpc.beam_dual"; - this.name = "Beam Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 20.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 80; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animations - this.windUpAnimationName = "Ability_BeamDual_Windup"; - this.activeAnimationName = "Ability_BeamDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start firing the beam that was spawned during windup - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.startFiring(target); - } - - if (dualFire) { - if (beamEntity2 != null && !beamEntity2.isDead && dualFireDelay <= 0) { - beamEntity2.startFiring(target); - } - } else if (beamEntity2 != null) { - beamEntity2.setDead(); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn beam in charging mode on first tick of windup - if (tick == 1) { - float offsetDist = 1.0f; - - // Create beam in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0], offsetDist); - beamEntity = new EntityAbilityBeam( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, - beamWidth, headSize, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0], - lockMovement.locksActive()); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1], offsetDist); - beamEntity2 = new EntityAbilityBeam( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, - beamWidth, headSize, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1], - lockMovement.locksActive()); - - beamEntity.setSiblingEntityId(beamEntity2.getEntityId()); - beamEntity2.setSiblingEntityId(beamEntity.getEntityId()); - - beamEntity.setupCharging(anchorData[0], windUpTicks, offsetDist); - beamEntity2.setupCharging(anchorData[1], windUpTicks, offsetDist); - - beamEntity.setEffects(this.effects); - if (dualFire) beamEntity2.setEffects(this.effects); - - beamEntity.setSourceAbility(this); - beamEntity2.setSourceAbility(this); - world.spawnEntityInWorld(beamEntity); - world.spawnEntityInWorld(beamEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((beamEntity == null || beamEntity.isDead) && (beamEntity2 == null || beamEntity2.isDead)) { - beamEntity = null; - beamEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && beamEntity2 != null && !beamEntity2.isDead) { - beamEntity2.startFiring(target); - } - } else { - if (beamEntity == null || beamEntity.isDead) { - beamEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn beam entity if still alive - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.setDead(); - } - - if (beamEntity2 != null && !beamEntity2.isDead) { - beamEntity2.setDead(); - } - - beamEntity = null; - beamEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(headSize * 2.0f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return headSize * 2.0f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("beamWidth", beamWidth); - nbt.setFloat("headSize", headSize); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - NBTTagCompound beam1 = new NBTTagCompound(); - NBTTagCompound beam2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound beam = i == 0 ? beam1 : beam2; - anchorData[i].writeNBT(beam); - displayData[i].writeNBT(beam); - lightningData[i].writeNBT(beam); - trajectoryData[i].writeNBT(beam); - } - - nbt.setTag("Beam_1", beam1); - nbt.setTag("Beam_2", beam2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound beam1 = nbt.hasKey("Beam_1") ? nbt.getCompoundTag("Beam_1") : new NBTTagCompound(); - NBTTagCompound beam2 = nbt.hasKey("Beam_2") ? nbt.getCompoundTag("Beam_2") : new NBTTagCompound(); - - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - for (int i = 0; i < 2; i++) { - NBTTagCompound beam = i == 0 ? beam1 : beam2; - anchorData[i].readNBT(beam); - displayData[i].readNBT(beam); - lightningData[i].readNBT(beam); - trajectoryData[i].readNBT(beam); - } - } - - // Getters & Setters - Standalone fields - public float getBeamWidth() { return beamWidth; } - public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } - public float getHeadSize() { return headSize; } - public void setHeadSize(float headSize) { this.headSize = headSize; } - public boolean isDualFire() { return dualFire; } - public void setDualFire(boolean dualFire) { this.dualFire = dualFire; } - public int getDualFireDelay() { return dualFireDelay; } - public void setDualFireDelay(int dualFireDelay) { this.dualFireDelay = dualFireDelay; } - - private EnergyDisplayData getColorData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return displayData[beam]; - } - private EnergyLightningData getLightningData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return lightningData[beam]; - } - private EnergyAnchorData getAnchorData(int beam) { - beam = ValueUtil.clamp(beam, 0, 1); - return anchorData[beam]; - } - - // Getters & Setters - Color data - public int getInnerColor(int beam) { return getColorData(beam).innerColor; } - public void setInnerColor(int beam, int innerColor) { getColorData(beam).innerColor = innerColor; } - public int getOuterColor(int beam) { return getColorData(beam).outerColor; } - public void setOuterColor(int beam, int outerColor) { getColorData(beam).outerColor = outerColor; } - public boolean isOuterColorEnabled(int beam) { return getColorData(beam).outerColorEnabled; } - public void setOuterColorEnabled(int beam, boolean enabled) { getColorData(beam).outerColorEnabled = enabled; } - public float getOuterColorWidth(int beam) { return getColorData(beam).outerColorWidth; } - public void setOuterColorWidth(int beam, float width) { getColorData(beam).outerColorWidth = width; } - public float getOuterColorAlpha(int beam) { return getColorData(beam).outerColorAlpha; } - public void setOuterColorAlpha(int beam, float alpha) { getColorData(beam).outerColorAlpha = alpha; } - public float getRotationSpeed(int beam) { return getColorData(beam).rotationSpeed; } - public void setRotationSpeed(int beam, float speed) { getColorData(beam).rotationSpeed = speed; } - - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Getters & Setters - Homing data - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect(int beam) { return getLightningData(beam).lightningEffect; } - public void setLightningEffect(int beam, boolean lightningEffect) { getLightningData(beam).lightningEffect = lightningEffect; } - public float getLightningDensity(int beam) { return getLightningData(beam).lightningDensity; } - public void setLightningDensity(int beam, float lightningDensity) { getLightningData(beam).lightningDensity = lightningDensity; } - public float getLightningRadius(int beam) { return getLightningData(beam).lightningRadius; } - public void setLightningRadius(int beam, float lightningRadius) { getLightningData(beam).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Anchor point - public AnchorPoint getAnchorPointEnum(int beam) { return getAnchorData(beam).anchorPoint; } - public void setAnchorPointEnum(int beam, AnchorPoint anchorPoint) { getAnchorData(beam).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int beam) { return getAnchorData(beam).anchorOffsetX; } - public void setAnchorOffsetX(int beam, float x) { getAnchorData(beam).anchorOffsetX = x; } - public float getAnchorOffsetY(int beam) { return getAnchorData(beam).anchorOffsetY; } - public void setAnchorOffsetY(int beam, float y) { getAnchorData(beam).anchorOffsetY = y; } - public float getAnchorOffsetZ(int beam) { return getAnchorData(beam).anchorOffsetZ; } - public void setAnchorOffsetZ(int beam, float z) { getAnchorData(beam).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int beam) { return getAnchorData(beam).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int beam, int point) { getAnchorData(beam).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), - FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.row( - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange) - .visibleWhen(this::isHoming) - ), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Beam 1 - FieldDef.section("ability.section.beam1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Beam 2 - FieldDef.section("ability.section.beam2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj); - beam.setupPreview(npc, beamWidth, headSize, displayData[0], lightningData[0], anchorData[0], windUpTicks, 1.0f); - return beam; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index e09ff7e11..780ddc050 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -2,7 +2,6 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.Telegraph; @@ -12,9 +11,6 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; @@ -26,9 +22,10 @@ import java.util.List; import java.util.Set; /** - * Charge ability: Rush attack where NPC charges in a line, damaging all targets hit. + * Charge ability: Rush attack where the caster charges in a line, damaging all targets hit. + * Extends AbilityMovement for shared direction locking, stall detection, and velocity application. */ -public class AbilityCharge extends Ability implements IAbilityCharge { +public class AbilityCharge extends AbilityMovement implements IAbilityCharge { // Type-specific parameters private float chargeSpeed = 0.8f; @@ -36,11 +33,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { private float knockback = 3.0f; private float hitWidth = 1.5f; - // Runtime state (transient) - private transient double startX, startY, startZ; - private transient Vec3 chargeDirection; + // Type-specific runtime state private transient Set hitEntities = new HashSet<>(); - private transient float lockedYaw; public AbilityCharge() { this.typeId = "ability.cnpc.charge"; @@ -56,6 +50,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { this.showTelegraph = true; this.windUpSound = "mob.zombie.wood"; this.activeSound = "mob.zombie.attack"; + this.windUpAnimationName = "Ability_Charge_Windup"; + this.activeAnimationName = "Ability_Active_Windup"; } @Override @@ -68,111 +64,75 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public boolean hasAbilityMovement() { - return true; // This ability moves the NPC - } - /** * Called on the first tick of windup - lock direction here so it matches telegraph. */ @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (tick == 1) { - // Lock direction on first windup tick (same time telegraph is created) - lockChargeDirection(caster, target); + lockDirection(caster, target); } - // Keep caster facing the locked direction during windup enforceLockedRotation(caster); } - /** - * Locks the charge direction based on current target position. - * Called once at windup start - direction won't change even if target moves. - */ - private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) { - if (target != null) { - double dx = target.posX - caster.posX; - double dz = target.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - chargeDirection = Vec3.createVectorHelper(dx / len, 0, dz / len); - } else { - float yaw = (float) Math.toRadians(caster.rotationYaw); - chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); - } - } else { - float yaw = (float) Math.toRadians(caster.rotationYaw); - chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); - } - lockedYaw = (float) Math.toDegrees(Math.atan2(-chargeDirection.xCoord, chargeDirection.zCoord)); - } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Initialize charge - direction was already locked during windup - startX = caster.posX; - startY = caster.posY; - startZ = caster.posZ; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + initMovement(caster, maxRange, chargeSpeed); hitEntities.clear(); // If direction wasn't set during windup (shouldn't happen), set it now - if (chargeDirection == null) { - lockChargeDirection(caster, target); + if (movementDirection == null) { + lockDirection(caster, target); } enforceLockedRotation(caster); } - private void enforceLockedRotation(EntityLivingBase caster) { - caster.rotationYaw = lockedYaw; - caster.rotationYawHead = lockedYaw; - caster.prevRotationYaw = lockedYaw; - caster.prevRotationYawHead = lockedYaw; - caster.renderYawOffset = lockedYaw; - caster.prevRenderYawOffset = lockedYaw; - } - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (chargeDirection == null) return; - - // Enforce rotation every tick - enforceLockedRotation(caster); - - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); - - // Check if reached max distance - if (distanceTraveled >= maxRange) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; - signalCompletion(); - return; - } - - if (isChargeBlocked(caster)) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (checkTimeout(tick)) { stopMomentum(caster); signalCompletion(); return; } - // Move caster - caster.motionX = chargeDirection.xCoord * chargeSpeed; - caster.motionY = 0; - caster.motionZ = chargeDirection.zCoord * chargeSpeed; - caster.velocityChanged = true; + if (movementDirection == null) { + signalCompletion(); + return; + } - // Server-side collision damage - if (!world.isRemote) { + if (!isPreview()) { + enforceLockedRotation(caster); + } + + if (checkStall(caster, tick)) { + stopMomentum(caster); + signalCompletion(); + return; + } + updatePrevPosition(caster); + + if (getDistanceTraveled(caster) >= maxRange) { + stopMomentum(caster); + signalCompletion(); + return; + } + + if (checkBlocked(caster, chargeSpeed)) { + stopMomentum(caster); + signalCompletion(); + return; + } + + // Move caster (flat: zero vertical motion) + applyVelocityFlat(caster, chargeSpeed); + + // Server-side collision damage (skip in preview) + if (!caster.worldObj.isRemote && !isPreview()) { AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth); @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, hitBox); for (Entity entity : entities) { if (!(entity instanceof EntityLivingBase)) continue; @@ -181,16 +141,14 @@ public class AbilityCharge extends Ability implements IAbilityCharge { EntityLivingBase livingEntity = (EntityLivingBase) entity; - // Hit this entity hitEntities.add(entity.getEntityId()); - // Apply damage with scripted event support boolean wasHit = applyAbilityDamageWithDirection(caster, livingEntity, damage, knockback, - chargeDirection.xCoord, chargeDirection.zCoord); + movementDirection.xCoord, movementDirection.zCoord); - // Play impact sound if hit wasn't cancelled if (wasHit) { - world.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); + applyEffects(livingEntity); + caster.worldObj.playSoundAtEntity(livingEntity, "random.explode", 0.5f, 1.2f); } } } @@ -208,23 +166,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { super.onInterrupt(caster, source, damage); } - private void stopMomentum(EntityLivingBase caster) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; - } - - private boolean isChargeBlocked(EntityLivingBase caster) { - double nextX = chargeDirection.xCoord * chargeSpeed; - double nextZ = chargeDirection.zCoord * chargeSpeed; - AxisAlignedBB nextBox = caster.boundingBox.copy().offset(nextX, 0, nextZ); - return !caster.worldObj.getCollidingBoundingBoxes(caster, nextBox).isEmpty(); - } - @Override - public void reset() { - super.reset(); - chargeDirection = null; + public void cleanup() { + super.cleanup(); hitEntities.clear(); } @@ -249,9 +193,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return null; } - // Calculate direction to target at this moment (locked) + // NPC: telegraph points toward aggro target + // Player: telegraph points in look direction float yaw; - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); @@ -277,66 +222,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return instance; } - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewCharging = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewCharging = false; - - // Calculate direction toward fake target - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - previewDirX = dx / len; - previewDirZ = dz / len; - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - previewCharging = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewCharging) return; - - // Check distance traveled - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= maxRange) { - previewCharging = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * chargeSpeed; - npc.posZ += previewDirZ * chargeSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(maxRange / chargeSpeed) + 5; } @@ -350,16 +237,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.chargeSpeed = nbt.hasKey("chargeSpeed") ? nbt.getFloat("chargeSpeed") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 3.0f; - if (nbt.hasKey("hitWidth")) { - this.hitWidth = nbt.getFloat("hitWidth"); - } else if (nbt.hasKey("hitRadius")) { - this.hitWidth = nbt.getFloat("hitRadius"); - } else { - this.hitWidth = 1.5f; - } + this.chargeSpeed = nbt.getFloat("chargeSpeed"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitWidth = nbt.getFloat("hitWidth"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index 405dac612..58c92009f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -3,6 +3,8 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -60,6 +62,8 @@ public class AbilityCutter extends Ability implements IAbilityCutter { // Runtime state private transient Set hitEntities = new HashSet<>(); private transient float currentRotation = 0.0f; + private transient boolean activeSoundPlayed = false; + private transient float sweepBaseYaw = 0.0f; public AbilityCutter() { this.typeId = "ability.cnpc.cutter"; @@ -86,6 +90,54 @@ public class AbilityCutter extends Ability implements IAbilityCutter { return new TargetingMode[]{TargetingMode.AOE_SELF}; } + /** + * Calculate how many ticks the active sweep phase takes. + * SWIPE: arcAngle / sweepSpeed ticks + * SPIN: spinDurationTicks + */ + private int getActiveDurationTicks() { + if (sweepMode == SweepMode.SPIN) { + return spinDurationTicks; + } + return sweepSpeed > 0 ? (int) Math.ceil(arcAngle / sweepSpeed) : 1; + } + + @Override + public boolean keepTelegraphDuringActive() { + return true; + } + + /** + * Creates a CONE telegraph that lasts through both windup and active sweep phases. + * Warning color transitions when the sweep actually begins (at windUpTicks). + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) { + return null; + } + + Telegraph telegraph = Telegraph.cone(getTelegraphLength(), getTelegraphAngle()); + int totalDuration = windUpTicks + getActiveDurationTicks(); + telegraph.setDurationTicks(totalDuration); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + // Warning transition starts when the sweep begins (active phase) + telegraph.setWarningStartTick(windUpTicks); + telegraph.setHeightOffset(telegraphHeightOffset); + + double groundY = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ); + TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, groundY, caster.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(caster.getEntityId()); + + if (target != null && !isRotationLockedDuringWindup()) { + instance.setTargetEntityId(target.getEntityId()); + } + + return instance; + } + @Override public float getTelegraphRadius() { return range; @@ -102,42 +154,79 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { hitEntities.clear(); currentRotation = -arcAngle / 2.0f; + activeSoundPlayed = false; + + // Lock sweep direction toward target at execute time to prevent + // AI look-at jitter from misdirecting the sweep at close range + if (target != null) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + if (dx * dx + dz * dz > 0.0001) { + sweepBaseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); + } else { + sweepBaseYaw = caster.rotationYaw; + } + } else { + sweepBaseYaw = caster.rotationYaw; + } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (caster.worldObj.isRemote && !isPreview()) return; switch (sweepMode) { case SWIPE: float prevRotation = currentRotation; currentRotation += sweepSpeed; + + // Play active sound when sweep reaches center (where target typically stands) + if (!activeSoundPlayed && currentRotation >= 0) { + playActiveSound(caster, caster.worldObj); + } + if (currentRotation > arcAngle / 2.0f) { - // Final sweep — check from prevRotation to end of arc - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + if (!isPreview()) { + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, arcAngle / 2.0f); + } signalCompletion(); return; } - // Check entities between previous and current sweep position - performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + if (!isPreview()) { + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevRotation, currentRotation); + } break; case SPIN: + // Play active sound at spin start + if (!activeSoundPlayed) { + playActiveSound(caster, caster.worldObj); + } + if (tick >= spinDurationTicks) { - signalCompletion(); // Spin duration complete + signalCompletion(); return; } float prevSpin = currentRotation; currentRotation = (currentRotation + sweepSpeed) % 360.0f; - hitEntities.clear(); - performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + if (!isPreview()) { + hitEntities.clear(); + performSweepDamageRange(caster, caster.worldObj, innerRadius, range, prevSpin, currentRotation); + } break; } } + private void playActiveSound(EntityLivingBase caster, World world) { + activeSoundPlayed = true; + if (activeSound != null && !activeSound.isEmpty()) { + world.playSoundAtEntity(caster, activeSound, 1.0f, 1.0f); + } + } + /** * Check for entities between two sweep angles, ensuring no gaps between ticks. * For SWIPE mode, this covers the continuous arc from startAngle to endAngle. @@ -167,7 +256,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { double dist = Math.sqrt(dx * dx + dz * dz); if (dist < minDist || dist > maxDist) continue; - if (!isInSweepRange(dx, dz, caster.rotationYaw, minAngle, maxAngle)) continue; + if (!isInSweepRange(dx, dz, sweepBaseYaw, minAngle, maxAngle)) continue; hitEntities.add(entity.getEntityId()); @@ -210,12 +299,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { hitEntities.clear(); currentRotation = 0.0f; + activeSoundPlayed = false; + sweepBaseYaw = 0.0f; } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { hitEntities.clear(); currentRotation = 0.0f; + activeSoundPlayed = false; + sweepBaseYaw = 0.0f; } @Override @@ -233,19 +326,19 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.arcAngle = nbt.hasKey("arcAngle") ? nbt.getFloat("arcAngle") : 90.0f; - this.range = nbt.hasKey("range") ? nbt.getFloat("range") : 6.0f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 7.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; + this.arcAngle = nbt.getFloat("arcAngle"); + this.range = nbt.getFloat("range"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); try { this.sweepMode = SweepMode.valueOf(nbt.getString("sweepMode")); } catch (Exception e) { this.sweepMode = SweepMode.SWIPE; } - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 6.0f; - this.spinDurationTicks = nbt.hasKey("spinDurationTicks") ? nbt.getInteger("spinDurationTicks") : 60; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.innerRadius = nbt.hasKey("innerRadius") ? nbt.getFloat("innerRadius") : 0.0f; + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.spinDurationTicks = nbt.getInteger("spinDurationTicks"); + this.piercing = nbt.getBoolean("piercing"); + this.innerRadius = nbt.getFloat("innerRadius"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index 1a1e76aa3..41c5faaa1 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -2,17 +2,12 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.api.ability.type.IAbilityDash; @@ -23,9 +18,9 @@ import java.util.Random; /** * Dash ability: Quick evasive sidestep with NO telegraph. - * Defensive repositioning move to evade attacks. + * Extends AbilityMovement for shared direction locking, stall detection, and velocity application. */ -public class AbilityDash extends Ability implements IAbilityDash { +public class AbilityDash extends AbilityMovement implements IAbilityDash { /** * Dash behavior mode. @@ -87,12 +82,9 @@ public class AbilityDash extends Ability implements IAbilityDash { // Type-specific parameters private DashMode dashMode = DashMode.DEFENSIVE; private float dashDistance = 4.0f; - private float dashSpeed = 1.5f; + private float dashSpeed = 0.5f; - // Runtime state - private transient Vec3 dashDirection; - private transient double startX, startY, startZ; - private transient double prevTickX, prevTickZ; + // Type-specific runtime state private transient DashDirection chosenDirection; public AbilityDash() { @@ -127,17 +119,8 @@ public class AbilityDash extends Ability implements IAbilityDash { } @Override - public boolean hasAbilityMovement() { - return true; // This ability moves the NPC - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - startX = caster.posX; - startY = caster.posY; - startZ = caster.posZ; - prevTickX = caster.posX; - prevTickZ = caster.posZ; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + initMovement(caster, dashDistance, dashSpeed); // Choose random direction based on mode DashDirection[] directions = dashMode == DashMode.AGGRESSIVE @@ -145,168 +128,74 @@ public class AbilityDash extends Ability implements IAbilityDash { : DEFENSIVE_DIRECTIONS; chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // Calculate dash direction relative to target - float baseYaw; - if (target != null) { - double dx = target.posX - caster.posX; - double dz = target.posZ - caster.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { - baseYaw = caster.rotationYaw; - } - - // Apply direction offset + // Calculate direction: base yaw (toward target or look dir) + direction offset + float baseYaw = getBaseYaw(caster, target); float dashYaw = baseYaw + chosenDirection.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - - dashDirection = Vec3.createVectorHelper( - -Math.sin(yawRad), - 0, - Math.cos(yawRad) - ); + setDirectionFromYaw(dashYaw); + // Small upward impulse for a skip/hop arc (gravity handles the descent) + caster.motionY = 0.2; } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (dashDirection == null) return; - - // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall - if (tick > 1) { - double movedThisTick = Math.sqrt( - Math.pow(caster.posX - prevTickX, 2) + - Math.pow(caster.posZ - prevTickZ, 2)); - if (movedThisTick < 0.01) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; - signalCompletion(); - return; - } - } - prevTickX = caster.posX; - prevTickZ = caster.posZ; - - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); - - // Check if reached max distance - if (distanceTraveled >= dashDistance) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (checkTimeout(tick)) { + stopMomentum(caster); signalCompletion(); return; } - if (isDashBlocked(caster)) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + if (movementDirection == null) { signalCompletion(); return; } - // Move caster - caster.motionX = dashDirection.xCoord * dashSpeed; - caster.motionY = 0; - caster.motionZ = dashDirection.zCoord * dashSpeed; - caster.velocityChanged = true; + if (checkStall(caster, tick)) { + stopMomentum(caster); + signalCompletion(); + return; + } + updatePrevPosition(caster); - // Trail particles - world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + if (getDistanceTraveledSq(caster) >= (double) dashDistance * dashDistance) { + stopMomentum(caster); + signalCompletion(); + return; + } + + if (checkBlocked(caster, dashSpeed)) { + stopMomentum(caster); + signalCompletion(); + return; + } + + // Move caster (motionY left to gravity for skip arc) + applyVelocity(caster, dashSpeed); + + if (!isPreview()) { + // Trail particles + caster.worldObj.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + stopMomentum(caster); } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + stopMomentum(caster); } @Override public void cleanup() { - dashDirection = null; + super.cleanup(); chosenDirection = null; } - private boolean isDashBlocked(EntityLivingBase caster) { - if (dashDirection == null) return true; - double nextX = dashDirection.xCoord * dashSpeed; - double nextZ = dashDirection.zCoord * dashSpeed; - return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty(); - } - - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewDashing = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewDashing = false; - - // Pick a random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - DashDirection dir = directions[RANDOM.nextInt(directions.length)]; - - float baseYaw; - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { - baseYaw = npc.rotationYaw; - } - - float dashYaw = baseYaw + dir.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - previewDirX = -Math.sin(yawRad); - previewDirZ = Math.cos(yawRad); - previewDashing = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewDashing) return; - - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= dashDistance) { - previewDashing = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * dashSpeed; - npc.posZ += previewDirZ * dashSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(dashDistance / dashSpeed) + 5; } @@ -329,8 +218,8 @@ public class AbilityDash extends Ability implements IAbilityDash { } catch (Exception e) { this.dashMode = DashMode.DEFENSIVE; } - this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 1.5f; + this.dashDistance = nbt.getFloat("dashDistance"); + this.dashSpeed = nbt.getFloat("dashSpeed"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 0f91869fa..5a542ce7d 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -2,56 +2,42 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityDisc; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** * Disc ability: Spawns a flat spinning disc projectile. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. * Has optional boomerang behavior to return to owner. */ -public class AbilityDisc extends Ability implements IAbilityDisc { +public class AbilityDisc extends AbstractEnergyProjectileAbility implements IAbilityDisc { - // Disc geometry private float discRadius = 1.0f; private float discThickness = 0.2f; - - // Boomerang properties + private boolean vertical = false; private boolean boomerang = false; private int boomerangDelay = 40; - // Energy data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); - private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for disc entity (used during windup charging) - private transient EntityAbilityDisc discEntity = null; - public AbilityDisc() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f), + new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f), + new EnergyHomingData(0.6f, true, 0.12f, 18.0f), + new EnergyLifespanData(35.0f, 200) + ); this.typeId = "ability.cnpc.disc"; this.name = "Disc"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -62,284 +48,150 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Disc_Windup"; this.activeAnimationName = "Ability_Disc_Active"; } + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + @Override - public boolean isTargetingModeLocked() { - return true; + protected EntityAbilityDisc createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityDisc( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + discRadius, discThickness, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + boomerang, boomerangDelay); } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start moving the disc that was spawned during windup - if (discEntity != null && !discEntity.isDead) { - discEntity.startMoving(target); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn disc in charging mode on first tick of windup - if (tick == 1) { - // Create disc in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - discEntity = new EntityAbilityDisc( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - discRadius, discThickness, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData, - boomerang, boomerangDelay); - discEntity.setupCharging(anchorData, windUpTicks); - - discEntity.setEffects(this.effects); - discEntity.setSourceAbility(this); - world.spawnEntityInWorld(discEntity); + protected void fireEntity(EntityAbilityDisc disc, EntityLivingBase target) { + if (isPreview()) { + disc.startPreviewFiring(); + } else { + disc.startMoving(target); } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (discEntity == null || discEntity.isDead) { - discEntity = null; - signalCompletion(); - } + protected void setupEntityCharging(EntityAbilityDisc disc, ProjectileData projData, int index) { + disc.setupCharging(projData.anchor, windUpTicks, vertical); } @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + protected void setupEntityPreview(EntityAbilityDisc disc, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + disc.setupPreview(caster, discRadius, discThickness, resolved, lightningData, projData.anchor, windUpTicks, vertical); } @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); + protected EntityAbilityDisc[] createEntityArray(int size) { + return new EntityAbilityDisc[size]; } @Override - public void cleanup() { - // Despawn disc entity if still alive - if (discEntity != null && !discEntity.isDead) { - discEntity.setDead(); - } - discEntity = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(discRadius * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { + protected float getProjectileTelegraphRadius() { return discRadius * 1.5f; } + // ==================== VARIANTS ==================== + @Override - public void writeTypeNBT(NBTTagCompound nbt) { + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Disc"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityDisc disc = (AbilityDisc) a; + a.setName("Dual Disc"); + disc.setProjectileCount(2); + disc.setFireDelay(5); + disc.projectiles[1].colorOverride = true; + disc.projectiles[1].innerColor = 0xFFFFFF; + disc.projectiles[1].outerColor = 0x8800FF; + a.setWindUpAnimationName("Ability_DiscDual_Windup"); + a.setActiveAnimationName("Ability_DiscDual_Active"); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("discRadius", discRadius); nbt.setFloat("discThickness", discThickness); + nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; - this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.discRadius = nbt.getFloat("discRadius"); + this.discThickness = nbt.getFloat("discThickness"); + this.vertical = nbt.getBoolean("vertical"); + this.boomerang = nbt.getBoolean("boomerang"); + this.boomerangDelay = nbt.getInteger("boomerangDelay"); } - // Getters & Setters + // ==================== TYPE-SPECIFIC GETTERS ==================== + public float getSpeed() { return homingData.speed; } public void setSpeed(float speed) { homingData.speed = speed; } + public float getDiscRadius() { return discRadius; } public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } + public float getDiscThickness() { return discThickness; } public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; } + + public boolean isVertical() { return vertical; } + public void setVertical(boolean vertical) { this.vertical = vertical; } + public boolean isBoomerang() { return boomerang; } public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; } + public int getBoomerangDelay() { return boomerangDelay; } public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; } - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { colorData.outerColor = outerColor; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { colorData.outerColorAlpha = outerColorAlpha; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { colorData.rotationSpeed = rotationSpeed; } - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } - - @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj); - disc.setupPreview(npc, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks); - return disc; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.disc"), - FieldDef.row( - FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), - FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.section("ability.section.boomerang"), - FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang) - .hover("ability.hover.boomerang"), - FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay) - .visibleWhen(this::isBoomerang), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + protected void addTypeDefinitions(List defs) { + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.disc")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), + FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) + )); + defs.add(FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) + .hover("ability.hover.vertical")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.boomerang")); + defs.add(FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang).hover("ability.hover.boomerang")); + defs.add(FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay).visibleWhen(this::isBoomerang)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java deleted file mode 100644 index 421861fcd..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDiscDual.java +++ /dev/null @@ -1,527 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityDiscDual extends Ability { - - // Disc geometry - private float discRadius = 1.0f; - private float discThickness = 0.2f; - - // Boomerang properties - private boolean boomerang = false; - private int boomerangDelay = 40; - - // Dual properties - private boolean dualFire = true; - private int dualFireDelay = 10; - - // Energy data classes - private final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f), - new EnergyDisplayData(0xFFFFFF, 0x8800FF, true, 0.4f, 0.5f, 5.0f) - }; - private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.LEFT_HAND), new EnergyAnchorData(AnchorPoint.RIGHT_HAND) - }; - private final EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for disc entity (used during windup charging) - private transient EntityAbilityDisc discEntity = null; - private transient EntityAbilityDisc discEntity2 = null; - - public AbilityDiscDual() { - this.typeId = "ability.cnpc.disc_dual"; - this.name = "Disc Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 30.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 60; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animations - this.windUpAnimationName = "Ability_DiscDual_Windup"; - this.activeAnimationName = "Ability_DiscDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start moving the orb that was spawned during windup - if (discEntity != null && !discEntity.isDead) { - discEntity.startMoving(target); - } - - if (dualFire) { - if (discEntity2 != null && !discEntity2.isDead && dualFireDelay <= 0) { - discEntity2.startMoving(target); - } - } else if (discEntity2 != null) { - discEntity2.setDead(); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn disc in charging mode on first tick of windup - if (tick == 1) { - // Create disc in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0]); - discEntity = new EntityAbilityDisc( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, - discRadius, discThickness, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0], - boomerang, boomerangDelay); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1]); - discEntity2 = new EntityAbilityDisc( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, - discRadius, discThickness, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1], - boomerang, boomerangDelay); - - discEntity.setSiblingEntityId(discEntity2.getEntityId()); - discEntity2.setSiblingEntityId(discEntity.getEntityId()); - - discEntity.setupCharging(anchorData[0], windUpTicks); - discEntity2.setupCharging(anchorData[1], windUpTicks); - - discEntity.setEffects(this.effects); - - if (dualFire) { - discEntity2.setEffects(this.effects); - } - - discEntity.setSourceAbility(this); - discEntity2.setSourceAbility(this); - world.spawnEntityInWorld(discEntity); - world.spawnEntityInWorld(discEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((discEntity == null || discEntity.isDead) && (discEntity2 == null || discEntity2.isDead)) { - discEntity = null; - discEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && discEntity2 != null && !discEntity2.isDead) { - discEntity2.startMoving(target); - } - } else { - if (discEntity == null || discEntity.isDead) { - discEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn disc entity if still alive - if (discEntity != null && !discEntity.isDead) { - discEntity.setDead(); - } - - if (discEntity2 != null && !discEntity2.isDead) { - discEntity2.setDead(); - } - - discEntity = null; - discEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(discRadius * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return discRadius * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("discRadius", discRadius); - nbt.setFloat("discThickness", discThickness); - nbt.setBoolean("boomerang", boomerang); - nbt.setInteger("boomerangDelay", boomerangDelay); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - - NBTTagCompound disc1 = new NBTTagCompound(); - NBTTagCompound disc2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound disc = i == 0 ? disc1 : disc2; - anchorData[i].writeNBT(disc); - displayData[i].writeNBT(disc); - lightningData[i].writeNBT(disc); - trajectoryData[i].writeNBT(disc); - } - - nbt.setTag("Disc_1", disc1); - nbt.setTag("Disc_2", disc2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound disc1 = nbt.hasKey("Disc_1") ? nbt.getCompoundTag("Disc_1") : new NBTTagCompound(); - NBTTagCompound disc2 = nbt.hasKey("Disc_2") ? nbt.getCompoundTag("Disc_2") : new NBTTagCompound(); - - this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; - this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; - this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); - this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - - for (int i = 0; i < 2; i++) { - NBTTagCompound disc = i == 0 ? disc1 : disc2; - anchorData[i].readNBT(disc); - displayData[i].readNBT(disc); - lightningData[i].readNBT(disc); - trajectoryData[i].readNBT(disc); - } - } - - // Getters & Setters - private EnergyDisplayData getColorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return displayData[orb]; - } - private EnergyLightningData getLightningData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return lightningData[orb]; - } - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public boolean isDualFire() { return dualFire; } - public void setDualFire(boolean dualFire) { this.dualFire = dualFire; } - public int getDualFireDelay() { return dualFireDelay; } - public void setDualFireDelay(int dualFireDelay) { this.dualFireDelay = dualFireDelay; } - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { homingData.speed = speed; } - public float getDiscRadius() { return discRadius; } - public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } - public float getDiscThickness() { return discThickness; } - public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; } - public boolean isBoomerang() { return boomerang; } - public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; } - public int getBoomerangDelay() { return boomerangDelay; } - public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; } - - - public int getInnerColor(int orb) { return getColorData(orb).innerColor; } - public void setInnerColor(int orb, int innerColor) { getColorData(orb).innerColor = innerColor; } - public int getOuterColor(int orb) { return getColorData(orb).outerColor; } - public void setOuterColor(int orb, int outerColor) { getColorData(orb).outerColor = outerColor; } - public boolean isOuterColorEnabled(int orb) { return getColorData(orb).outerColorEnabled; } - public void setOuterColorEnabled(int orb, boolean enabled) { getColorData(orb).outerColorEnabled = enabled; } - public float getOuterColorWidth(int orb) { return getColorData(orb).outerColorWidth; } - public void setOuterColorWidth(int orb, float width) { getColorData(orb).outerColorWidth = width; } - public float getOuterColorAlpha(int orb) { return getColorData(orb).outerColorAlpha; } - public void setOuterColorAlpha(int orb, float alpha) { getColorData(orb).outerColorAlpha = alpha; } - public float getRotationSpeed(int orb) { return getColorData(orb).rotationSpeed; } - public void setRotationSpeed(int orb, float speed) { getColorData(orb).rotationSpeed = speed; } - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - - public boolean hasLightningEffect(int orb) { return getLightningData(orb).lightningEffect; } - public void setLightningEffect(int orb, boolean lightningEffect) { getLightningData(orb).lightningEffect = lightningEffect; } - public float getLightningDensity(int orb) { return getLightningData(orb).lightningDensity; } - public void setLightningDensity(int orb, float lightningDensity) { getLightningData(orb).lightningDensity = lightningDensity; } - public float getLightningRadius(int orb) { return getLightningData(orb).lightningRadius; } - public void setLightningRadius(int orb, float lightningRadius) { getLightningData(orb).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) - ), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.section("ability.section.disc"), - FieldDef.row( - FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), - FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming) - .hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength) - .visibleWhen(this::isHoming), - FieldDef.section("ability.section.boomerang"), - FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang) - .hover("ability.hover.boomerang"), - FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay) - .visibleWhen(this::isBoomerang), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive) - .hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius) - .visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Disc 1 - FieldDef.section("ability.section.disc1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 5.0f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 10.0f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Disc 2 - FieldDef.section("ability.section.disc2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj); - disc.setupPreview(npc, discRadius, discThickness, displayData[0], lightningData[0], anchorData[0], windUpTicks); - return disc; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java index ec9f157f9..dc1b075e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -66,7 +66,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } @Override - public boolean hasDamage() { + public boolean allowBurst() { return false; } @@ -95,7 +95,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { lastAttacker = null; counterTriggered = false; lastDamageTaken = 0.0f; @@ -103,9 +103,9 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !world.isRemote) { - performCounter(caster, world); + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !caster.worldObj.isRemote) { + performCounter(caster, caster.worldObj); } if (tick > counterWindow && counterEligible) { @@ -128,16 +128,22 @@ public class AbilityGuard extends Ability implements IAbilityGuard { lastAttacker = attacker; lastDamageTaken = damage; - float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); - float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); - - caster.setHealth(newHealth); - - if (!canCounter || !counterEligible || counterTriggered || !isDirectHit(source)) { - caster.setHealth(newHealth); + // Players: damage reduction handled via LivingHurtEvent (event.ammount modification) + // NPCs: called AFTER damageEntity() so health was already reduced — heal back here + if (caster instanceof EntityPlayer) { + if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { + counterTriggered = true; + } } else { - caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); - counterTriggered = true; + float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); + float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); + + if (canCounter && counterEligible && !counterTriggered && isDirectHit(source)) { + caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); + counterTriggered = true; + } else { + caster.setHealth(newHealth); + } } } @@ -232,27 +238,19 @@ public class AbilityGuard extends Ability implements IAbilityGuard { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; - this.canCounter = nbt.hasKey("canCounter") && nbt.getBoolean("canCounter"); - this.counterWindow = nbt.hasKey("counterWindow") ? nbt.getInteger("counterWindow") : 10; + this.durationTicks = nbt.getInteger("durationTicks"); + this.damageReduction = nbt.getFloat("damageReduction"); + this.canCounter = nbt.getBoolean("canCounter"); + this.counterWindow = nbt.getInteger("counterWindow"); try { this.counterType = CounterType.valueOf(nbt.getString("counterType")); } catch (Exception e) { this.counterType = CounterType.FLAT; } - if (nbt.hasKey("counterValue")) { - this.counterValue = nbt.getFloat("counterValue"); - } else if (nbt.hasKey("counterDamage")) { - this.counterValue = nbt.getFloat("counterDamage"); - } else { - this.counterValue = 6.0f; - } - this.counterSound = nbt.hasKey("counterSound") ? nbt.getString("counterSound") : "random.wood_click"; - this.counterAnimationId = nbt.hasKey("counterAnimationId") ? nbt.getInteger("counterAnimationId") : -1; - this.counterAnimationName = nbt.hasKey("counterAnimationName") ? - nbt.getString("counterAnimationName") : - "Ability_Guard_Counter"; + this.counterValue = nbt.getFloat("counterValue"); + this.counterSound = nbt.getString("counterSound"); + this.counterAnimationId = nbt.getInteger("counterAnimationId"); + this.counterAnimationName = nbt.getString("counterAnimationName"); } // Getters & Setters @@ -337,6 +335,10 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterAnimationId = counterAnimationId; } + public boolean isCounterTriggered() { + return counterTriggered; + } + public String getCounterAnimationName() { return counterAnimationName; } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 99ea47172..7ca81c95a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -1,18 +1,11 @@ package kamkeel.npcs.controllers.data.ability.type; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionEffect; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; + import noppes.npcs.api.ability.type.IAbilityHazard; @@ -22,640 +15,141 @@ import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Random; -import java.util.Set; -/** - * Hazard ability: Creates persistent ground effect zones. - * Deals damage and/or applies debuffs to entities in the zone over time. - */ -public class AbilityHazard extends Ability implements IAbilityHazard { - - public enum HazardShape { - CIRCLE, - RING, - CONE; - - @Override - public String toString() { - switch (this) { - case CIRCLE: return "ability.shape.circle"; - case RING: return "ability.shape.ring"; - case CONE: return "ability.shape.cone"; - default: return name(); - } - } - } - - public enum PlacementMode { - AT_CASTER, - AT_TARGET, - FOLLOW_CASTER, - FOLLOW_TARGET; - - @Override - public String toString() { - switch (this) { - case AT_CASTER: return "ability.placement.atCaster"; - case AT_TARGET: return "ability.placement.atTarget"; - case FOLLOW_CASTER: return "ability.placement.followCaster"; - case FOLLOW_TARGET: return "ability.placement.followTarget"; - default: return name(); - } - } - } - - private int durationTicks = 100; - private float radius = 4.0f; - private float innerRadius = 0.0f; - private float coneAngle = 45.0f; - private HazardShape shape = HazardShape.CIRCLE; - private PlacementMode placement = PlacementMode.AT_TARGET; +public class AbilityHazard extends AbilityZone implements IAbilityHazard { + private float radius = 2.0f; private float damagePerSecond = 1.0f; private int damageInterval = 20; private boolean ignoreInvulnFrames = false; - - private int slownessLevel = -1; - private int weaknessLevel = -1; - private int poisonLevel = -1; - private int witherLevel = -1; - private int blindnessLevel = -1; - private int debuffDuration = 40; - private boolean affectsCaster = false; - private float heightAbove = 2.0f; - private float heightBelow = 1.0f; - - // Offset parameters - hazard spawns near target, not exactly on them - private float minOffset = 0.0f; // Minimum offset from target - private float maxOffset = 2.0f; // Maximum offset from target - private boolean randomOffset = true; // Random or fixed offset - - // Runtime state - private static final Random RANDOM = new Random(); - private transient double zoneX, zoneY, zoneZ; - private transient boolean positionLocked = false; - private transient int ticksSinceDamage = 0; - private transient Set damagedThisTick = new HashSet<>(); public AbilityHazard() { + super(300, new EnergyDisplayData(0x00CC00, 0x006600, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.hazard"; this.name = "Hazard"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; this.windUpTicks = 30; - this.telegraphType = TelegraphType.CIRCLE; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; } @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public float getTelegraphRadius() { + public float getZoneRadius() { return radius; } @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - TelegraphInstance instance = super.createTelegraph(caster, target); - if (instance == null) return null; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + activeEntities.clear(); - // Control telegraph following based on placement mode - switch (placement) { - case AT_CASTER: - case FOLLOW_CASTER: - // Telegraph stays at caster position, no following - instance.setEntityIdToFollow(-1); - instance.setX(caster.posX); - instance.setY(caster.posY); - instance.setZ(caster.posZ); - break; - case AT_TARGET: - // Telegraph follows target during windup, locks on execute - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - case FOLLOW_TARGET: - // Telegraph follows target during windup AND active phase - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - } - return instance; - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // AT_CASTER locks immediately, AT_TARGET follows during windup and locks on execute - if (tick == 0) { - switch (placement) { - case AT_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - positionLocked = true; - break; - case AT_TARGET: - // Position will be set from telegraph on execute - // Telegraph follows target during windup - positionLocked = false; - break; - default: - positionLocked = false; - break; + List positions; + if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { + positions = new ArrayList<>(preCalculatedPositions); + preCalculatedPositions.clear(); + } else { + positions = new ArrayList<>(); + List placedPositions = new ArrayList<>(); + float minSeparation = radius * 2.0f; + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + positions.add(pos); } } - } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Lock position from telegraph (which was following target) or calculate it now - TelegraphInstance telegraph = getTelegraphInstance(); + for (int i = 0; i < zoneCount; i++) { + double[] pos = positions.get(i); - switch (placement) { - case AT_CASTER: - // Already locked during windup - if (!positionLocked) { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - case AT_TARGET: - // Use telegraph position if available, apply offset - if (telegraph != null) { - double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), - minOffset, maxOffset, randomOffset, RANDOM); - zoneX = pos[0]; - zoneY = pos[1]; - zoneZ = pos[2]; - // Update telegraph to show actual hazard position - telegraph.setX(zoneX); - telegraph.setY(zoneY); - telegraph.setZ(zoneZ); - } else if (target != null) { - double[] pos = Ability.calculateOffsetPosition(target.posX, target.posY, target.posZ, - minOffset, maxOffset, randomOffset, RANDOM); - zoneX = pos[0]; - zoneY = pos[1]; - zoneZ = pos[2]; - } else { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } else { - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - } - break; - } - positionLocked = true; - ticksSinceDamage = damageInterval; - } + EntityAbilityZone entity = EntityAbilityZone.createHazard(caster.worldObj, caster, + pos[0], caster.posY, pos[1], + zoneShape, + radius, + damagePerSecond, damageInterval, + ignoreInvulnFrames, affectsCaster, + durationTicks, + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + getEffects()); - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + applyVisualToEntity(entity); - // Check if hazard duration has ended - if (tick >= durationTicks) { - signalCompletion(); - return; - } - - damagedThisTick.clear(); - ticksSinceDamage++; - - switch (placement) { - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } - break; - default: - break; - } - - if (ticksSinceDamage >= damageInterval) { - ticksSinceDamage = 0; - - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - zoneX - radius, zoneY - heightBelow, zoneZ - radius, - zoneX + radius, zoneY + heightAbove, zoneZ + radius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - - for (EntityLivingBase entity : entities) { - if (entity == caster && !affectsCaster) continue; - if (damagedThisTick.contains(entity.getEntityId())) continue; - if (!isInZone(entity, caster)) continue; - - if (damagePerSecond > 0) { - if (ignoreInvulnFrames) { - entity.hurtResistantTime = 0; - } - // Apply damage with scripted event support (no knockback for hazard) - boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); - if (!wasHit) continue; // Skip debuffs if hit was cancelled - } - - applyDebuffs(entity); - damagedThisTick.add(entity.getEntityId()); + if (isPreview()) { + entity.setupPreview(caster); } - } - } - private boolean isInZone(EntityLivingBase entity, EntityLivingBase caster) { - double dx = entity.posX - zoneX; - double dz = entity.posZ - zoneZ; - double dist = Math.sqrt(dx * dx + dz * dz); - - switch (shape) { - case CIRCLE: - return dist <= radius; - case RING: - return dist >= innerRadius && dist <= radius; - case CONE: - if (dist > radius) return false; - float casterYaw = caster.rotationYaw; - double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); - double angleDiff = Math.abs(normalizeAngle(angleToEntity - casterYaw)); - return angleDiff <= coneAngle / 2; - default: - return dist <= radius; + spawnAbilityEntity(entity); + activeEntities.add(entity); } } - private double normalizeAngle(double angle) { - while (angle > 180) angle -= 360; - while (angle < -180) angle += 360; - return angle; - } - - private void applyDebuffs(EntityLivingBase target) { - if (slownessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, debuffDuration, slownessLevel)); - } - if (weaknessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.weakness.id, debuffDuration, weaknessLevel)); - } - if (poisonLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.poison.id, debuffDuration, poisonLevel)); - } - if (witherLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.wither.id, debuffDuration, witherLevel)); - } - if (blindnessLevel >= 0) { - target.addPotionEffect(new PotionEffect(Potion.blindness.id, debuffDuration, blindnessLevel)); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - damagedThisTick.clear(); - positionLocked = false; - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - damagedThisTick.clear(); - positionLocked = false; - } - @Override public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); + writeZoneNBT(nbt); nbt.setFloat("radius", radius); - nbt.setFloat("innerRadius", innerRadius); - nbt.setFloat("coneAngle", coneAngle); - nbt.setString("shape", shape.name()); - nbt.setString("placement", placement.name()); nbt.setFloat("damagePerSecond", damagePerSecond); nbt.setInteger("damageInterval", damageInterval); nbt.setBoolean("ignoreInvulnFrames", ignoreInvulnFrames); - nbt.setInteger("slownessLevel", slownessLevel); - nbt.setInteger("weaknessLevel", weaknessLevel); - nbt.setInteger("poisonLevel", poisonLevel); - nbt.setInteger("witherLevel", witherLevel); - nbt.setInteger("blindnessLevel", blindnessLevel); - nbt.setInteger("debuffDuration", debuffDuration); nbt.setBoolean("affectsCaster", affectsCaster); - nbt.setFloat("heightAbove", heightAbove); - nbt.setFloat("heightBelow", heightBelow); - nbt.setFloat("minOffset", minOffset); - nbt.setFloat("maxOffset", maxOffset); - nbt.setBoolean("randomOffset", randomOffset); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 100; - this.radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 4.0f; - this.innerRadius = nbt.hasKey("innerRadius") ? nbt.getFloat("innerRadius") : 0.0f; - this.coneAngle = nbt.hasKey("coneAngle") ? nbt.getFloat("coneAngle") : 45.0f; - try { - this.shape = HazardShape.valueOf(nbt.getString("shape")); - } catch (Exception e) { - this.shape = HazardShape.CIRCLE; - } - try { - this.placement = PlacementMode.valueOf(nbt.getString("placement")); - } catch (Exception e) { - this.placement = PlacementMode.AT_TARGET; - } - // Support legacy "damagePerTick" key for backwards compatibility - if (nbt.hasKey("damagePerSecond")) { - this.damagePerSecond = nbt.getFloat("damagePerSecond"); - } else if (nbt.hasKey("damagePerTick")) { - this.damagePerSecond = nbt.getFloat("damagePerTick"); - } else { - this.damagePerSecond = 1.0f; - } - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 20; - this.ignoreInvulnFrames = nbt.hasKey("ignoreInvulnFrames") && nbt.getBoolean("ignoreInvulnFrames"); - this.slownessLevel = nbt.hasKey("slownessLevel") ? nbt.getInteger("slownessLevel") : -1; - this.weaknessLevel = nbt.hasKey("weaknessLevel") ? nbt.getInteger("weaknessLevel") : -1; - this.poisonLevel = nbt.hasKey("poisonLevel") ? nbt.getInteger("poisonLevel") : -1; - this.witherLevel = nbt.hasKey("witherLevel") ? nbt.getInteger("witherLevel") : -1; - this.blindnessLevel = nbt.hasKey("blindnessLevel") ? nbt.getInteger("blindnessLevel") : -1; - this.debuffDuration = nbt.hasKey("debuffDuration") ? nbt.getInteger("debuffDuration") : 40; - this.affectsCaster = nbt.hasKey("affectsCaster") && nbt.getBoolean("affectsCaster"); - this.heightAbove = nbt.hasKey("heightAbove") ? nbt.getFloat("heightAbove") : 2.0f; - this.heightBelow = nbt.hasKey("heightBelow") ? nbt.getFloat("heightBelow") : 1.0f; - this.minOffset = nbt.hasKey("minOffset") ? nbt.getFloat("minOffset") : 0.0f; - this.maxOffset = nbt.hasKey("maxOffset") ? nbt.getFloat("maxOffset") : 2.0f; - this.randomOffset = !nbt.hasKey("randomOffset") || nbt.getBoolean("randomOffset"); + readZoneNBT(nbt, 300); + this.radius = nbt.getFloat("radius"); + this.damagePerSecond = nbt.getFloat("damagePerSecond"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.ignoreInvulnFrames = nbt.getBoolean("ignoreInvulnFrames"); + this.affectsCaster = nbt.getBoolean("affectsCaster"); } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } + public float getRadius() { return radius; } + public void setRadius(float radius) { this.radius = radius; } - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } + public float getDamagePerSecond() { return damagePerSecond; } + public void setDamagePerSecond(float damagePerSecond) { this.damagePerSecond = damagePerSecond; } - public float getRadius() { - return radius; - } + public int getDamageInterval() { return damageInterval; } + public void setDamageInterval(int damageInterval) { this.damageInterval = damageInterval; } - public void setRadius(float radius) { - this.radius = radius; - } + public boolean isIgnoreInvulnFrames() { return ignoreInvulnFrames; } + public void setIgnoreInvulnFrames(boolean ignoreInvulnFrames) { this.ignoreInvulnFrames = ignoreInvulnFrames; } - public float getInnerRadius() { - return innerRadius; - } - - public void setInnerRadius(float innerRadius) { - this.innerRadius = innerRadius; - } - - public float getConeAngle() { - return coneAngle; - } - - public void setConeAngle(float coneAngle) { - this.coneAngle = coneAngle; - } - - public HazardShape getShapeEnum() { - return shape; - } - - public void setShapeEnum(HazardShape shape) { - this.shape = shape; - } - - @Override - public int getShape() { - return shape.ordinal(); - } - - @Override - public void setShape(int shape) { - HazardShape[] values = HazardShape.values(); - this.shape = shape >= 0 && shape < values.length ? values[shape] : HazardShape.CIRCLE; - } - - public PlacementMode getPlacementEnum() { - return placement; - } - - public void setPlacementEnum(PlacementMode placement) { - this.placement = placement; - } - - @Override - public int getPlacement() { - return placement.ordinal(); - } - - @Override - public void setPlacement(int placement) { - PlacementMode[] values = PlacementMode.values(); - this.placement = placement >= 0 && placement < values.length ? values[placement] : PlacementMode.AT_CASTER; - } - - public float getDamagePerSecond() { - return damagePerSecond; - } - - public void setDamagePerSecond(float damagePerSecond) { - this.damagePerSecond = damagePerSecond; - } - - public int getDamageInterval() { - return damageInterval; - } - - public void setDamageInterval(int damageInterval) { - this.damageInterval = damageInterval; - } - - public boolean isIgnoreInvulnFrames() { - return ignoreInvulnFrames; - } - - public void setIgnoreInvulnFrames(boolean ignoreInvulnFrames) { - this.ignoreInvulnFrames = ignoreInvulnFrames; - } - - public int getSlownessLevel() { - return slownessLevel; - } - - public void setSlownessLevel(int slownessLevel) { - this.slownessLevel = slownessLevel; - } - - public int getWeaknessLevel() { - return weaknessLevel; - } - - public void setWeaknessLevel(int weaknessLevel) { - this.weaknessLevel = weaknessLevel; - } - - public int getPoisonLevel() { - return poisonLevel; - } - - public void setPoisonLevel(int poisonLevel) { - this.poisonLevel = poisonLevel; - } - - public int getWitherLevel() { - return witherLevel; - } - - public void setWitherLevel(int witherLevel) { - this.witherLevel = witherLevel; - } - - public int getBlindnessLevel() { - return blindnessLevel; - } - - public void setBlindnessLevel(int blindnessLevel) { - this.blindnessLevel = blindnessLevel; - } - - public int getDebuffDuration() { - return debuffDuration; - } - - public void setDebuffDuration(int debuffDuration) { - this.debuffDuration = debuffDuration; - } - - public boolean isAffectsCaster() { - return affectsCaster; - } - - public void setAffectsCaster(boolean affectsCaster) { - this.affectsCaster = affectsCaster; - } - - public float getHeightAbove() { - return heightAbove; - } - - public void setHeightAbove(float heightAbove) { - this.heightAbove = heightAbove; - } - - public float getHeightBelow() { - return heightBelow; - } - - public void setHeightBelow(float heightBelow) { - this.heightBelow = heightBelow; - } - - public float getMinOffset() { - return minOffset; - } - - public void setMinOffset(float minOffset) { - this.minOffset = minOffset; - } - - public float getMaxOffset() { - return maxOffset; - } - - public void setMaxOffset(float maxOffset) { - this.maxOffset = maxOffset; - } - - public boolean isRandomOffset() { - return randomOffset; - } - - public void setRandomOffset(boolean randomOffset) { - this.randomOffset = randomOffset; - } - - // Runtime getters - public double getZoneX() { - return zoneX; - } - - public double getZoneY() { - return zoneY; - } - - public double getZoneZ() { - return zoneZ; - } + public boolean isAffectsCaster() { return affectsCaster; } + public void setAffectsCaster(boolean affectsCaster) { this.affectsCaster = affectsCaster; } @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), - FieldDef.enumField("ability.shape", HazardShape.class, this::getShapeEnum, this::setShapeEnum) - .hover("ability.hover.shape"), - FieldDef.enumField("ability.placement", PlacementMode.class, this::getPlacementEnum, this::setPlacementEnum) - .hover("ability.hover.placement"), - FieldDef.section("ability.section.area"), FieldDef.row( - FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), - FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius) + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), + FieldDef.enumField("ability.zoneShape", ZoneShape.class, this::getZoneShapeEnum, this::setZoneShapeEnum) ), + FieldDef.section("ability.section.zone"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getSpawnRadius, this::setSpawnRadius), + FieldDef.intField("gui.count", this::getZoneCount, this::setZoneCount).range(1, 20) + ), + FieldDef.floatField("gui.height", this::getZoneHeight, this::setZoneHeight), + FieldDef.section("ability.section.area"), + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), FieldDef.section("ability.section.damage"), FieldDef.row( - FieldDef.floatField("ability.damagePerSecond", this::getDamagePerSecond, this::setDamagePerSecond), - FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval) + FieldDef.floatField("gui.dps", this::getDamagePerSecond, this::setDamagePerSecond), + FieldDef.intField("gui.interval", this::getDamageInterval, this::setDamageInterval) ), - FieldDef.section("ability.section.debuffs"), - FieldDef.row( - FieldDef.intField("ability.slownessLevel", this::getSlownessLevel, this::setSlownessLevel), - FieldDef.intField("ability.debuffDuration", this::getDebuffDuration, this::setDebuffDuration) - ), - FieldDef.intField("ability.poisonLevel", this::getPoisonLevel, this::setPoisonLevel), + FieldDef.boolField("ability.ignoreInvulnFrames", this::isIgnoreInvulnFrames, this::setIgnoreInvulnFrames), FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster) .hover("ability.hover.affectsCaster"), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); + + addVisualFieldDefs(defs); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index c1faf000b..6119e1340 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -63,6 +63,11 @@ public class AbilityHeal extends Ability implements IAbilityHeal { return false; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -74,28 +79,32 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) return; - getHealedAllies().clear(); + if (!isPreview()) { + getHealedAllies().clear(); - // Always find allies if we're healing them (needed for both instant and HoT) - if (healAllies && healRadius > 0) { - findAlliesInRadius(caster, world); + // Always find allies if we're healing them (needed for both instant and HoT) + if (healAllies && healRadius > 0) { + findAlliesInRadius(caster, caster.worldObj); + } + + if (instantHeal) { + // Instant heal - apply all healing now + if (healSelf) { + healEntity(caster); + spawnHealParticles(caster.worldObj, caster); + } + + for (EntityLivingBase ally : getHealedAllies()) { + healEntity(ally); + spawnHealParticles(caster.worldObj, ally); + } + } } if (instantHeal) { - // Instant heal - apply all healing now - if (healSelf) { - healEntity(caster); - spawnHealParticles(world, caster); - } - - for (EntityLivingBase ally : getHealedAllies()) { - healEntity(ally); - spawnHealParticles(world, ally); - } - // Instant heal completes immediately signalCompletion(); } @@ -103,8 +112,8 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote || instantHeal) return; + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if ((caster.worldObj.isRemote && !isPreview()) || instantHeal) return; // Heal over time - distribute heal across duration ticks if (tick % 10 == 0) { @@ -119,7 +128,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } caster.heal(selfTickHeal); if (tick % 20 == 0) { - spawnHealParticles(world, caster); + spawnHealParticles(caster.worldObj, caster); } } @@ -133,7 +142,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } ally.heal(allyTickHeal); if (tick % 20 == 0) { - spawnHealParticles(world, ally); + spawnHealParticles(caster.worldObj, ally); } } } @@ -218,13 +227,13 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; - this.healAmount = nbt.hasKey("healAmount") ? nbt.getFloat("healAmount") : 10.0f; - this.healPercent = nbt.hasKey("healPercent") ? nbt.getFloat("healPercent") : 0.0f; - this.healSelf = !nbt.hasKey("healSelf") || nbt.getBoolean("healSelf"); - this.healAllies = nbt.hasKey("healAllies") && nbt.getBoolean("healAllies"); - this.healRadius = nbt.hasKey("healRadius") ? nbt.getFloat("healRadius") : 0.0f; - this.instantHeal = !nbt.hasKey("instantHeal") || nbt.getBoolean("instantHeal"); + this.durationTicks = nbt.getInteger("durationTicks"); + this.healAmount = nbt.getFloat("healAmount"); + this.healPercent = nbt.getFloat("healPercent"); + this.healSelf = nbt.getBoolean("healSelf"); + this.healAllies = nbt.getBoolean("healAllies"); + this.healRadius = nbt.getFloat("healRadius"); + this.instantHeal = nbt.getBoolean("instantHeal"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 0e236de32..367b534c7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -9,7 +9,6 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityHeavyHit; @@ -28,6 +27,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { private float knockback = 2.0f; private float hitLength = 4.0f; // How far in front of the caster the hit reaches private float hitWidth = 3.0f; // How wide to each side (total width = hitWidth * 2) + private int activeDisplayTicks = 10; // How long active animation plays before completing public AbilityHeavyHit() { this.typeId = "ability.cnpc.heavy_hit"; @@ -67,59 +67,60 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { signalCompletion(); return; } - // Calculate forward and right vectors from caster yaw - float yawRad = (float) Math.toRadians(caster.rotationYaw); - double forwardX = -Math.sin(yawRad); - double forwardZ = Math.cos(yawRad); - double rightX = forwardZ; // perpendicular right - double rightZ = -forwardX; + if (!isPreview()) { + // Calculate forward and right vectors from caster yaw + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double forwardX = -Math.sin(yawRad); + double forwardZ = Math.cos(yawRad); + double rightX = forwardZ; // perpendicular right + double rightZ = -forwardX; - // Search area: AABB that encompasses the rectangle - float searchDist = Math.max(hitLength, hitWidth) + 1.0f; - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity( - caster, caster.boundingBox.expand(searchDist, 2, searchDist)); + // Search area: AABB that encompasses the rectangle + float searchDist = Math.max(hitLength, hitWidth) + 1.0f; + @SuppressWarnings("unchecked") + List entities = caster.worldObj.getEntitiesWithinAABBExcludingEntity( + caster, caster.boundingBox.expand(searchDist, 2, searchDist)); - boolean anyHit = false; - for (Entity entity : entities) { - if (!(entity instanceof EntityLivingBase) || entity == caster) continue; - EntityLivingBase livingTarget = (EntityLivingBase) entity; + boolean anyHit = false; + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase) || entity == caster) continue; + EntityLivingBase livingTarget = (EntityLivingBase) entity; - double dx = livingTarget.posX - caster.posX; - double dz = livingTarget.posZ - caster.posZ; + double dx = livingTarget.posX - caster.posX; + double dz = livingTarget.posZ - caster.posZ; - // Project onto forward direction (must be in front, within hitLength) - double forwardDist = dx * forwardX + dz * forwardZ; - if (forwardDist < 0 || forwardDist > hitLength) continue; + // Project onto forward direction (must be in front, within hitLength) + double forwardDist = dx * forwardX + dz * forwardZ; + if (forwardDist < 0 || forwardDist > hitLength) continue; - // Project onto right direction (must be within hitWidth to each side) - double sideDist = dx * rightX + dz * rightZ; - if (Math.abs(sideDist) > hitWidth) continue; + // Project onto right direction (must be within hitWidth to each side) + double sideDist = dx * rightX + dz * rightZ; + if (Math.abs(sideDist) > hitWidth) continue; - // Entity is within the rectangle - apply damage - boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); - if (wasHit) { - applyEffects(livingTarget); - anyHit = true; + // Entity is within the rectangle - apply damage + boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); + if (wasHit) { + applyEffects(livingTarget); + anyHit = true; + } } - } - // Play hit sound even if nothing was hit (the attack still happens) - if (!anyHit) { - world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + // Play hit sound even if nothing was hit (the attack still happens) + if (!anyHit) { + caster.worldObj.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + } } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Just enough delay to see the active animation - if (tick == 10) + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (tick >= activeDisplayTicks) signalCompletion(); } @@ -129,14 +130,16 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { nbt.setFloat("knockback", knockback); nbt.setFloat("hitLength", hitLength); nbt.setFloat("hitWidth", hitWidth); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f; - this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f; - this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f; + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.hitLength = nbt.getFloat("hitLength"); + this.hitWidth = nbt.getFloat("hitWidth"); + this.activeDisplayTicks = nbt.hasKey("activeDisplayTicks") ? nbt.getInteger("activeDisplayTicks") : 10; } // Getters & Setters @@ -172,6 +175,14 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.hitWidth = hitWidth; } + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -185,6 +196,7 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength), FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) ), + FieldDef.intField("ability.activeDisplayTicks", this::getActiveDisplayTicks, this::setActiveDisplayTicks).range(1, 200), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index 4be2315d5..3ce1e33fb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -2,51 +2,42 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityLaser; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; import net.minecraft.util.Vec3; -import net.minecraft.world.World; import noppes.npcs.api.ability.type.IAbilityLaserShot; +import noppes.npcs.client.gui.builder.FieldDef; -import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** * Laser Shot ability: Fast expanding thin line that pierces through targets. * Travels in a straight line from origin, damaging all entities it passes through. + * Single-projectile only (always projectileCount=1). */ -public class AbilityLaserShot extends Ability implements IAbilityLaserShot { +public class AbilityLaserShot extends AbstractEnergyProjectileAbility implements IAbilityLaserShot { - // Laser properties private float laserWidth = 0.3f; private float expansionSpeed = 3.0f; private int lingerTicks = 8; - // Data classes - private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); - private final EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100); - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for laser entity (used for movement locking) - private transient EntityAbilityLaser laserEntity = null; - public AbilityLaserShot() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f), + new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f), + new EnergyHomingData(), + new EnergyLifespanData(40.0f, 100) + ); this.typeId = "ability.cnpc.laser_shot"; this.name = "Laser Shot"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -55,21 +46,55 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.cooldownTicks = 0; this.windUpTicks = 15; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP; this.telegraphType = TelegraphType.LINE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Laser_Windup"; this.activeAnimationName = "Ability_Laser_Active"; } + // ==================== OVERRIDES ==================== + + @Override + protected AnchorPoint getDefaultAnchor(int index) { + return AnchorPoint.FRONT; + } + @Override public boolean isTargetingModeLocked() { return false; } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + public int getMaxPreviewDuration() { + return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; + } + + /** + * LINE telegraph: positioned at caster, aimed toward target. + * Overrides the circle telegraph from AbstractEnergyProjectileAbility. + */ + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster)) { + return null; + } + + Telegraph telegraph = Telegraph.line(getTelegraphLength(), getTelegraphWidth()); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, caster.posX, caster.posY, caster.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(caster.getEntityId()); + if (target != null) { + instance.setTargetEntityId(target.getEntityId()); + } + return instance; } @Override @@ -79,228 +104,99 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public float getTelegraphWidth() { - return laserWidth * 2.0f; // Make telegraph slightly wider for visibility + return laserWidth * 2.0f; + } + + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + + @Override + protected EntityAbilityLaser createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityLaser( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + laserWidth, + resolved, combatData, lightningData, lifespanData, trajectoryData, + expansionSpeed, lingerTicks); } @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - if (tick == 1) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - laserEntity = new EntityAbilityLaser( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - laserWidth, - colorData, combatData, lightningData, lifespanData, trajectoryData, - expansionSpeed, lingerTicks - ); - - laserEntity.setupCharging(anchorData, windUpTicks); - - laserEntity.setEffects(this.effects); - laserEntity.setSourceAbility(this); - world.spawnEntityInWorld(laserEntity); - } + protected void fireEntity(EntityAbilityLaser laser, EntityLivingBase target) { + laser.setLockVerticalDirection(true); + laser.startMoving(target); } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - if (laserEntity == null) { - signalCompletion(); - return; - } - - laserEntity.startMoving(target); - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class + protected void setupEntityCharging(EntityAbilityLaser laser, ProjectileData projData, int index) { + laser.setupCharging(projData.anchor, windUpTicks); } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (laserEntity == null || laserEntity.isDead) { - laserEntity = null; - signalCompletion(); - } + protected void setupEntityPreview(EntityAbilityLaser laser, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + laser.setupPreview(caster, laserWidth, resolved, lightningData, expansionSpeed, lifespanData.maxDistance); } @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + protected EntityAbilityLaser[] createEntityArray(int size) { + return new EntityAbilityLaser[size]; } @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - cleanup(); + protected float getProjectileTelegraphRadius() { + return laserWidth * 2.0f; } - @Override - public void cleanup() { - // Despawn laser entity if still alive - if (laserEntity != null && !laserEntity.isDead) { - laserEntity.setDead(); - } - laserEntity = null; - } + // ==================== TYPE-SPECIFIC NBT ==================== @Override - public void writeTypeNBT(NBTTagCompound nbt) { + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("laserWidth", laserWidth); nbt.setFloat("expansionSpeed", expansionSpeed); nbt.setInteger("lingerTicks", lingerTicks); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.laserWidth = nbt.hasKey("laserWidth") ? nbt.getFloat("laserWidth") : 0.3f; - this.expansionSpeed = nbt.hasKey("expansionSpeed") ? nbt.getFloat("expansionSpeed") : 3.0f; - this.lingerTicks = nbt.hasKey("lingerTicks") ? nbt.getInteger("lingerTicks") : 8; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.laserWidth = nbt.getFloat("laserWidth"); + this.expansionSpeed = nbt.getFloat("expansionSpeed"); + this.lingerTicks = nbt.getInteger("lingerTicks"); } - // Getters & Setters - Standalone fields + // ==================== TYPE-SPECIFIC GETTERS ==================== + public float getLaserWidth() { return laserWidth; } public void setLaserWidth(float laserWidth) { this.laserWidth = laserWidth; } + public float getExpansionSpeed() { return expansionSpeed; } public void setExpansionSpeed(float expansionSpeed) { this.expansionSpeed = expansionSpeed; } + public int getLingerTicks() { return lingerTicks; } public void setLingerTicks(int lingerTicks) { this.lingerTicks = lingerTicks; } - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - // Getters & Setters - Color data - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - public int getAnchorPoint() { - return anchorData.anchorPoint.ordinal(); - } - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityLaser laser = new EntityAbilityLaser(npc.worldObj); - laser.setupPreview(npc, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); - return laser; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; - } - - @Override - public boolean spawnPreviewDuringWindup() { - return false; // Laser has no charging, spawns at active phase - } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.row( - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), - FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp) - ), - FieldDef.section("ability.section.beam"), - FieldDef.row( - FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth), - FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed) - ), - FieldDef.row( - FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + protected void addTypeDefinitions(List defs) { + defs.add(FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp) )); + defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth), + FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed) + )); + defs.add(FieldDef.row( + FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java new file mode 100644 index 000000000..de2090cc3 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityMovement.java @@ -0,0 +1,270 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import kamkeel.npcs.controllers.data.ability.Ability; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.Vec3; + +/** + * Abstract base class for abilities that move the caster along the ground + * in a specific direction (Charge, Dash, etc.). + *

+ * Provides shared movement logic: direction locking, stall detection with + * player-aware grace period, velocity application, distance tracking, + * rotation enforcement, and wall collision checking. + *

+ * NOT for ballistic/arc movement (Slam uses a different pattern). + */ +public abstract class AbilityMovement extends Ability { + + /** + * Grace period (in active ticks) before stall detection activates. + * Players need more time because: + * - Server sets motionX/Z and sends S12 velocity packet to client + * - Client receives S12 and starts moving + * - Client sends C03 position packet with updated position back to server + * Until the round trip completes, the server sees the old (stationary) position, + * which would falsely trigger stall detection. + */ + private static final int PLAYER_STALL_GRACE_TICKS = 5; + private static final int NPC_STALL_GRACE_TICKS = 2; + + // ═══════════════════════════════════════════════════════════════════ + // COMMON MOVEMENT STATE (transient, not saved to NBT) + // ═══════════════════════════════════════════════════════════════════ + + protected transient double startX, startY, startZ; + protected transient double prevTickX, prevTickZ; + protected transient Vec3 movementDirection; + protected transient float lockedYaw; + protected transient int maxActiveTicks; + + // ═══════════════════════════════════════════════════════════════════ + // OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + public boolean hasAbilityMovement() { + return true; + } + + @Override + public void cleanup() { + movementDirection = null; + maxActiveTicks = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // DIRECTION HELPERS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Lock direction based on caster type. + * NPC: toward target. Player: look direction. + */ + protected void lockDirection(EntityLivingBase caster, EntityLivingBase target) { + if (!isPlayerCaster(caster) && target != null) { + lockDirectionToTarget(caster, target); + } else { + lockDirectionFromLook(caster); + } + } + + /** + * Lock direction to the caster's look direction (horizontal only). + */ + protected void lockDirectionFromLook(EntityLivingBase caster) { + float yaw = (float) Math.toRadians(caster.rotationYaw); + movementDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); + lockedYaw = computeYawFromDirection(); + } + + /** + * Lock direction toward a target entity. + * Falls back to look direction if target is at the same position. + */ + protected void lockDirectionToTarget(EntityLivingBase caster, EntityLivingBase target) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + movementDirection = Vec3.createVectorHelper(dx / len, 0, dz / len); + lockedYaw = computeYawFromDirection(); + } else { + lockDirectionFromLook(caster); + } + } + + /** + * Get the base yaw for direction calculation. + * NPC: yaw toward target. Player: current look yaw. + */ + protected float getBaseYaw(EntityLivingBase caster, EntityLivingBase target) { + if (!isPlayerCaster(caster) && target != null) { + double dx = target.posX - caster.posX; + double dz = target.posZ - caster.posZ; + return (float) Math.toDegrees(Math.atan2(-dx, dz)); + } + return caster.rotationYaw; + } + + /** + * Set movement direction from a yaw angle (degrees). + */ + protected void setDirectionFromYaw(float yawDegrees) { + float yawRad = (float) Math.toRadians(yawDegrees); + movementDirection = Vec3.createVectorHelper(-Math.sin(yawRad), 0, Math.cos(yawRad)); + lockedYaw = yawDegrees; + } + + // ═══════════════════════════════════════════════════════════════════ + // MOVEMENT INITIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Initialize movement tracking. Call from onExecute(). + * + * @param caster The entity performing the movement + * @param distance Maximum travel distance (for timeout computation) + * @param speed Movement speed in blocks/tick (for timeout computation) + */ + protected void initMovement(EntityLivingBase caster, float distance, float speed) { + startX = caster.posX; + startY = caster.posY; + startZ = caster.posZ; + prevTickX = caster.posX; + prevTickZ = caster.posZ; + maxActiveTicks = speed > 0 ? (int) (distance / speed) + 10 : 10; + } + + // ═══════════════════════════════════════════════════════════════════ + // ACTIVE TICK CHECKS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Check for timeout or missing movement direction. + * + * @return true if the ability should stop + */ + protected boolean checkTimeout(int tick) { + return !isPreview() && (movementDirection == null || tick > maxActiveTicks); + } + + /** + * Check stall detection with appropriate grace period for player vs NPC. + * Players need a longer grace period because velocity sync via S12 packet + * takes time to reach the client, and C03 position packets lag behind. + * + * @return true if the entity is stalled (not moving) + */ + protected boolean checkStall(EntityLivingBase caster, int tick) { + if (isPreview()) return false; + int graceTicks = isPlayerCaster(caster) ? PLAYER_STALL_GRACE_TICKS : NPC_STALL_GRACE_TICKS; + if (tick <= graceTicks) return false; + + double dx = caster.posX - prevTickX; + double dz = caster.posZ - prevTickZ; + return dx * dx + dz * dz < 0.0001; + } + + /** + * Update previous tick position for stall detection. + * Call after stall check, before movement application. + */ + protected void updatePrevPosition(EntityLivingBase caster) { + prevTickX = caster.posX; + prevTickZ = caster.posZ; + } + + /** + * Get total linear distance traveled from start position. + */ + protected double getDistanceTraveled(EntityLivingBase caster) { + double dx = caster.posX - startX; + double dz = caster.posZ - startZ; + return Math.sqrt(dx * dx + dz * dz); + } + + /** + * Get total distance traveled squared (more efficient for comparison). + */ + protected double getDistanceTraveledSq(EntityLivingBase caster) { + double dx = caster.posX - startX; + double dz = caster.posZ - startZ; + return dx * dx + dz * dz; + } + + /** + * Check if movement direction is blocked by walls. + * + * @return true if blocked + */ + protected boolean checkBlocked(EntityLivingBase caster, float speed) { + if (isPreview() || movementDirection == null) return false; + return isMovementBlocked(caster, movementDirection.xCoord, movementDirection.zCoord, speed); + } + + // ═══════════════════════════════════════════════════════════════════ + // VELOCITY APPLICATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Apply movement velocity to the caster (horizontal only, Y unchanged). + */ + protected void applyVelocity(EntityLivingBase caster, float speed) { + caster.motionX = movementDirection.xCoord * speed; + caster.motionZ = movementDirection.zCoord * speed; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + /** + * Apply movement velocity with zero vertical motion. + * Used for ground-locked movement like Charge. + */ + protected void applyVelocityFlat(EntityLivingBase caster, float speed) { + caster.motionX = movementDirection.xCoord * speed; + caster.motionY = 0; + caster.motionZ = movementDirection.zCoord * speed; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + /** + * Stop all horizontal momentum. + */ + protected void stopMomentum(EntityLivingBase caster) { + caster.motionX = 0; + caster.motionZ = 0; + if (!isPreview()) { + caster.velocityChanged = true; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ROTATION + // ═══════════════════════════════════════════════════════════════════ + + /** + * Compute yaw angle (degrees) from current movement direction. + */ + protected float computeYawFromDirection() { + if (movementDirection == null) return 0; + return (float) Math.toDegrees(Math.atan2(-movementDirection.xCoord, movementDirection.zCoord)); + } + + /** + * Enforce locked rotation on all yaw fields. + * Sets rotationYaw, rotationYawHead, prevRotationYaw, prevRotationYawHead, + * renderYawOffset, and prevRenderYawOffset to lockedYaw. + */ + protected void enforceLockedRotation(EntityLivingBase caster) { + caster.rotationYaw = lockedYaw; + caster.rotationYawHead = lockedYaw; + caster.prevRotationYaw = lockedYaw; + caster.prevRotationYawHead = lockedYaw; + caster.renderYawOffset = lockedYaw; + caster.prevRenderYawOffset = lockedYaw; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 96881cf4e..42f24757e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -2,52 +2,37 @@ package kamkeel.npcs.controllers.data.ability.type; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityOrb; +import noppes.npcs.client.gui.builder.FieldDef; import java.util.Arrays; import java.util.List; -import noppes.npcs.entity.EntityNPCInterface; /** - * Orb ability: Spawns a homing projectile sphere that tracks target. - * The EntityAbilityOrb handles all movement, collision, and damage logic. - * This ability just configures and spawns the orb entity. + * Orb ability: Spawns homing projectile sphere(s) that track target. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ -public class AbilityOrb extends Ability implements IAbilityOrb { +public class AbilityOrb extends AbstractEnergyProjectileAbility implements IAbilityOrb { - // Ability-specific properties private float orbSize = 1.0f; - // Data classes for energy properties - private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - private final EnergyCombatData combatData = new EnergyCombatData(); - private final EnergyDisplayData displayData = new EnergyDisplayData(); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - // Transient state for orb entity (used during windup charging) - private transient EntityAbilityOrb orbEntity = null; - public AbilityOrb() { + super( + new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f), + new EnergyCombatData(), + new EnergyHomingData(), + new EnergyLifespanData() + ); this.typeId = "ability.cnpc.orb"; this.name = "Orb"; this.targetingMode = TargetingMode.AGGRO_TARGET; @@ -58,416 +43,134 @@ public class AbilityOrb extends Ability implements IAbilityOrb { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animation this.windUpAnimationName = "Ability_Orb_Windup"; this.activeAnimationName = "Ability_Orb_Active"; } + // ==================== ABSTRACT IMPLEMENTATIONS ==================== + @Override - public boolean isTargetingModeLocked() { - return true; + protected EntityAbilityOrb createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index) { + return new EntityAbilityOrb( + caster.worldObj, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); } @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start moving the orb that was spawned during windup - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.startMoving(target); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - displayData, combatData, homingData, lightningData, lifespanData, trajectoryData); - orbEntity.setupCharging(anchorData, windUpTicks); - - orbEntity.setEffects(this.effects); - orbEntity.setSourceAbility(this); - world.spawnEntityInWorld(orbEntity); + protected void fireEntity(EntityAbilityOrb orb, EntityLivingBase target) { + if (isPreview()) { + orb.startPreviewFiring(); + } else { + orb.startMoving(target); } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (orbEntity == null || orbEntity.isDead) { - orbEntity = null; - signalCompletion(); - } + protected void setupEntityCharging(EntityAbilityOrb orb, ProjectileData projData, int index) { + orb.setupCharging(projData.anchor, windUpTicks); } @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - // Nothing to clean up - entity manages itself + protected void setupEntityPreview(EntityAbilityOrb orb, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index) { + orb.setupPreview(caster, orbSize, resolved, lightningData, projData.anchor, windUpTicks); } @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); + protected EntityAbilityOrb[] createEntityArray(int size) { + return new EntityAbilityOrb[size]; } @Override - public void cleanup() { - // Despawn orb entity if still alive - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - orbEntity = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create small circle telegraph at target position - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { + protected float getProjectileTelegraphRadius() { return orbSize * 1.5f; } + // ==================== VARIANTS ==================== + @Override - public void writeTypeNBT(NBTTagCompound nbt) { + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Orb"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Dual Orb"); + orb.setProjectileCount(2); + orb.setFireDelay(5); + a.setWindUpAnimationName("Ability_OrbDual_Windup"); + a.setActiveAnimationName("Ability_OrbDual_Active"); + }), + new AbilityVariant("ability.variant.barrage", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Orb Barrage"); + orb.setOrbSize(0.5f); + orb.setDamage(4.0f); + orb.setKnockback(0.0f); + orb.setKnockbackUp(0.0f); + a.setMaxRange(75.0f); + a.setBurstEnabled(true); + a.setBurstAmount(15); + a.setBurstDelay(5); + a.setBurstReplayAnimations(false); + a.setBurstOverlap(true); + a.setWindUpAnimationName("Ability_OrbBarrage_Windup"); + a.setActiveAnimationName("Ability_OrbBarrage_Active"); + }) + ); + } + + // ==================== TYPE-SPECIFIC NBT ==================== + + @Override + protected void writeTypeSpecificNBT(NBTTagCompound nbt) { nbt.setFloat("orbSize", orbSize); - anchorData.writeNBT(nbt); - combatData.writeNBT(nbt); - displayData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - trajectoryData.writeNBT(nbt); - // Backward compat: old key was "orbSpeed" - nbt.setFloat("orbSpeed", homingData.speed); } @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - anchorData.readNBT(nbt); - combatData.readNBT(nbt); - displayData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); - trajectoryData.readNBT(nbt); - // Backward compat: old key was "orbSpeed" - if (nbt.hasKey("orbSpeed")) { - homingData.speed = nbt.getFloat("orbSpeed"); - } + protected void readTypeSpecificNBT(NBTTagCompound nbt) { + this.orbSize = nbt.getFloat("orbSize"); } - // Getters & Setters - public float getOrbSpeed() { - return homingData.speed; - } + // ==================== TYPE-SPECIFIC GETTERS ==================== - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } + public float getOrbSpeed() { return homingData.speed; } + public void setOrbSpeed(float speed) { homingData.speed = speed; } - public float getOrbSize() { - return orbSize; - } + public float getOrbSize() { return orbSize; } + public void setOrbSize(float size) { this.orbSize = size; } - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - public int getInnerColor() { - return displayData.innerColor; - } - - public void setInnerColor(int innerColor) { - displayData.innerColor = innerColor; - } - - public int getOuterColor() { - return displayData.outerColor; - } - - public void setOuterColor(int outerColor) { - displayData.outerColor = outerColor; - } - - public float getOuterColorWidth() { - return displayData.outerColorWidth; - } - - public void setOuterColorWidth(float outerColorWidth) { - displayData.outerColorWidth = outerColorWidth; - } - - public float getOuterColorAlpha() { - return displayData.outerColorAlpha; - } - - public void setOuterColorAlpha(float outerColorAlpha) { - displayData.outerColorAlpha = outerColorAlpha; - } - - public boolean isOuterColorEnabled() { - return displayData.outerColorEnabled; - } - - public void setOuterColorEnabled(boolean outerColorEnabled) { - displayData.outerColorEnabled = outerColorEnabled; - } - - public float getRotationSpeed() { - return displayData.rotationSpeed; - } - - public void setRotationSpeed(float rotationSpeed) { - displayData.rotationSpeed = rotationSpeed; - } - - public boolean hasLightningEffect() { - return lightningData.lightningEffect; - } - - public void setLightningEffect(boolean lightningEffect) { - lightningData.lightningEffect = lightningEffect; - } - - public float getLightningDensity() { - return lightningData.lightningDensity; - } - - public void setLightningDensity(float lightningDensity) { - lightningData.lightningDensity = lightningDensity; - } - - public float getLightningRadius() { - return lightningData.lightningRadius; - } - - public void setLightningRadius(float lightningRadius) { - lightningData.lightningRadius = lightningRadius; - } - - public int getLightningFadeTime() { - return lightningData.lightningFadeTime; - } - - public void setLightningFadeTime(int lightningFadeTime) { - lightningData.lightningFadeTime = lightningFadeTime; - } - - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - - public int getAnchorPoint() { - return anchorData.anchorPoint.ordinal(); - } - - @Override - public void setAnchorPoint(int point) { - this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); - } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, displayData, lightningData, anchorData, windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } + // ==================== TYPE-SPECIFIC GUI ==================== @SideOnly(Side.CLIENT) @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed).tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") + protected void addTypeDefinitions(List defs) { + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) )); + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) + )); + defs.add(FieldDef.row( + FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java deleted file mode 100644 index 71be07a34..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbBarrage.java +++ /dev/null @@ -1,614 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.DamageSource; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.Constants; -import noppes.npcs.client.gui.builder.FieldDef; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class AbilityOrbBarrage extends Ability { - - // Ability-specific properties - private float orbSize = 0.5f; - private int orbAmount = 16; - private int firingSpeed = 2; - private boolean dualCharging = true; - - // Data classes for energy properties - private final EnergyDisplayData colorData = new EnergyDisplayData(); - private final EnergyCombatData combatData = new EnergyCombatData(4.0f, 0.0f, 0.0f, false, 1.5f, 0.5f); - private final EnergyHomingData homingData = new EnergyHomingData(); - private final EnergyLightningData lightningData = new EnergyLightningData(); - private final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); - - - // Array to store entities - private transient List orbEntities = new ArrayList<>(); - private transient EntityAbilityOrb[] chargingEntities = null; - - // Field to keep track of the currently firing orb - private int currentOrb = 0; - - public AbilityOrbBarrage() { - this.typeId = "ability.cnpc.orb_barrage"; - this.name = "Orb Barrage"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 75.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 30; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animation - this.windUpAnimationName = "Ability_BeamDual_Windup"; - this.activeAnimationName = "Ability_BeamDual_Active"; - } - -// @Override -// @SideOnly(Side.CLIENT) -// public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { -// return new SubGuiAbilityOrbBarrage(this, callback); -// } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - for (int i = 0; i < chargingEntities.length; i++) { - EntityAbilityOrb orbEntity = chargingEntities[i]; - - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - - chargingEntities[i] = null; - } - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup - - if (dualCharging) { - chargingEntities = new EntityAbilityOrb[2]; - } else { - chargingEntities = new EntityAbilityOrb[1]; - } - - for (int i = 0; i < chargingEntities.length; i++) { - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[i]); - - EntityAbilityOrb orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - colorData, combatData, homingData, lightningData, lifespanData, trajectoryData - ); - - orbEntity.setupCharging(anchorData[i], windUpTicks); - orbEntity.setSourceAbility(this); - - chargingEntities[i] = orbEntity; - world.spawnEntityInWorld(orbEntity); - } - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (!orbEntities.isEmpty()) { - boolean allDead = true; - - for (EntityAbilityOrb orbEntity : orbEntities) { - if (orbEntity != null && !orbEntity.isDead) { - allDead = false; - break; - } - } - - if (allDead && currentOrb >= orbAmount) { - signalCompletion(); - return; - } - } - - if (currentOrb >= orbAmount) { - return; - } - - int ticksPerOrb = Math.max(1, 20 / firingSpeed); - - if (tick % ticksPerOrb != 0) { - return; - } - - EnergyAnchorData anchor; - - if (dualCharging) { - anchor = anchorData[currentOrb % 2]; - } else { - anchor = anchorData[0]; - } - - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchor); - - EntityAbilityOrb orb = new EntityAbilityOrb( - world, caster, target, spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - orbSize, colorData, combatData, homingData, lightningData, lifespanData, trajectoryData - ); - - orb.setSourceAbility(this); - world.spawnEntityInWorld(orb); - - orbEntities.add(orb); - currentOrb++; - } - - @Override - public boolean canInterrupt(DamageSource source) { - // Can be interrupted if the caster is hit when the beam is moving - if (!interruptible) { - return false; - } - - // Only direct physical hits can interrupt, not magic, fire, or other indirect damage - if (source == null) { - return false; - } - - // Reject indirect damage types - if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) { - return false; - } - - // Reject damage without a direct attacker entity - if (source.getEntity() == null) { - return false; - } - - // Direct hit from an entity - can interrupt - return true; - } - - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - currentOrb = 0; - - if (chargingEntities != null) { - for (int i = 0; i < chargingEntities.length; i++) { - if (chargingEntities[i] != null && !chargingEntities[i].isDead) { - chargingEntities[i].setDead(); - } - chargingEntities[i] = null; - } - chargingEntities = null; - } - - if (orbEntities != null && !orbEntities.isEmpty()) { - for (EntityAbilityOrb orbEntity : orbEntities) { - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - } - orbEntities.clear(); - } - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create small circle telegraph at target position - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return orbSize * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("orbSize", orbSize); - nbt.setInteger("orbAmount", orbAmount); - nbt.setInteger("firingSpeed", firingSpeed); - nbt.setBoolean("dualCharging", dualCharging); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - trajectoryData.writeNBT(nbt); - - for (int i = 0; i < anchorData.length; i++) { - NBTTagCompound comp = new NBTTagCompound(); - anchorData[i].writeNBT(comp); - nbt.setTag("Anchor_" + i, comp); - } - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - this.orbAmount = nbt.hasKey("orbAmount") ? nbt.getInteger("orbAmount") : 16; - this.firingSpeed = nbt.hasKey("firingSpeed") ? nbt.getInteger("firingSpeed") : 2; - this.dualCharging = !nbt.hasKey("dualCharging") || nbt.getBoolean("dualCharging"); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); - trajectoryData.readNBT(nbt); - - for (int i = 0; i < anchorData.length; i++) { - if (nbt.hasKey("Anchor_" + i, Constants.NBT.TAG_COMPOUND)) { - anchorData[i].readNBT(nbt.getCompoundTag("Anchor_" + i)); - } else { - anchorData[i] = new EnergyAnchorData(i == 0 ? AnchorPoint.RIGHT_HAND : AnchorPoint.LEFT_HAND); - } - } - } - - // Getters & Setters - public float getOrbSpeed() { - return homingData.speed; - } - - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } - - public float getOrbSize() { - return orbSize; - } - - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public int getOrbAmount() { return orbAmount; } - - public void setOrbAmount(int orbAmount) { this.orbAmount = orbAmount; } - - public int getFiringSpeed() { return firingSpeed; } - - public void setFiringSpeed(int firingSpeed) { this.firingSpeed = firingSpeed; } - - public boolean isDualCharging() { return dualCharging; } - - public void setDualCharging(boolean dualCharging) { this.dualCharging = dualCharging; } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - public int getInnerColor() { - return colorData.innerColor; - } - - public void setInnerColor(int innerColor) { - colorData.innerColor = innerColor; - } - - public int getOuterColor() { - return colorData.outerColor; - } - - public void setOuterColor(int outerColor) { - colorData.outerColor = outerColor; - } - - public float getOuterColorWidth() { - return colorData.outerColorWidth; - } - - public void setOuterColorWidth(float outerColorWidth) { - colorData.outerColorWidth = outerColorWidth; - } - - public float getOuterColorAlpha() { - return colorData.outerColorAlpha; - } - - public void setOuterColorAlpha(float outerColorAlpha) { - colorData.outerColorAlpha = outerColorAlpha; - } - - public boolean isOuterColorEnabled() { - return colorData.outerColorEnabled; - } - - public void setOuterColorEnabled(boolean outerColorEnabled) { - colorData.outerColorEnabled = outerColorEnabled; - } - - public float getRotationSpeed() { - return colorData.rotationSpeed; - } - - public void setRotationSpeed(float rotationSpeed) { - colorData.rotationSpeed = rotationSpeed; - } - - public boolean hasLightningEffect() { - return lightningData.lightningEffect; - } - - public void setLightningEffect(boolean lightningEffect) { - lightningData.lightningEffect = lightningEffect; - } - - public float getLightningDensity() { - return lightningData.lightningDensity; - } - - public void setLightningDensity(float lightningDensity) { - lightningData.lightningDensity = lightningDensity; - } - - public float getLightningRadius() { - return lightningData.lightningRadius; - } - - public void setLightningRadius(float lightningRadius) { - lightningData.lightningRadius = lightningRadius; - } - - public int getLightningFadeTime() { - return lightningData.lightningFadeTime; - } - - public void setLightningFadeTime(int lightningFadeTime) { - lightningData.lightningFadeTime = lightningFadeTime; - } - - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, colorData, lightningData, anchorData[0], windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.barrage"), - FieldDef.row( - FieldDef.intField("ability.amount", this::getOrbAmount, this::setOrbAmount), - FieldDef.intField("ability.firingSpeed", this::getFiringSpeed, this::setFiringSpeed) - ), - FieldDef.boolField("ability.dualCharge", this::isDualCharging, this::setDualCharging), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - - - // Visual tab - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) - .tab("ability.tab.visual"), - FieldDef.section("ability.section.colors").tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) - .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) - .visibleWhen(this::isOuterColorEnabled), - FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) - .range(0, 1).visibleWhen(this::isOuterColorEnabled) - ).tab("ability.tab.visual"), - FieldDef.section("ability.section.effects").tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed).tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) - .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), - FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) - .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) - ).tab("ability.tab.visual") - )); - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java deleted file mode 100644 index bd2870438..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrbDual.java +++ /dev/null @@ -1,586 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.util.ValueUtil; - -import java.util.Arrays; -import java.util.List; - -public class AbilityOrbDual extends Ability { - // Ability-specific properties - private float orbSize = 1.0f; - private boolean dualFire= true; - private int dualFireDelay = 5; - - // Data classes for energy properties - public final EnergyDisplayData[] displayData = new EnergyDisplayData[]{ - new EnergyDisplayData(), new EnergyDisplayData() - }; - public final EnergyCombatData combatData = new EnergyCombatData(); - public final EnergyHomingData homingData = new EnergyHomingData(); - public final EnergyLightningData[] lightningData = new EnergyLightningData[]{ - new EnergyLightningData(), new EnergyLightningData() - }; - public final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private final EnergyAnchorData[] anchorData = new EnergyAnchorData[]{ - new EnergyAnchorData(AnchorPoint.RIGHT_HAND), new EnergyAnchorData(AnchorPoint.LEFT_HAND) - }; - private EnergyTrajectoryData[] trajectoryData = new EnergyTrajectoryData[]{ - new EnergyTrajectoryData(), new EnergyTrajectoryData() - }; - - // Transient state for orb entity (used during windup charging) - private transient EntityAbilityOrb orbEntity = null; - private transient EntityAbilityOrb orbEntity2 = null; - - public AbilityOrbDual() { - this.typeId = "ability.cnpc.orb_dual"; - this.name = "Orb Dual"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 25.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 30; - this.lockMovement = LockMovementType.WINDUP; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animation - this.windUpAnimationName = "Ability_OrbDual_Windup"; - this.activeAnimationName = "Ability_OrbDual_Active"; - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start moving the orb that was spawned during windup - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.startMoving(target); - } - - if (dualFire) { - if (orbEntity2 != null && !orbEntity2.isDead && dualFireDelay <= 0) { - orbEntity2.startMoving(target); - } - } else if (orbEntity2 != null) { - orbEntity2.setDead(); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn orb in charging mode on first tick of windup - if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos1 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[0]); - orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos1.xCoord, spawnPos1.yCoord, spawnPos1.zCoord, orbSize, - displayData[0], combatData, homingData, lightningData[0], lifespanData, trajectoryData[0]); - - Vec3 spawnPos2 = AnchorPointHelper.calculateAnchorPosition(caster, anchorData[1]); - orbEntity2 = new EntityAbilityOrb( - world, caster, target, - spawnPos2.xCoord, spawnPos2.yCoord, spawnPos2.zCoord, orbSize, - displayData[1], combatData, homingData, lightningData[1], lifespanData, trajectoryData[1]); - - orbEntity.setSiblingEntityId(orbEntity2.getEntityId()); - orbEntity2.setSiblingEntityId(orbEntity.getEntityId()); - - orbEntity.setupCharging(anchorData[0], windUpTicks); - orbEntity2.setupCharging(anchorData[1], windUpTicks); - - orbEntity.setEffects(this.effects); - - if (dualFire) { - orbEntity2.setEffects(this.effects); - } - - orbEntity.setSourceAbility(this); - orbEntity2.setSourceAbility(this); - world.spawnEntityInWorld(orbEntity); - world.spawnEntityInWorld(orbEntity2); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (dualFire) { - if ((orbEntity == null || orbEntity.isDead) && (orbEntity2 == null || orbEntity2.isDead)) { - orbEntity = null; - orbEntity2 = null; - signalCompletion(); - } - - if (tick == dualFireDelay && orbEntity2 != null && !orbEntity2.isDead) { - orbEntity2.startMoving(target); - } - } else { - if (orbEntity == null || orbEntity.isDead) { - orbEntity = null; - signalCompletion(); - } - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { - cleanup(); - } - - @Override - public void cleanup() { - // Despawn orb entity if still alive - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); - } - - if (orbEntity2 != null && !orbEntity2.isDead) { - orbEntity2.setDead(); - } - - orbEntity = null; - orbEntity2 = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create small circle telegraph at target position - Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return orbSize * 1.5f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("orbSize", orbSize); - nbt.setBoolean("dualFire", dualFire); - nbt.setInteger("dualFireDelay", dualFireDelay); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - // Backward compat: old key was "orbSpeed" - nbt.setFloat("orbSpeed", homingData.speed); - - NBTTagCompound orb1 = new NBTTagCompound(); - NBTTagCompound orb2 = new NBTTagCompound(); - - for (int i = 0; i < 2; i++) { - NBTTagCompound orb = i == 0 ? orb1 : orb2; - anchorData[i].writeNBT(orb); - displayData[i].writeNBT(orb); - lightningData[i].writeNBT(orb); - trajectoryData[i].writeNBT(orb); - } - - nbt.setTag("Orb_1", orb1); - nbt.setTag("Orb_2", orb2); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - NBTTagCompound orb1 = nbt.hasKey("Orb_1") ? nbt.getCompoundTag("Orb_1") : new NBTTagCompound(); - NBTTagCompound orb2 = nbt.hasKey("Orb_2") ? nbt.getCompoundTag("Orb_2") : new NBTTagCompound(); - - this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - this.dualFire = !nbt.hasKey("dualFire") || nbt.getBoolean("dualFire"); - this.dualFireDelay = nbt.hasKey("dualFireDelay") ? nbt.getInteger("dualFireDelay") : 0; - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lifespanData.readNBT(nbt); - // Backward compat: old key was "orbSpeed" - if (nbt.hasKey("orbSpeed")) { - homingData.speed = nbt.getFloat("orbSpeed"); - } - - for (int i = 0; i < 2; i++) { - NBTTagCompound orb = i == 0 ? orb1 : orb2; - anchorData[i].readNBT(orb); - displayData[i].readNBT(orb); - lightningData[i].readNBT(orb); - trajectoryData[i].readNBT(orb); - } - } - - // Getters & Setters - private EnergyDisplayData getColorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return displayData[orb]; - } - private EnergyLightningData getLightningData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return lightningData[orb]; - } - private EnergyAnchorData getAnchorData(int orb) { - orb = ValueUtil.clamp(orb, 0, 1); - return anchorData[orb]; - } - - public float getOrbSpeed() { - return homingData.speed; - } - - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; - } - - public float getOrbSize() { - return orbSize; - } - - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public boolean isDualFire() { - return dualFire; - } - - public void setDualFire(boolean dualFire) { - this.dualFire = dualFire; - } - - public int getDualFireDelay() { - return dualFireDelay; - } - - public void setDualFireDelay(int dualFireDelay) { - this.dualFireDelay = dualFireDelay; - } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - - public int getInnerColor(int orb) { return getColorData(orb).innerColor; } - public void setInnerColor(int orb, int innerColor) { getColorData(orb).innerColor = innerColor; } - public int getOuterColor(int orb) { return getColorData(orb).outerColor; } - public void setOuterColor(int orb, int outerColor) { getColorData(orb).outerColor = outerColor; } - public boolean isOuterColorEnabled(int orb) { return getColorData(orb).outerColorEnabled; } - public void setOuterColorEnabled(int orb, boolean enabled) { getColorData(orb).outerColorEnabled = enabled; } - public float getOuterColorWidth(int orb) { return getColorData(orb).outerColorWidth; } - public void setOuterColorWidth(int orb, float width) { getColorData(orb).outerColorWidth = width; } - public float getOuterColorAlpha(int orb) { return getColorData(orb).outerColorAlpha; } - public void setOuterColorAlpha(int orb, float alpha) { getColorData(orb).outerColorAlpha = alpha; } - public float getRotationSpeed(int orb) { return getColorData(orb).rotationSpeed; } - public void setRotationSpeed(int orb, float speed) { getColorData(orb).rotationSpeed = speed; } - - public int getInnerColor() { return getInnerColor(0); } - public void setInnerColor(int innerColor) { setInnerColor(0, innerColor); } - public int getOuterColor() { return getOuterColor(0); } - public void setOuterColor(int outerColor) { setOuterColor(0, outerColor); } - public boolean isOuterColorEnabled() { return isOuterColorEnabled(0); } - public void setOuterColorEnabled(boolean enabled) { setOuterColorEnabled(0, enabled); } - public float getOuterColorWidth() { return getOuterColorWidth(0); } - public void setOuterColorWidth(float width) { setOuterColorWidth(0, width); } - public float getOuterColorAlpha() { return getOuterColorAlpha(0); } - public void setOuterColorAlpha(float alpha) { setOuterColorAlpha(0, alpha); } - public float getRotationSpeed() { return getRotationSpeed(0); } - public void setRotationSpeed(float speed) { setRotationSpeed(0, speed); } - - - public boolean hasLightningEffect(int orb) { return getLightningData(orb).lightningEffect; } - public void setLightningEffect(int orb, boolean lightningEffect) { getLightningData(orb).lightningEffect = lightningEffect; } - public float getLightningDensity(int orb) { return getLightningData(orb).lightningDensity; } - public void setLightningDensity(int orb, float lightningDensity) { getLightningData(orb).lightningDensity = lightningDensity; } - public float getLightningRadius(int orb) { return getLightningData(orb).lightningRadius; } - public void setLightningRadius(int orb, float lightningRadius) { getLightningData(orb).lightningRadius = lightningRadius; } - - public boolean hasLightningEffect() { return hasLightningEffect(0); } - public void setLightningEffect(boolean lightningEffect) { setLightningEffect(0, lightningEffect); } - public float getLightningDensity() { return getLightningDensity(0); } - public void setLightningDensity(float lightningDensity) { setLightningDensity(0, lightningDensity); } - public float getLightningRadius() { return getLightningRadius(0); } - public void setLightningRadius(float lightningRadius) { setLightningRadius(0, lightningRadius); } - - - public AnchorPoint getAnchorPointEnum(int orb) { return getAnchorData(orb).anchorPoint; } - public void setAnchorPointEnum(int orb, AnchorPoint anchorPoint) { getAnchorData(orb).anchorPoint = anchorPoint; } - public float getAnchorOffsetX(int orb) { return getAnchorData(orb).anchorOffsetX; } - public void setAnchorOffsetX(int orb, float x) { getAnchorData(orb).anchorOffsetX = x; } - public float getAnchorOffsetY(int orb) { return getAnchorData(orb).anchorOffsetY; } - public void setAnchorOffsetY(int orb, float y) { getAnchorData(orb).anchorOffsetY = y; } - public float getAnchorOffsetZ(int orb) { return getAnchorData(orb).anchorOffsetZ; } - public void setAnchorOffsetZ(int orb, float z) { getAnchorData(orb).anchorOffsetZ = z; } - - public AnchorPoint getAnchorPointEnum() { return getAnchorPointEnum(0); } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { setAnchorPointEnum(0, anchorPoint); } - public float getAnchorOffsetX() { return getAnchorOffsetX(0); } - public void setAnchorOffsetX(float x) { setAnchorOffsetX(0, x); } - public float getAnchorOffsetY() { return getAnchorOffsetY(0); } - public void setAnchorOffsetY(float y) { setAnchorOffsetY(0, y); } - public float getAnchorOffsetZ() { return getAnchorOffsetZ(0); } - public void setAnchorOffsetZ(float z) { setAnchorOffsetZ(0, z); } - - //@Override - public int getAnchorPoint(int orb) { return getAnchorData(orb).anchorPoint.ordinal(); } - public int getAnchorPoint() { return getAnchorData(0).anchorPoint.ordinal(); } - - //@Override - public void setAnchorPoint(int orb, int point) { getAnchorData(orb).anchorPoint = AnchorPoint.fromOrdinal(point); } - public void setAnchorPoint(int point) { getAnchorData(0).anchorPoint = AnchorPoint.fromOrdinal(point); } - - @SideOnly(Side.CLIENT) - @Override - public void getAbilityDefinitions(List defs) { - defs.addAll(Arrays.asList( - // Type tab - FieldDef.row( - FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), - FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) - ), - FieldDef.row( - FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), - FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) - ), - FieldDef.row( - FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), - FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) - ), - FieldDef.section("ability.section.dual"), - FieldDef.boolField("ability.dualFire", this::isDualFire, this::setDualFire), - FieldDef.intField("ability.dualFireDelay", this::getDualFireDelay, this::setDualFireDelay) - .visibleWhen(this::isDualFire), - FieldDef.section("ability.section.homing"), - FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), - FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), - FieldDef.section("ability.section.explosive"), - FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), - FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), - AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), - // Visual tab - Orb 1 - FieldDef.section("ability.section.orb1").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(0), v -> setAnchorPointEnum(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(0), v -> setInnerColor(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(0), v -> setOuterColorEnabled(0, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(0), v -> setOuterColor(0, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(0), v -> setOuterColorWidth(0, v)) - .visibleWhen(() -> isOuterColorEnabled(0)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(0), v -> setOuterColorAlpha(0, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(0)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(0), v -> setRotationSpeed(0, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(0), v -> setLightningEffect(0, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(0), v -> setLightningDensity(0, v)) - .range(0.01f, 5.0f).visibleWhen(() -> hasLightningEffect(0)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(0), v -> setLightningRadius(0, v)) - .range(0.1f, 10.0f).visibleWhen(() -> hasLightningEffect(0)) - ).tab("ability.tab.visual"), - // Visual tab - Orb 2 - FieldDef.section("ability.section.orb2").tab("ability.tab.visual"), - FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, - () -> getAnchorPointEnum(1), v -> setAnchorPointEnum(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.innerColor", - () -> getInnerColor(1), v -> setInnerColor(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.outerEnabled", - () -> isOuterColorEnabled(1), v -> setOuterColorEnabled(1, v)) - .tab("ability.tab.visual"), - FieldDef.colorSubGui("ability.outerColor", - () -> getOuterColor(1), v -> setOuterColor(1, v)) - .tab("ability.tab.visual").visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.row( - FieldDef.floatField("ability.outerWidth", - () -> getOuterColorWidth(1), v -> setOuterColorWidth(1, v)) - .visibleWhen(() -> isOuterColorEnabled(1)), - FieldDef.floatField("ability.outerAlpha", - () -> getOuterColorAlpha(1), v -> setOuterColorAlpha(1, v)) - .range(0, 1).visibleWhen(() -> isOuterColorEnabled(1)) - ).tab("ability.tab.visual"), - FieldDef.floatField("ability.rotationSpeed", - () -> getRotationSpeed(1), v -> setRotationSpeed(1, v)) - .tab("ability.tab.visual"), - FieldDef.boolField("ability.lightning", - () -> hasLightningEffect(1), v -> setLightningEffect(1, v)) - .tab("ability.tab.visual"), - FieldDef.row( - FieldDef.floatField("gui.density", - () -> getLightningDensity(1), v -> setLightningDensity(1, v)) - .range(0.01f, 100f).visibleWhen(() -> hasLightningEffect(1)), - FieldDef.floatField("gui.radius", - () -> getLightningRadius(1), v -> setLightningRadius(1, v)) - .range(0.1f, 100f).visibleWhen(() -> hasLightningEffect(1)) - ).tab("ability.tab.visual") - )); - } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, displayData[0], lightningData[0], anchorData[0], windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index e5f6f5df6..46242fc71 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -9,6 +9,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.entity.EntityNPCInterface; @@ -50,6 +51,11 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { this.showTelegraph = false; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -61,62 +67,130 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote || target == null) return; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (caster.worldObj.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (isPlayerCaster(caster)) { + // Player: instant hit-scan in look direction + executePlayerProjectile(caster, caster.worldObj); + } else if (target != null) { + // NPC: instant hit-scan on aggro target + executeNpcProjectile(caster, target, caster.worldObj); + } + + signalCompletion(); + } + + /** + * NPC projectile: instant hit-scan damage on the aggro target. + */ + private void executeNpcProjectile(EntityLivingBase caster, EntityLivingBase target, World world) { + if (isPreview()) return; - // Calculate direction to target double dx = target.posX - caster.posX; double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); double dz = target.posZ - caster.posZ; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { dx /= len; dy /= len; dz /= len; } - if (len > 0) { - dx /= len; - dy /= len; - dz /= len; - } - - // Deal instant damage with scripted event support - // TODO: Use custom EntityAbilityProjectile for actual tracking applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); - - // Play sound world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); - // Handle splash damage for explosive projectiles if (explosive && explosionRadius > 0) { - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity(target, - target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + applyExplosionDamage(caster, target, world, target.posX, target.posY, target.posZ); + } - for (Entity entity : entities) { - if (entity instanceof EntityLivingBase && entity != caster) { - EntityLivingBase living = (EntityLivingBase) entity; - float dist = target.getDistanceToEntity(living); - if (dist < explosionRadius) { - float falloff = 1.0f - (dist / explosionRadius); - // Apply splash damage with scripted event support (no knockback) - applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); - } - } - } + spawnProjectileParticles(world, caster, target); + } - // Explosion particles - world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f); - for (int i = 0; i < 10; i++) { - world.spawnParticle("explode", - target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius, - target.posY + world.rand.nextDouble() * target.height, - target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius, - 0, 0.1, 0); + /** + * Player projectile: fires instant hit-scan in look direction. + * Raycasts for the first entity in range and applies damage. + */ + private void executePlayerProjectile(EntityLivingBase caster, World world) { + if (isPreview()) return; + + Vec3 look = caster.getLookVec(); + double eyeX = caster.posX; + double eyeY = caster.posY + caster.getEyeHeight(); + double eyeZ = caster.posZ; + + // Raycast: find the closest entity along look direction + EntityLivingBase hitTarget = null; + double closestDist = maxRange; + + @SuppressWarnings("unchecked") + List candidates = world.getEntitiesWithinAABBExcludingEntity(caster, + caster.boundingBox.expand(maxRange, maxRange, maxRange)); + + for (Entity entity : candidates) { + if (!(entity instanceof EntityLivingBase)) continue; + if (entity.isDead) continue; + + // Check if entity is roughly along look direction + double dx = entity.posX - eyeX; + double dy = (entity.posY + entity.height / 2) - eyeY; + double dz = entity.posZ - eyeZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist > maxRange || dist < 0.5) continue; + + // Dot product to check alignment with look vector + double dot = (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) / dist; + if (dot < 0.95) continue; // Must be within ~18 degree cone + + if (dist < closestDist) { + closestDist = dist; + hitTarget = (EntityLivingBase) entity; } } - // Spawn projectile particles (visual trail) - spawnProjectileParticles(world, caster, target); + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); - // Projectile is instant - signalCompletion(); + if (hitTarget != null) { + applyAbilityDamageWithDirection(caster, hitTarget, damage, knockback, look.xCoord, look.zCoord); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, hitTarget, world, hitTarget.posX, hitTarget.posY, hitTarget.posZ); + } + + spawnProjectileParticles(world, caster, hitTarget); + } else { + // No hit — spawn particles along look direction anyway + spawnProjectileParticlesInDirection(world, caster, look); + } + } + + /** + * Apply explosion splash damage around a point. + */ + private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world, + double x, double y, double z) { + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget, + primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + + for (Entity entity : entities) { + if (entity instanceof EntityLivingBase && entity != caster) { + EntityLivingBase living = (EntityLivingBase) entity; + float dist = primaryTarget.getDistanceToEntity(living); + if (dist < explosionRadius) { + float falloff = 1.0f - (dist / explosionRadius); + applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + } + } + } + + world.playSoundAtEntity(primaryTarget, "random.explode", 0.5f, 1.0f); + for (int i = 0; i < 10; i++) { + world.spawnParticle("explode", + x + (world.rand.nextDouble() - 0.5) * explosionRadius, + y + world.rand.nextDouble() * 2, + z + (world.rand.nextDouble() - 0.5) * explosionRadius, + 0, 0.1, 0); + } } private void spawnProjectileParticles(World world, EntityLivingBase caster, EntityLivingBase target) { @@ -150,8 +224,33 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } } + /** + * Spawn projectile particles along a direction (player miss — no entity hit). + */ + private void spawnProjectileParticlesInDirection(World world, EntityLivingBase caster, Vec3 look) { + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + + String particle = "flame"; + if (projectileType.equals("arrow")) { + particle = "crit"; + } else if (projectileType.equals("magic")) { + particle = "witchMagic"; + } + + int steps = (int) Math.max(5, maxRange * 2); + for (int i = 0; i < steps; i++) { + double progress = (double) i / steps * maxRange; + double px = startX + look.xCoord * progress; + double py = startY + look.yCoord * progress; + double pz = startZ + look.zCoord * progress; + world.spawnParticle(particle, px, py, pz, 0, 0, 0); + } + } + @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Projectile is instant, nothing to do per-tick } @@ -174,14 +273,14 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.speed = nbt.hasKey("speed") ? nbt.getFloat("speed") : 1.5f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.projectileType = nbt.hasKey("projectileType") ? nbt.getString("projectileType") : "fireball"; - this.explosive = nbt.hasKey("explosive") && nbt.getBoolean("explosive"); - this.explosionRadius = nbt.hasKey("explosionRadius") ? nbt.getFloat("explosionRadius") : 0.0f; - this.homing = nbt.hasKey("homing") && nbt.getBoolean("homing"); - this.homingStrength = nbt.hasKey("homingStrength") ? nbt.getFloat("homingStrength") : 0.1f; + this.damage = nbt.getFloat("damage"); + this.speed = nbt.getFloat("speed"); + this.knockback = nbt.getFloat("knockback"); + this.projectileType = nbt.getString("projectileType"); + this.explosive = nbt.getBoolean("explosive"); + this.explosionRadius = nbt.getFloat("explosionRadius"); + this.homing = nbt.getBoolean("homing"); + this.homingStrength = nbt.getFloat("homingStrength"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 775c15515..1eebdab99 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -10,7 +10,6 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; -import net.minecraft.world.World; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.client.gui.builder.FieldDef; @@ -30,12 +29,13 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { private float pushStrength = 1.5f; private float damage = 8.0f; private int maxTargets = 10; + private int activeDisplayTicks = 10; public AbilityShockwave() { this.typeId = "ability.cnpc.shockwave"; this.name = "Shockwave"; this.targetingMode = TargetingMode.AOE_SELF; - this.maxRange = 15.0f; + this.maxRange = 8.0f; this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; this.cooldownTicks = 0; this.windUpTicks = 25; @@ -62,56 +62,58 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Shockwave is instant - apply effect immediately after windup + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + if (!isPreview()) { + // Shockwave is instant - apply effect immediately after windup - // Get all entities in radius - AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + // Get all entities in radius + AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); + @SuppressWarnings("unchecked") + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist > pushRadius) continue; + double dist = caster.getDistanceToEntity(entity); + if (dist > pushRadius) continue; - count++; - if (count > maxTargets) break; + count++; + if (count > maxTargets) break; - // Calculate push direction (away from caster) - double dx = entity.posX - caster.posX; - double dz = entity.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dz * dz); + // Calculate push direction (away from caster) + double dx = entity.posX - caster.posX; + double dz = entity.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - dx /= len; - dz /= len; - } else { - // Entity is directly on top of caster, push in random direction - double angle = Math.random() * Math.PI * 2; - dx = Math.cos(angle); - dz = Math.sin(angle); - } + if (len > 0) { + dx /= len; + dz /= len; + } else { + // Entity is directly on top of caster, push in random direction + double angle = Math.random() * Math.PI * 2; + dx = Math.cos(angle); + dz = Math.sin(angle); + } - // Scale knockback by distance (closer = stronger) - float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; - float finalPush = pushStrength * distFactor; - // Apply damage with custom knockback direction - boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); + // Scale knockback by distance (closer = stronger) + float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; + float finalPush = pushStrength * distFactor; + // Apply damage with custom knockback direction + boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); - // Apply effects if hit connected - if (wasHit) { - applyEffects(entity); + // Apply effects if hit connected + if (wasHit) { + applyEffects(entity); + } } } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (tick == 10) + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (tick >= activeDisplayTicks) signalCompletion(); } @@ -121,14 +123,16 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { nbt.setFloat("pushStrength", pushStrength); nbt.setFloat("damage", damage); nbt.setInteger("maxTargets", maxTargets); + nbt.setInteger("activeDisplayTicks", activeDisplayTicks); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pushRadius = nbt.hasKey("pushRadius") ? nbt.getFloat("pushRadius") : 8.0f; - this.pushStrength = nbt.hasKey("pushStrength") ? nbt.getFloat("pushStrength") : 1.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 10; + this.pushRadius = nbt.getFloat("pushRadius"); + this.pushStrength = nbt.getFloat("pushStrength"); + this.damage = nbt.getFloat("damage"); + this.maxTargets = nbt.getInteger("maxTargets"); + this.activeDisplayTicks = nbt.hasKey("activeDisplayTicks") ? nbt.getInteger("activeDisplayTicks") : 10; } // Getters & Setters @@ -164,6 +168,14 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.maxTargets = maxTargets; } + public int getActiveDisplayTicks() { + return activeDisplayTicks; + } + + public void setActiveDisplayTicks(int activeDisplayTicks) { + this.activeDisplayTicks = activeDisplayTicks; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { @@ -175,6 +187,7 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength) ), FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets), + FieldDef.intField("ability.activeDisplayTicks", this::getActiveDisplayTicks, this::setActiveDisplayTicks).range(1, 200), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 1be741d35..f8a6559ca 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -84,49 +84,86 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Update target position during windup - if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam at caster's current position - targetX = caster.posX; - targetY = caster.posY; - targetZ = caster.posZ; - } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: telegraph follows target via setEntityIdToFollow - targetX = target.posX; - targetY = target.posY; - targetZ = target.posZ; + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (isPlayerCaster(caster)) { + // Player: update target along look direction during windup + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else { + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); + double launchDist = Math.max(4.0, maxRange * 0.5); + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; + } + } else { + // NPC: update target position during windup for telegraph tracking + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { + targetX = target.posX; + targetY = target.posY; + targetZ = target.posZ; + } } } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Lock in the destination at moment of launch + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + hasLaunched = false; + hasLanded = false; + airTicks = 0; + caster.fallDistance = 0; + + if (isPlayerCaster(caster)) { + executePlayerSlam(caster); + } else { + executeNpcSlam(caster, target); + } + } + + /** + * NPC slam: Lock destination based on targeting mode, then launch in a ballistic arc toward it. + */ + private void executeNpcSlam(EntityLivingBase caster, EntityLivingBase target) { if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam in place (just jump up) targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: leap to target's current position targetX = target.posX; targetY = target.posY; targetZ = target.posZ; } else { - // Fallback: slam in place targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } + launchTowardTarget(caster); + } - hasLaunched = false; - hasLanded = false; - airTicks = 0; + /** + * Player slam: Launch in look direction using same ballistic arc as NPC slam. + * AOE damage triggers wherever the player lands. + */ + private void executePlayerSlam(EntityLivingBase caster) { + // Calculate target position along player's look direction (horizontal only) + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double dirX = -Math.sin(yawRad); + double dirZ = Math.cos(yawRad); - // Reset fall distance to prevent fall damage during slam - caster.fallDistance = 0; + double launchDist = Math.max(4.0, maxRange * 0.5); + + targetX = caster.posX + dirX * launchDist; + targetY = caster.posY; + targetZ = caster.posZ + dirZ * launchDist; - // Calculate and apply leap velocity launchTowardTarget(caster); } @@ -187,11 +224,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.motionZ = 0; caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; - caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + if (!isPreview()) { + caster.velocityChanged = true; + caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + } return; } @@ -233,10 +272,12 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } // Face the target float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); @@ -245,34 +286,44 @@ public class AbilitySlam extends Ability implements IAbilitySlam { } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { if (!hasLaunched) return; if (hasLanded) return; airTicks++; // Continuously reset fall distance during slam to prevent fall damage - caster.fallDistance = 0; + if (!isPreview()) { + caster.fallDistance = 0; + } - // Check for landing - if (caster.onGround && airTicks > 3) { - // Landed! - onLanding(caster, world); - return; + // Check for landing: hit the ground or hit a wall mid-flight + if (airTicks > 3) { + if (caster.onGround || caster.isCollidedHorizontally) { + onLanding(caster, caster.worldObj); + return; + } } // Timeout protection - force landing after max air time if (airTicks >= maxAirTicks) { - onLanding(caster, world); + onLanding(caster, caster.worldObj); return; } - // While in air, face toward target - double dx = targetX - caster.posX; - double dz = targetZ - caster.posZ; - float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); - caster.rotationYaw = targetYaw; - caster.rotationYawHead = targetYaw; + // Face toward target destination while in air (both NPC and Player) + if (!isPreview()) { + double dx = targetX - caster.posX; + double dz = targetZ - caster.posZ; + if (dx * dx + dz * dz > 0.25) { + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + if (isPlayerCaster(caster)) { + caster.velocityChanged = true; + } + } + } } /** @@ -280,22 +331,25 @@ public class AbilitySlam extends Ability implements IAbilitySlam { */ private void onLanding(EntityLivingBase caster, World world) { hasLanded = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } // Signal that the ability has completed its active phase signalCompletion(); - // Reset fall distance to prevent fall damage on landing - caster.fallDistance = 0; - // Stop horizontal momentum caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; - if (world.isRemote) return; + if (!isPreview()) { + // Reset fall distance to prevent fall damage on landing + caster.fallDistance = 0; + caster.velocityChanged = true; + } + + if (world.isRemote && !isPreview()) return; + if (isPreview()) return; // Play slam impact sound on landing world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f); @@ -361,7 +415,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -371,7 +425,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -387,97 +441,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam { airTicks = 0; } - // ==================== PREVIEW MODE ==================== - - private transient double previewVelX, previewVelY, previewVelZ; - private transient boolean previewLaunched = false; - private transient double previewGroundY; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewLaunched = false; - - double tx, ty, tz; - if (previewTarget != null && targetingMode == TargetingMode.AOE_TARGET) { - tx = previewTarget.posX; - ty = previewTarget.posY; - tz = previewTarget.posZ; - } else { - tx = npc.posX; - ty = npc.posY; - tz = npc.posZ; - } - - previewGroundY = npc.posY; - - double dx = tx - npc.posX; - double dz = tz - npc.posZ; - double horizontalDist = Math.sqrt(dx * dx + dz * dz); - - // Calculate vertical velocity for exact leapHeight - double arcHeight = Math.max(1.0, leapHeight); - double vy = calculateLaunchVelocity(arcHeight); - - if (horizontalDist < 0.5) { - previewVelX = 0; - previewVelZ = 0; - previewVelY = vy; - } else { - if (horizontalDist > maxRange) { - double scale = maxRange / horizontalDist; - dx *= scale; - dz *= scale; - horizontalDist = maxRange; - } - - double speedFactor = Math.max(0.1, leapSpeed); - int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); - double drag = 0.91; - double dragPowN = Math.pow(drag, flightTicks); - double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN); - - double dirX = dx / horizontalDist; - double dirZ = dz / horizontalDist; - previewVelX = dirX * vHorizontal; - previewVelZ = dirZ * vHorizontal; - previewVelY = vy; - } - previewLaunched = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewLaunched) return; - - // Apply velocity - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewVelX; - npc.posY += previewVelY; - npc.posZ += previewVelZ; - - // Gravity and drag - previewVelY -= 0.08; - previewVelY *= 0.98; - previewVelX *= 0.91; - previewVelZ *= 0.91; - - // Ground clamp - stop falling below starting Y - if (npc.posY < previewGroundY && previewVelY < 0) { - npc.posY = previewGroundY; - previewVelY = 0; - previewVelX = 0; - previewVelZ = 0; - previewLaunched = false; - } - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return 60; } @@ -519,11 +484,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); - // AOE_TARGET: telegraph follows target during windup - if (targetingMode == TargetingMode.AOE_TARGET && target != null) { + // NPC AOE_TARGET: telegraph follows target during windup + // Player: telegraph stays at caster position (no target to follow) + if (!isPlayerCaster(caster) && targetingMode == TargetingMode.AOE_TARGET && target != null) { instance.setEntityIdToFollow(target.getEntityId()); } - // AOE_SELF: telegraph stays at caster position, no follow return instance; } @@ -544,11 +509,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void readTypeNBT(NBTTagCompound nbt) { - damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 10.0f; - radius = nbt.hasKey("radius") ? nbt.getFloat("radius") : 5.0f; - knockbackStrength = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 1.5f; - leapSpeed = nbt.hasKey("leapSpeed") ? nbt.getFloat("leapSpeed") : 1.0f; - leapHeight = nbt.hasKey("leapHeight") ? nbt.getFloat("leapHeight") : 4.0f; + damage = nbt.getFloat("damage"); + radius = nbt.getFloat("radius"); + knockbackStrength = nbt.getFloat("knockback"); + leapSpeed = nbt.getFloat("leapSpeed"); + leapHeight = nbt.getFloat("leapHeight"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index 2fcc62956..c7cc9a1fa 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -14,7 +14,7 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilitySweeper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + import noppes.npcs.api.ability.type.IAbilitySweeper; import java.util.Arrays; @@ -61,6 +61,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { this.showTelegraph = true; } + @Override + public boolean allowBurst() { + return false; + } + @Override public boolean isTargetingModeLocked() { return true; @@ -72,27 +77,29 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Spawn the entity that handles BOTH visuals AND damage - activeEntity = new EntityAbilitySweeper(world, caster, target, + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Spawn the sweeper entity that handles BOTH visuals AND damage. + // NPC: target is the aggro target — lockOnTarget tracks it during sweep. + // Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect. + activeEntity = new EntityAbilitySweeper(caster.worldObj, caster, target, beamLength, beamWidth, beamHeight, colorData, sweepSpeed, numberOfRotations, damage, damageInterval, piercing, lockOnTarget); - world.spawnEntityInWorld(activeEntity); + + if (isPreview()) { + activeEntity.setupPreview(caster); + } + + spawnAbilityEntity(activeEntity); // Ability stays active until entity dies (prevents firing another while projectile is alive) // Movement locking is handled separately by the base class } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { // Signal completion when entity dies if (activeEntity == null || activeEntity.isDead) { activeEntity = null; @@ -160,15 +167,15 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.beamLength = nbt.hasKey("beamLength") ? nbt.getFloat("beamLength") : 10.0f; - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.3f; - this.beamHeight = nbt.hasKey("beamHeight") ? nbt.getFloat("beamHeight") : 0.5f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageInterval = nbt.hasKey("damageInterval") ? nbt.getInteger("damageInterval") : 5; - this.piercing = !nbt.hasKey("piercing") || nbt.getBoolean("piercing"); - this.sweepSpeed = nbt.hasKey("sweepSpeed") ? nbt.getFloat("sweepSpeed") : 3.0f; - this.numberOfRotations = nbt.hasKey("numberOfRotations") ? nbt.getInteger("numberOfRotations") : 2; - this.lockOnTarget = nbt.hasKey("lockOnTarget") && nbt.getBoolean("lockOnTarget"); + this.beamLength = nbt.getFloat("beamLength"); + this.beamWidth = nbt.getFloat("beamWidth"); + this.beamHeight = nbt.getFloat("beamHeight"); + this.damage = nbt.getFloat("damage"); + this.damageInterval = nbt.getInteger("damageInterval"); + this.piercing = nbt.getBoolean("piercing"); + this.sweepSpeed = nbt.getFloat("sweepSpeed"); + this.numberOfRotations = nbt.getInteger("numberOfRotations"); + this.lockOnTarget = nbt.getBoolean("lockOnTarget"); colorData.readNBT(nbt); } @@ -200,6 +207,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } + @Override + public int getMaxPreviewDuration() { + return (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index cb06b7b6b..70228652e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.type; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -72,6 +73,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.typeId = "ability.cnpc.teleport"; this.name = "Teleport"; this.targetingMode = TargetingMode.AGGRO_TARGET; + this.allowedBy = UserType.NPC_ONLY; this.maxRange = 30.0f; this.minRange = 5.0f; this.cooldownTicks = 0; @@ -84,11 +86,6 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.activeSound = "mob.endermen.portal"; } - @Override - public boolean hasDamage() { - return false; - } - @Override public boolean isTargetingModeLocked() { return true; @@ -100,13 +97,13 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { currentBlink = 0; ticksSinceLastBlink = blinkDelayTicks; // Trigger first blink immediately } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; if (currentBlink >= blinkLimit) { signalCompletion(); @@ -116,7 +113,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { ticksSinceLastBlink++; if (ticksSinceLastBlink >= blinkDelayTicks) { - performBlink(caster, target, world); + performBlink(caster, target, caster.worldObj); currentBlink++; ticksSinceLastBlink = 0; @@ -128,7 +125,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } private void performBlink(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; double oldX = caster.posX; double oldY = caster.posY; @@ -137,36 +134,47 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { Vec3 destination = calculateDestination(caster, target, world); if (destination == null) return; - boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; - if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, - destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { - destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + if (!isPreview()) { + boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; + if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, + destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { + destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + destination.xCoord, destination.yCoord, destination.zCoord); + if (destination == null) return; + } + + destination = findSafeDestination(world, oldX, oldY, oldZ, destination.xCoord, destination.yCoord, destination.zCoord); if (destination == null) return; + + // Damage at origin + if (damageAtStart) { + dealDamageAt(caster, world, oldX, oldY, oldZ); + } + + // Spawn particles at origin + spawnTeleportParticles(world, oldX, oldY, oldZ); } - destination = findSafeDestination(world, oldX, oldY, oldZ, - destination.xCoord, destination.yCoord, destination.zCoord); - if (destination == null) return; - - // Damage at origin - if (damageAtStart) { - dealDamageAt(caster, world, oldX, oldY, oldZ); - } - - // Spawn particles at origin - spawnTeleportParticles(world, oldX, oldY, oldZ); - // Teleport - caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + if (isPreview()) { + caster.setPosition(destination.xCoord, destination.yCoord, destination.zCoord); + caster.prevPosX = destination.xCoord; + caster.prevPosY = destination.yCoord; + caster.prevPosZ = destination.zCoord; + } else { + caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + } caster.fallDistance = 0; - // Spawn particles at destination - spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); + if (!isPreview()) { + // Spawn particles at destination + spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); - // Damage at destination - if (damageAtEnd) { - dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + // Damage at destination + if (damageAtEnd) { + dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + } } // Face target after teleport @@ -217,26 +225,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } } - // No target (player use) - teleport in caster's look direction - Vec3 look = caster.getLookVec(); - switch (mode) { - case BEHIND: - // Teleport forward in look direction by behindDistance - newX = caster.posX + look.xCoord * behindDistance; - newZ = caster.posZ + look.zCoord * behindDistance; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - case SINGLE: - case BLINK: - default: - // Teleport forward in look direction within blinkRadius - double dist = Math.min(blinkRadius, maxRange); - double offset = (RANDOM.nextDouble() * 0.5 + 0.5) * dist; // 50-100% of max distance - newX = caster.posX + look.xCoord * offset; - newZ = caster.posZ + look.zCoord * offset; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - } + // NPC-only ability — should not reach here + return null; } private Vec3 findSafeDestination(World world, double oldX, double oldY, double oldZ, @@ -440,33 +430,20 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { @Override public void readTypeNBT(NBTTagCompound nbt) { - if (nbt.hasKey("mode")) { - try { - this.mode = TeleportMode.valueOf(nbt.getString("mode")); - } catch (Exception e) { - this.mode = TeleportMode.BLINK; - } - } else if (nbt.hasKey("pattern")) { - String legacy = nbt.getString("pattern"); - if ("BEHIND_TARGET".equals(legacy)) { - this.mode = TeleportMode.BEHIND; - } else if ("RANDOM".equals(legacy)) { - this.mode = TeleportMode.BLINK; - } else { - this.mode = TeleportMode.SINGLE; - } - } else { + try { + this.mode = TeleportMode.valueOf(nbt.getString("mode")); + } catch (Exception e) { this.mode = TeleportMode.BLINK; } - this.blinkCount = nbt.hasKey("blinkCount") ? nbt.getInteger("blinkCount") : 3; - this.blinkDelayTicks = nbt.hasKey("blinkDelayTicks") ? nbt.getInteger("blinkDelayTicks") : 10; - this.blinkRadius = nbt.hasKey("blinkRadius") ? nbt.getFloat("blinkRadius") : 8.0f; - this.behindDistance = nbt.hasKey("behindDistance") ? nbt.getFloat("behindDistance") : 2.0f; - this.requireLineOfSight = !nbt.hasKey("requireLineOfSight") || nbt.getBoolean("requireLineOfSight"); - this.damageAtStart = nbt.hasKey("damageAtStart") && nbt.getBoolean("damageAtStart"); - this.damageAtEnd = nbt.hasKey("damageAtEnd") && nbt.getBoolean("damageAtEnd"); - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 5.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 2.0f; + this.blinkCount = nbt.getInteger("blinkCount"); + this.blinkDelayTicks = nbt.getInteger("blinkDelayTicks"); + this.blinkRadius = nbt.getFloat("blinkRadius"); + this.behindDistance = nbt.getFloat("behindDistance"); + this.requireLineOfSight = nbt.getBoolean("requireLineOfSight"); + this.damageAtStart = nbt.getBoolean("damageAtStart"); + this.damageAtEnd = nbt.getBoolean("damageAtEnd"); + this.damage = nbt.getFloat("damage"); + this.damageRadius = nbt.getFloat("damageRadius"); } // Getters & Setters @@ -561,6 +538,12 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.damageRadius = damageRadius; } + @Override + public int getMaxPreviewDuration() { + int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; + return blinkLimit * blinkDelayTicks + 10; + } + @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index 102c4395f..62471c051 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -1,57 +1,26 @@ package kamkeel.npcs.controllers.data.ability.type; -import kamkeel.npcs.controllers.data.ability.Ability; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.DamageSource; -import net.minecraft.world.World; -import noppes.npcs.entity.EntityNPCInterface; - import noppes.npcs.api.ability.type.IAbilityTrap; - +import noppes.npcs.client.gui.SubGuiTrapPresetSelector; import noppes.npcs.client.gui.builder.FieldDef; -import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import noppes.npcs.constants.EnumPotionType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.UUID; -/** - * Trap ability: Places a proximity-triggered trap. - * Features arm time, trigger radius, and various effects on trigger. - */ -public class AbilityTrap extends Ability implements IAbilityTrap { +public class AbilityTrap extends AbilityZone implements IAbilityTrap { - public enum TrapPlacement { - AT_CASTER, - AT_TARGET, - AHEAD_OF_CASTER; - - @Override - public String toString() { - switch (this) { - case AT_CASTER: return "ability.trapPlace.atCaster"; - case AT_TARGET: return "ability.trapPlace.atTarget"; - case AHEAD_OF_CASTER: return "ability.trapPlace.aheadOfCaster"; - default: return name(); - } - } - } - - private int durationTicks = 200; - private TrapPlacement placement = TrapPlacement.AT_TARGET; - private float placementDistance = 5.0f; private float triggerRadius = 2.0f; private int armTime = 20; private int maxTriggers = 1; @@ -61,235 +30,143 @@ public class AbilityTrap extends Ability implements IAbilityTrap { private float knockback = 0.5f; private boolean visible = true; - // Offset parameters - trap spawns near target, not exactly on them - private float minOffset = 0.0f; - private float maxOffset = 1.5f; - private boolean randomOffset = true; - - // Runtime state - private static final Random RANDOM = new Random(); - private transient double trapX, trapY, trapZ; - private transient boolean armed = false; - private transient int triggerCount = 0; - private transient int ticksSinceLastTrigger = 0; - private transient Set triggeredEntities = new HashSet<>(); - public AbilityTrap() { + super(300, new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.0f, 0.5f, 1.5f)); this.typeId = "ability.cnpc.trap"; this.name = "Trap"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 15.0f; - this.lockMovement = LockMovementType.WINDUP; - this.cooldownTicks = 0; - this.windUpTicks = 20; - this.telegraphType = TelegraphType.CIRCLE; + this.windUpTicks = 30; + this.windUpAnimationName = "Ability_Zone_Windup"; + this.activeAnimationName = "Ability_Zone_Active"; } @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public float getTelegraphRadius() { + public float getZoneRadius() { return triggerRadius; } @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - TelegraphInstance instance = super.createTelegraph(caster, target); - if (instance == null) return null; + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + activeEntities.clear(); - // Control telegraph following based on placement mode - switch (placement) { - case AT_CASTER: - case AHEAD_OF_CASTER: - // Telegraph at caster or ahead, no following - instance.setEntityIdToFollow(-1); - if (placement == TrapPlacement.AHEAD_OF_CASTER) { - double yaw = Math.toRadians(caster.rotationYaw); - instance.setX(caster.posX - Math.sin(yaw) * placementDistance); - instance.setY(caster.posY); - instance.setZ(caster.posZ + Math.cos(yaw) * placementDistance); - } else { - instance.setX(caster.posX); - instance.setY(caster.posY); - instance.setZ(caster.posZ); - } - break; - case AT_TARGET: - // Telegraph follows target during windup, locks on execute - if (target != null) { - instance.setEntityIdToFollow(target.getEntityId()); - } - break; - } - return instance; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - armed = false; - triggerCount = 0; - ticksSinceLastTrigger = armTime; - triggeredEntities.clear(); - - // Use telegraph position if available (for AT_TARGET, it was following target) - TelegraphInstance telegraph = getTelegraphInstance(); - - switch (placement) { - case AT_CASTER: - trapX = caster.posX; - trapY = caster.posY; - trapZ = caster.posZ; - break; - case AT_TARGET: - // Use telegraph position with offset - if (telegraph != null) { - double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), - minOffset, maxOffset, randomOffset, RANDOM); - trapX = pos[0]; - trapY = pos[1]; - trapZ = pos[2]; - // Update telegraph to show actual trap position - telegraph.setX(trapX); - telegraph.setY(trapY); - telegraph.setZ(trapZ); - } else if (target != null) { - double[] pos = Ability.calculateOffsetPosition(target.posX, target.posY, target.posZ, - minOffset, maxOffset, randomOffset, RANDOM); - trapX = pos[0]; - trapY = pos[1]; - trapZ = pos[2]; - } else { - trapX = caster.posX; - trapY = caster.posY; - trapZ = caster.posZ; - } - break; - case AHEAD_OF_CASTER: - double yaw = Math.toRadians(caster.rotationYaw); - trapX = caster.posX - Math.sin(yaw) * placementDistance; - trapY = caster.posY; - trapZ = caster.posZ + Math.cos(yaw) * placementDistance; - break; - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Check if trap duration has ended - if (tick >= durationTicks) { - signalCompletion(); - return; - } - - if (!armed) { - if (tick >= armTime) { - armed = true; - } - return; - } - - ticksSinceLastTrigger++; - - if (maxTriggers > 0 && triggerCount >= maxTriggers) { - signalCompletion(); // All triggers used, trap is done - return; - } - - if (ticksSinceLastTrigger < triggerCooldown) { - return; - } - - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, - trapX + triggerRadius, trapY + 2, trapZ + triggerRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; - if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; - - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); - - if (dist <= triggerRadius) { - triggerTrap(caster, entity, world); - return; - } - } - } - - private void triggerTrap(EntityLivingBase caster, EntityLivingBase triggerer, World world) { - triggerCount++; - ticksSinceLastTrigger = 0; - triggeredEntities.add(triggerer.getUniqueID()); - - Set affected = new HashSet<>(); - - if (damageRadius > 0) { - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - damageRadius, trapY - 1, trapZ - damageRadius, - trapX + damageRadius, trapY + 3, trapZ + damageRadius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist <= damageRadius) { - affected.add(entity); - } - } + List positions; + if (!preCalculatedPositions.isEmpty() && preCalculatedPositions.size() == zoneCount) { + positions = new ArrayList<>(preCalculatedPositions); + preCalculatedPositions.clear(); } else { - affected.add(triggerer); - } - - for (EntityLivingBase entity : affected) { - // Apply damage with scripted event support - boolean wasHit = applyAbilityDamage(caster, entity, damage, knockback); - - // Apply effects if the hit wasn't cancelled - if (wasHit) { - applyEffects(entity); + positions = new ArrayList<>(); + List placedPositions = new ArrayList<>(); + float minSeparation = triggerRadius * 2.0f; + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + positions.add(pos); } } + + for (int i = 0; i < zoneCount; i++) { + double[] pos = positions.get(i); + + EntityAbilityZone entity = EntityAbilityZone.createTrap(caster.worldObj, caster, + pos[0], caster.posY, pos[1], + zoneShape, + triggerRadius, armTime, maxTriggers, triggerCooldown, + damage, damageRadius, knockback, durationTicks, + colorData.innerColor, colorData.outerColor, colorData.outerColorEnabled, + zoneHeight, + particleDensity, particleScale, animSpeed, lightningDensity, + visible, + getEffects()); + + applyVisualToEntity(entity); + + if (isPreview()) { + entity.setupPreview(caster); + } + + spawnAbilityEntity(entity); + activeEntities.add(entity); + } } - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - armed = false; - triggerCount = 0; - triggeredEntities.clear(); + @SideOnly(Side.CLIENT) + public enum TrapPreset { + HIDDEN, VENOM, EXPLOSIVE, CURSED, SHOCK, SNARE; + + @Override + public String toString() { + return "ability.preset." + name().toLowerCase(); + } } - @Override - public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - armed = false; - triggerCount = 0; - triggeredEntities.clear(); + private void applyTrapPresetDefaults(String preset) { + effects.clear(); + particleDir = ""; + + groundFill = true; + rings = false; + ringCount = 1; + border = false; + borderSpeed = 1.0f; + accents = false; + accentStyle = 0; + lightning = false; + particleGlow = false; + + switch (preset) { + case "VENOM": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:mobSpell"; + colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; + windUpColor = 0x6044DD44; activeColor = 0xC044FF44; + effects.add(new AbilityEffect(EnumPotionType.Poison, 100, 0)); + break; + case "EXPLOSIVE": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.6f; + particleMotion = 0; particleDir = "mc:smoke"; + colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; + windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; + effects.add(new AbilityEffect(EnumPotionType.Fire, 60, 0)); + break; + case "CURSED": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:portal"; + colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; + windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; + effects.add(new AbilityEffect(EnumPotionType.Weakness, 100, 0)); + break; + case "SHOCK": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.4f; + particleMotion = 2; particleDir = "mc:enchantmenttable"; + colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; + windUpColor = 0x604488FF; activeColor = 0xC066AAFF; + effects.add(new AbilityEffect(EnumPotionType.MiningFatigue, 80, 1)); + break; + case "SNARE": + groundAlpha = 0.04f; + particles = true; particleDensity = 0.3f; particleScale = 0.5f; + particleMotion = 1; particleDir = "mc:snowshovel"; + colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; + windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; + effects.add(new AbilityEffect(EnumPotionType.Slowness, 100, 1)); + break; + case "HIDDEN": + default: + groundAlpha = 0.03f; + particles = false; particleDensity = 0.0f; particleScale = 1.0f; + particleMotion = 0; + colorData.innerColor = 0x888888; colorData.outerColor = 0x444444; + windUpColor = 0x60888888; activeColor = 0xC0AAAAAA; + break; + } } @Override public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setInteger("durationTicks", durationTicks); - nbt.setString("placement", placement.name()); - nbt.setFloat("placementDistance", placementDistance); + writeZoneNBT(nbt); nbt.setFloat("triggerRadius", triggerRadius); nbt.setInteger("armTime", armTime); nbt.setInteger("maxTriggers", maxTriggers); @@ -298,190 +175,78 @@ public class AbilityTrap extends Ability implements IAbilityTrap { nbt.setFloat("damageRadius", damageRadius); nbt.setFloat("knockback", knockback); nbt.setBoolean("visible", visible); - nbt.setFloat("minOffset", minOffset); - nbt.setFloat("maxOffset", maxOffset); - nbt.setBoolean("randomOffset", randomOffset); } @Override public void readTypeNBT(NBTTagCompound nbt) { - this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 200; - try { - this.placement = TrapPlacement.valueOf(nbt.getString("placement")); - } catch (Exception e) { - this.placement = TrapPlacement.AT_TARGET; - } - this.placementDistance = nbt.hasKey("placementDistance") ? nbt.getFloat("placementDistance") : 5.0f; - this.triggerRadius = nbt.hasKey("triggerRadius") ? nbt.getFloat("triggerRadius") : 2.0f; - this.armTime = nbt.hasKey("armTime") ? nbt.getInteger("armTime") : 20; - this.maxTriggers = nbt.hasKey("maxTriggers") ? nbt.getInteger("maxTriggers") : 1; - this.triggerCooldown = nbt.hasKey("triggerCooldown") ? nbt.getInteger("triggerCooldown") : 20; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 6.0f; - this.damageRadius = nbt.hasKey("damageRadius") ? nbt.getFloat("damageRadius") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.5f; - this.visible = !nbt.hasKey("visible") || nbt.getBoolean("visible"); - this.minOffset = nbt.hasKey("minOffset") ? nbt.getFloat("minOffset") : 0.0f; - this.maxOffset = nbt.hasKey("maxOffset") ? nbt.getFloat("maxOffset") : 1.5f; - this.randomOffset = !nbt.hasKey("randomOffset") || nbt.getBoolean("randomOffset"); + readZoneNBT(nbt, 300); + this.triggerRadius = nbt.getFloat("triggerRadius"); + this.armTime = nbt.getInteger("armTime"); + this.maxTriggers = nbt.getInteger("maxTriggers"); + this.triggerCooldown = nbt.getInteger("triggerCooldown"); + this.damage = nbt.getFloat("damage"); + this.damageRadius = nbt.getFloat("damageRadius"); + this.knockback = nbt.getFloat("knockback"); + this.visible = nbt.getBoolean("visible"); } - // Getters & Setters - public int getDurationTicks() { - return durationTicks; - } - - public void setDurationTicks(int durationTicks) { - this.durationTicks = Math.max(1, durationTicks); - } - - public TrapPlacement getPlacementEnum() { - return placement; - } - - public void setPlacementEnum(TrapPlacement placement) { - this.placement = placement; - } + public float getTriggerRadius() { return triggerRadius; } + public void setTriggerRadius(float triggerRadius) { this.triggerRadius = triggerRadius; } + public int getArmTime() { return armTime; } + public void setArmTime(int armTime) { this.armTime = armTime; } + public int getMaxTriggers() { return maxTriggers; } + public void setMaxTriggers(int maxTriggers) { this.maxTriggers = maxTriggers; } + public int getTriggerCooldown() { return triggerCooldown; } + public void setTriggerCooldown(int triggerCooldown) { this.triggerCooldown = triggerCooldown; } + public float getDamage() { return damage; } + public void setDamage(float damage) { this.damage = damage; } + public float getDamageRadius() { return damageRadius; } + public void setDamageRadius(float damageRadius) { this.damageRadius = damageRadius; } + public float getKnockback() { return knockback; } + public void setKnockback(float knockback) { this.knockback = knockback; } + public boolean isVisible() { return visible; } + public void setVisible(boolean visible) { this.visible = visible; } + @SideOnly(Side.CLIENT) @Override - public int getPlacement() { - return placement.ordinal(); - } - - @Override - public void setPlacement(int placement) { - TrapPlacement[] values = TrapPlacement.values(); - this.placement = placement >= 0 && placement < values.length ? values[placement] : TrapPlacement.AT_TARGET; - } - - public float getPlacementDistance() { - return placementDistance; - } - - public void setPlacementDistance(float placementDistance) { - this.placementDistance = placementDistance; - } - - public float getTriggerRadius() { - return triggerRadius; - } - - public void setTriggerRadius(float triggerRadius) { - this.triggerRadius = triggerRadius; - } - - public int getArmTime() { - return armTime; - } - - public void setArmTime(int armTime) { - this.armTime = armTime; - } - - public int getMaxTriggers() { - return maxTriggers; - } - - public void setMaxTriggers(int maxTriggers) { - this.maxTriggers = maxTriggers; - } - - public int getTriggerCooldown() { - return triggerCooldown; - } - - public void setTriggerCooldown(int triggerCooldown) { - this.triggerCooldown = triggerCooldown; - } - - public float getDamage() { - return damage; - } - - public void setDamage(float damage) { - this.damage = damage; - } - - public float getDamageRadius() { - return damageRadius; - } - - public void setDamageRadius(float damageRadius) { - this.damageRadius = damageRadius; - } - - public float getKnockback() { - return knockback; - } - - public void setKnockback(float knockback) { - this.knockback = knockback; - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(boolean visible) { - this.visible = visible; - } - - public float getMinOffset() { - return minOffset; - } - - public void setMinOffset(float minOffset) { - this.minOffset = minOffset; - } - - public float getMaxOffset() { - return maxOffset; - } - - public void setMaxOffset(float maxOffset) { - this.maxOffset = maxOffset; - } - - public boolean isRandomOffset() { - return randomOffset; - } - - public void setRandomOffset(boolean randomOffset) { - this.randomOffset = randomOffset; - } - - // Runtime getters - public double getTrapX() { - return trapX; - } - - public double getTrapY() { - return trapY; - } - - public double getTrapZ() { - return trapZ; - } - - public boolean isArmed() { - return armed; + protected void addPresetFieldDef(List defs) { + defs.add(FieldDef.subGuiField("gui.applyPreset", + SubGuiTrapPresetSelector::new, + gui -> { + SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui; + if (selector.selectedPreset != null) { + applyTrapPresetDefaults(selector.selectedPreset); + } + })); } @SideOnly(Side.CLIENT) @Override public void getAbilityDefinitions(List defs) { + addPresetFieldDef(defs); + defs.addAll(Arrays.asList( - FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) - .range(1, 2000), - FieldDef.enumField("ability.placement", TrapPlacement.class, this::getPlacementEnum, this::setPlacementEnum) - .hover("ability.hover.placement"), + FieldDef.row( + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), + FieldDef.enumField("ability.zoneShape", ZoneShape.class, this::getZoneShapeEnum, this::setZoneShapeEnum) + ), + FieldDef.section("ability.section.zone"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getSpawnRadius, this::setSpawnRadius), + FieldDef.intField("gui.count", this::getZoneCount, this::setZoneCount).range(1, 20) + ), + FieldDef.row( + FieldDef.floatField("gui.height", this::getZoneHeight, this::setZoneHeight), + FieldDef.boolField("ability.visible", this::isVisible, this::setVisible) + ), FieldDef.section("ability.section.trigger"), FieldDef.row( FieldDef.floatField("gui.radius", this::getTriggerRadius, this::setTriggerRadius), FieldDef.intField("ability.armTime", this::getArmTime, this::setArmTime) ), FieldDef.row( - FieldDef.intField("ability.maxTriggers", this::getMaxTriggers, this::setMaxTriggers), - FieldDef.intField("ability.triggerCooldown", this::getTriggerCooldown, this::setTriggerCooldown) + FieldDef.intField("gui.max", this::getMaxTriggers, this::setMaxTriggers), + FieldDef.intField("gui.cooldown", this::getTriggerCooldown, this::setTriggerCooldown) ), FieldDef.section("ability.section.damage"), FieldDef.row( @@ -491,5 +256,7 @@ public class AbilityTrap extends Ability implements IAbilityTrap { FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) )); + + addVisualFieldDefs(defs); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index e31a1e6ce..f969c27cd 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -79,41 +79,50 @@ public class AbilityVortex extends Ability implements IAbilityVortex { } @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { getPulledEntities().clear(); pullComplete = false; ticksSincePullDamage = 0; - if (aoe) { - AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + if (!isPreview()) { + if (aoe) { + AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + @SuppressWarnings("unchecked") + List entities = caster.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist <= pullRadius) { - getPulledEntities().add(entity.getUniqueID()); - count++; - if (count >= maxTargets) break; + double dist = caster.getDistanceToEntity(entity); + if (dist <= pullRadius) { + getPulledEntities().add(entity.getUniqueID()); + count++; + if (count >= maxTargets) break; + } } - } - } else { - // Single target mode - still check pullRadius - if (target != null && !target.isDead) { - double dist = caster.getDistanceToEntity(target); - if (dist <= pullRadius) { - getPulledEntities().add(target.getUniqueID()); + } else { + // NPC single-target mode: pull the aggro target + // Player: single-target mode has no effect (no target to pull — use AOE mode instead) + if (!isPlayerCaster(caster) && target != null && !target.isDead) { + double dist = caster.getDistanceToEntity(target); + if (dist <= pullRadius) { + getPulledEntities().add(target.getUniqueID()); + } } } } } @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (isPreview()) { + // No entities to pull in preview, just run animation for a duration + if (tick >= 60) signalCompletion(); + return; + } + if (pullComplete || getPulledEntities().isEmpty()) { signalCompletion(); return; @@ -127,7 +136,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { ticksSincePullDamage++; for (UUID uuid : new HashSet<>(getPulledEntities())) { - EntityLivingBase entity = findEntity(caster, world, uuid); + EntityLivingBase entity = findEntity(caster, caster.worldObj, uuid); if (entity == null || entity.isDead) { getPulledEntities().remove(uuid); continue; @@ -140,7 +149,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { if (dist <= 1.5f) { getPulledEntities().remove(uuid); - onTargetArrived(caster, entity, world); + onTargetArrived(caster, entity, caster.worldObj); continue; } @@ -155,7 +164,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double nextZ = dz * factor; AxisAlignedBB nextBox = entity.boundingBox.copy().offset(nextX, nextY, nextZ); - if (!world.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { + if (!caster.worldObj.getCollidingBoundingBoxes(entity, nextBox).isEmpty()) { getPulledEntities().remove(uuid); continue; } @@ -227,14 +236,14 @@ public class AbilityVortex extends Ability implements IAbilityVortex { @Override public void readTypeNBT(NBTTagCompound nbt) { - this.pullRadius = nbt.hasKey("pullRadius") ? nbt.getFloat("pullRadius") : 8.0f; - this.pullStrength = nbt.hasKey("pullStrength") ? nbt.getFloat("pullStrength") : 0.8f; - this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 0.0f; - this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 0.0f; - this.aoe = nbt.hasKey("aoe") && nbt.getBoolean("aoe"); - this.maxTargets = nbt.hasKey("maxTargets") ? nbt.getInteger("maxTargets") : 5; - this.damageOnPull = nbt.hasKey("damageOnPull") && nbt.getBoolean("damageOnPull"); - this.pullDamage = nbt.hasKey("pullDamage") ? nbt.getFloat("pullDamage") : 0.0f; + this.pullRadius = nbt.getFloat("pullRadius"); + this.pullStrength = nbt.getFloat("pullStrength"); + this.damage = nbt.getFloat("damage"); + this.knockback = nbt.getFloat("knockback"); + this.aoe = nbt.getBoolean("aoe"); + this.maxTargets = nbt.getInteger("maxTargets"); + this.damageOnPull = nbt.getBoolean("damageOnPull"); + this.pullDamage = nbt.getFloat("pullDamage"); } // Getters & Setters diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java new file mode 100644 index 000000000..0d4b0ce8f --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityZone.java @@ -0,0 +1,482 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityZone; +import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle; +import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion; +import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.constants.EnumPotionType; +import net.minecraft.util.DamageSource; + + +import noppes.npcs.client.gui.SubGuiZonePresetSelector; +import noppes.npcs.client.gui.builder.FieldDef; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public abstract class AbilityZone extends Ability { + + protected int durationTicks; + protected ZoneShape zoneShape = ZoneShape.CIRCLE; + protected float spawnRadius = 10.0f; + protected int zoneCount = 3; + protected float zoneHeight = 2.0f; + + protected float particleDensity = 1.0f; + protected float particleScale = 1.0f; + protected float animSpeed = 1.0f; + protected float lightningDensity = 1.0f; + protected EnergyDisplayData colorData; + + protected boolean groundFill = true; + protected float groundAlpha = 0.25f; + protected boolean rings = true; + protected int ringCount = 3; + protected boolean border = true; + protected float borderSpeed = 1.0f; + protected boolean accents = true; + protected int accentStyle = 0; + protected boolean lightning = false; + protected boolean particles = true; + protected int particleMotion = 0; + protected String particleDir = ""; + protected int particleSize = 32; + protected boolean particleGlow = true; + + protected static final Random RANDOM = new Random(); + protected transient List activeEntities = new ArrayList<>(); + protected transient List preCalculatedPositions = new ArrayList<>(); + + protected AbilityZone(int defaultDuration, EnergyDisplayData defaultColors) { + this.durationTicks = defaultDuration; + this.colorData = defaultColors; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 20.0f; + this.lockMovement = LockMovementType.WINDUP; + this.cooldownTicks = 0; + this.allowedBy = UserType.NPC_ONLY; + } + + @Override + public boolean allowBurst() { + return false; + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + public abstract float getZoneRadius(); + + @Override + public List createTelegraphs(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || windUpTicks <= 0) return new ArrayList<>(); + + preCalculatedPositions.clear(); + List placedPositions = new ArrayList<>(); + float minSeparation = getZoneRadius() * 2.0f; + + for (int i = 0; i < zoneCount; i++) { + double[] pos = findSpawnPosition(caster, placedPositions, minSeparation); + placedPositions.add(pos); + preCalculatedPositions.add(pos); + } + + List telegraphs = new ArrayList<>(); + float zoneRadius = getZoneRadius(); + + for (double[] pos : preCalculatedPositions) { + Telegraph telegraph; + if (zoneShape == ZoneShape.SQUARE) { + telegraph = Telegraph.square(zoneRadius); + } else { + telegraph = Telegraph.circle(zoneRadius); + } + + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + double groundY = findGroundLevel(caster.worldObj, pos[0], caster.posY, pos[1]); + TelegraphInstance instance = new TelegraphInstance(telegraph, pos[0], groundY, pos[1], 0); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(-1); + telegraphs.add(instance); + } + + return telegraphs; + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + Iterator it = activeEntities.iterator(); + while (it.hasNext()) { + EntityAbilityZone entity = it.next(); + if (entity == null || entity.isDead) { + it.remove(); + } + } + + if (activeEntities.isEmpty()) { + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + cleanup(); + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + for (EntityAbilityZone entity : activeEntities) { + if (entity != null && !entity.isDead) { + killAbilityEntity(entity); + } + } + activeEntities.clear(); + preCalculatedPositions.clear(); + } + + @Override + public int getMaxPreviewDuration() { + return durationTicks + 10; + } + + protected double[] findSpawnPosition(EntityLivingBase caster, List placedPositions, float minSeparation) { + double spawnX = caster.posX; + double spawnZ = caster.posZ; + + for (int attempt = 0; attempt < 15; attempt++) { + double angle = RANDOM.nextDouble() * Math.PI * 2; + double dist = Math.sqrt(RANDOM.nextDouble()) * spawnRadius; + double candidateX = caster.posX + Math.cos(angle) * dist; + double candidateZ = caster.posZ + Math.sin(angle) * dist; + + boolean overlaps = false; + for (double[] placed : placedPositions) { + double dx = candidateX - placed[0]; + double dz = candidateZ - placed[1]; + if (Math.sqrt(dx * dx + dz * dz) < minSeparation) { + overlaps = true; + break; + } + } + + spawnX = candidateX; + spawnZ = candidateZ; + if (!overlaps) break; + } + + return new double[]{spawnX, spawnZ}; + } + + protected void applyVisualToEntity(EntityAbilityZone entity) { + entity.applyVisual(groundFill, groundAlpha, + rings, ringCount, border, borderSpeed, + accents, accentStyle, lightning, + particles, particleMotion, particleDir, + particleSize, particleGlow); + } + + private void applyPresetDefaults(String styleName) { + effects.clear(); + particleDir = ""; + switch (styleName) { + case "TOXIC": + groundFill = true; groundAlpha = 0.30f; rings = true; ringCount = 3; + border = false; borderSpeed = 1.0f; accents = true; accentStyle = 1; + lightning = false; particles = true; particleDensity = 1.5f; particleScale = 0.8f; + particleMotion = 1; particleGlow = true; particleDir = "mc:mobSpell"; + colorData.innerColor = 0x44DD44; colorData.outerColor = 0x116611; + windUpColor = 0x6044DD44; activeColor = 0xC044FF44; + effects.add(new AbilityEffect(EnumPotionType.Poison, 100, 0)); + break; + case "INFERNO": + groundFill = true; groundAlpha = 0.35f; rings = true; ringCount = 3; + border = true; borderSpeed = 2.0f; accents = true; accentStyle = 2; + lightning = false; particles = true; particleDensity = 2.0f; particleScale = 1.2f; + particleMotion = 0; particleGlow = true; particleDir = "mc:flame"; + colorData.innerColor = 0xFF6611; colorData.outerColor = 0xCC2200; + windUpColor = 0x60FF6611; activeColor = 0xC0FF4400; + effects.add(new AbilityEffect(EnumPotionType.Fire, 60, 0)); + break; + case "ARCANE": + groundFill = true; groundAlpha = 0.20f; rings = true; ringCount = 1; + border = true; borderSpeed = 0.8f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleDensity = 1.0f; particleScale = 1.0f; + particleMotion = 1; particleGlow = true; particleDir = "mc:portal"; + colorData.innerColor = 0xAA44FF; colorData.outerColor = 0x6622BB; + windUpColor = 0x60AA44FF; activeColor = 0xC0CC66FF; + effects.add(new AbilityEffect(EnumPotionType.Weakness, 100, 0)); + break; + case "ELECTRIC": + groundFill = true; groundAlpha = 0.15f; rings = false; ringCount = 1; + border = false; borderSpeed = 1.0f; accents = false; accentStyle = 0; + lightning = true; particles = true; particleDensity = 0.8f; particleScale = 0.6f; + particleMotion = 2; particleGlow = true; particleDir = "mc:enchantmenttable"; + colorData.innerColor = 0x4488FF; colorData.outerColor = 0x2244BB; + windUpColor = 0x604488FF; activeColor = 0xC066AAFF; + effects.add(new AbilityEffect(EnumPotionType.MiningFatigue, 80, 1)); + break; + case "FROST": + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 0.3f; accents = true; accentStyle = 0; + lightning = false; particles = true; particleDensity = 1.5f; particleScale = 1.0f; + particleMotion = 1; particleGlow = true; particleDir = "mc:snowshovel"; + colorData.innerColor = 0x88CCFF; colorData.outerColor = 0x4488CC; + windUpColor = 0x6088CCFF; activeColor = 0xC0AADDFF; + effects.add(new AbilityEffect(EnumPotionType.Slowness, 100, 1)); + break; + case "DEFAULT": + groundFill = true; groundAlpha = 0.25f; rings = true; ringCount = 3; + border = true; borderSpeed = 1.0f; accents = true; accentStyle = 0; + lightning = false; particles = false; particleDensity = 1.0f; particleScale = 1.0f; + particleMotion = 0; particleGlow = true; + colorData.innerColor = 0xCCCCCC; colorData.outerColor = 0x666666; + windUpColor = 0x60CCCCCC; activeColor = 0xC0FFFFFF; + break; + default: + break; + } + } + + @SideOnly(Side.CLIENT) + public enum ZonePreset { + DEFAULT, TOXIC, INFERNO, ARCANE, ELECTRIC, FROST; + + @Override + public String toString() { + return "ability.preset." + name().toLowerCase(); + } + } + + protected void writeZoneNBT(NBTTagCompound nbt) { + nbt.setInteger("durationTicks", durationTicks); + nbt.setString("zoneShape", zoneShape.name()); + nbt.setFloat("spawnRadius", spawnRadius); + nbt.setInteger("zoneCount", zoneCount); + nbt.setFloat("zoneHeight", zoneHeight); + nbt.setFloat("particleDensity", particleDensity); + nbt.setFloat("particleScale", particleScale); + nbt.setFloat("animSpeed", animSpeed); + nbt.setFloat("lightningDensity", lightningDensity); + colorData.writeNBT(nbt); + + nbt.setBoolean("groundFill", groundFill); + nbt.setFloat("groundAlpha", groundAlpha); + nbt.setBoolean("rings", rings); + nbt.setInteger("ringCount", ringCount); + nbt.setBoolean("border", border); + nbt.setFloat("borderSpeed", borderSpeed); + nbt.setBoolean("accents", accents); + nbt.setInteger("accentStyle", accentStyle); + nbt.setBoolean("lightning", lightning); + nbt.setBoolean("particles", particles); + nbt.setInteger("particleMotion", particleMotion); + nbt.setString("particleDir", particleDir); + nbt.setInteger("particleSize", particleSize); + nbt.setBoolean("particleGlow", particleGlow); + } + + protected void readZoneNBT(NBTTagCompound nbt, int defaultDuration) { + this.durationTicks = nbt.getInteger("durationTicks"); + try { this.zoneShape = ZoneShape.valueOf(nbt.getString("zoneShape")); } + catch (Exception e) { this.zoneShape = ZoneShape.CIRCLE; } + this.spawnRadius = nbt.getFloat("spawnRadius"); + this.zoneCount = nbt.getInteger("zoneCount"); + this.zoneHeight = nbt.getFloat("zoneHeight"); + this.particleDensity = nbt.getFloat("particleDensity"); + this.particleScale = nbt.getFloat("particleScale"); + this.animSpeed = nbt.getFloat("animSpeed"); + this.lightningDensity = nbt.getFloat("lightningDensity"); + colorData.readNBT(nbt); + + this.groundFill = nbt.getBoolean("groundFill"); + this.groundAlpha = nbt.getFloat("groundAlpha"); + this.rings = nbt.getBoolean("rings"); + this.ringCount = nbt.getInteger("ringCount"); + this.border = nbt.getBoolean("border"); + this.borderSpeed = nbt.getFloat("borderSpeed"); + this.accents = nbt.getBoolean("accents"); + this.accentStyle = nbt.getInteger("accentStyle"); + this.lightning = nbt.getBoolean("lightning"); + this.particles = nbt.getBoolean("particles"); + this.particleMotion = nbt.getInteger("particleMotion"); + this.particleDir = nbt.getString("particleDir"); + this.particleSize = nbt.getInteger("particleSize"); + this.particleGlow = nbt.getBoolean("particleGlow"); + } + + public int getDurationTicks() { return durationTicks; } + public void setDurationTicks(int durationTicks) { this.durationTicks = Math.max(1, durationTicks); } + + public ZoneShape getZoneShapeEnum() { return zoneShape; } + public void setZoneShapeEnum(ZoneShape shape) { this.zoneShape = shape; } + + public int getZoneShapeOrdinal() { return zoneShape.ordinal(); } + public void setZoneShapeOrdinal(int shape) { + ZoneShape[] values = ZoneShape.values(); + this.zoneShape = shape >= 0 && shape < values.length ? values[shape] : ZoneShape.CIRCLE; + } + + public float getSpawnRadius() { return spawnRadius; } + public void setSpawnRadius(float spawnRadius) { this.spawnRadius = Math.max(0, spawnRadius); } + public int getZoneCount() { return zoneCount; } + public void setZoneCount(int zoneCount) { this.zoneCount = Math.max(1, zoneCount); } + public float getZoneHeight() { return zoneHeight; } + public void setZoneHeight(float zoneHeight) { this.zoneHeight = Math.max(0.5f, zoneHeight); } + + public float getParticleDensity() { return particleDensity; } + public void setParticleDensity(float v) { this.particleDensity = Math.max(0, Math.min(5, v)); } + public float getParticleScale() { return particleScale; } + public void setParticleScale(float v) { this.particleScale = Math.max(0.1f, Math.min(5, v)); } + public float getAnimSpeed() { return animSpeed; } + public void setAnimSpeed(float v) { this.animSpeed = Math.max(0.1f, Math.min(5, v)); } + public float getLightningDensity() { return lightningDensity; } + public void setLightningDensity(float v) { this.lightningDensity = Math.max(0, Math.min(3, v)); } + + public int getInnerColor() { return colorData.innerColor; } + public void setInnerColor(int color) { colorData.innerColor = color; } + public int getOuterColor() { return colorData.outerColor; } + public void setOuterColor(int color) { colorData.outerColor = color; } + public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } + public void setOuterColorEnabled(boolean enabled) { colorData.outerColorEnabled = enabled; } + + public boolean isGroundFill() { return groundFill; } + public void setGroundFill(boolean v) { this.groundFill = v; } + public float getGroundAlpha() { return groundAlpha; } + public void setGroundAlpha(float v) { this.groundAlpha = Math.max(0, Math.min(1, v)); } + public boolean isRings() { return rings; } + public void setRings(boolean v) { this.rings = v; } + public int getRingCount() { return ringCount; } + public void setRingCount(int v) { this.ringCount = Math.max(1, Math.min(5, v)); } + public boolean isBorder() { return border; } + public void setBorder(boolean v) { this.border = v; } + public float getBorderSpeed() { return borderSpeed; } + public void setBorderSpeed(float v) { this.borderSpeed = Math.max(0.1f, Math.min(5, v)); } + public boolean isAccents() { return accents; } + public void setAccents(boolean v) { this.accents = v; } + public int getAccentStyle() { return accentStyle; } + public void setAccentStyle(int v) { this.accentStyle = Math.max(0, Math.min(AccentStyle.values().length - 1, v)); } + public AccentStyle getAccentStyleEnum() { return AccentStyle.values()[Math.max(0, Math.min(accentStyle, AccentStyle.values().length - 1))]; } + public void setAccentStyleEnum(AccentStyle s) { this.accentStyle = s.ordinal(); } + public boolean isLightning() { return lightning; } + public void setLightning(boolean v) { this.lightning = v; } + public boolean isParticles() { return particles; } + public void setParticles(boolean v) { this.particles = v; } + public int getParticleMotion() { return particleMotion; } + public void setParticleMotion(int v) { this.particleMotion = Math.max(0, Math.min(ParticleMotion.values().length - 1, v)); } + public ParticleMotion getParticleMotionEnum() { return ParticleMotion.values()[Math.max(0, Math.min(particleMotion, ParticleMotion.values().length - 1))]; } + public void setParticleMotionEnum(ParticleMotion m) { this.particleMotion = m.ordinal(); } + public String getParticleDir() { return particleDir; } + public void setParticleDir(String v) { this.particleDir = v != null ? v : ""; } + public int getParticleSize() { return particleSize; } + public void setParticleSize(int v) { this.particleSize = Math.max(1, Math.min(256, v)); } + public boolean isParticleGlow() { return particleGlow; } + public void setParticleGlow(boolean v) { this.particleGlow = v; } + + @SideOnly(Side.CLIENT) + protected void addPresetFieldDef(List defs) { + defs.add(FieldDef.subGuiField("gui.applyPreset", + SubGuiZonePresetSelector::new, + gui -> { + SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui; + if (selector.selectedPreset != null) { + applyPresetDefaults(selector.selectedPreset); + } + })); + } + + @SideOnly(Side.CLIENT) + protected void addVisualFieldDefs(List defs) { + defs.addAll(Arrays.asList( + FieldDef.section("ability.section.ground").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isGroundFill, this::setGroundFill), + FieldDef.floatField("gui.alpha", this::getGroundAlpha, this::setGroundAlpha) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.rings").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isRings, this::setRings), + FieldDef.intField("gui.count", this::getRingCount, this::setRingCount).range(1, 5) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.border").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isBorder, this::setBorder), + FieldDef.floatField("gui.speed", this::getBorderSpeed, this::setBorderSpeed) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.accents").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isAccents, this::setAccents), + FieldDef.enumField("gui.style", AccentStyle.class, this::getAccentStyleEnum, this::setAccentStyleEnum) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.lightning").tab("ability.tab.visual"), + FieldDef.row( + FieldDef.boolField("gui.enabled", this::isLightning, this::setLightning), + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + ).tab("ability.tab.visual"), + + FieldDef.section("ability.section.particles").tab("ability.tab.visual"), + FieldDef.boolField("gui.enabled", this::isParticles, this::setParticles) + .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("gui.density", this::getParticleDensity, this::setParticleDensity), + FieldDef.floatField("gui.scale", this::getParticleScale, this::setParticleScale) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.row( + FieldDef.enumField("gui.motion", ParticleMotion.class, this::getParticleMotionEnum, this::setParticleMotionEnum), + FieldDef.boolField("gui.glow", this::isParticleGlow, this::setParticleGlow) + ).tab("ability.tab.visual").visibleWhen(this::isParticles), + FieldDef.stringField("gui.texture", this::getParticleDir, this::setParticleDir) + .tab("ability.tab.visual").visibleWhen(this::isParticles), + + FieldDef.section("ability.section.animation").tab("ability.tab.visual"), + FieldDef.floatField("gui.speed", this::getAnimSpeed, this::setAnimSpeed) + .tab("ability.tab.visual"), + + FieldDef.section("ability.section.colors").tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual"), + FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled) + )); + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java new file mode 100644 index 000000000..f3ee572c2 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbstractEnergyProjectileAbility.java @@ -0,0 +1,617 @@ +package kamkeel.npcs.controllers.data.ability.type; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityProjectile; +import kamkeel.npcs.util.AnchorPointHelper; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; +import noppes.npcs.api.ability.type.IAbilityEnergyProjectile; +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * Abstract base for energy projectile abilities (Orb, Disc, Beam, LaserShot). + * Handles shared lifecycle (windup → execute → active → completion), multi-projectile + * support with staggered firing, telegraph creation, NBT persistence, and GUI definitions. + * + * Subclasses provide entity creation/firing/charging logic and type-specific fields. + * + * @param The entity type this ability spawns + */ +public abstract class AbstractEnergyProjectileAbility + extends Ability implements IAbilityEnergyProjectile { + + protected static final int MAX_PROJECTILES = 8; + + // Multi-projectile support + protected int projectileCount = 1; + protected int fireDelay = 0; + + // Shared visual data + protected EnergyDisplayData displayData; + protected EnergyLightningData lightningData; + protected EnergyTrajectoryData trajectoryData; + + // Shared combat/movement data + protected final EnergyCombatData combatData; + protected final EnergyHomingData homingData; + protected final EnergyLifespanData lifespanData; + + // Per-projectile data (anchor + optional color override) + protected ProjectileData[] projectiles; + + // Transient entity state + protected transient E[] entities; + + // ==================== CONSTRUCTOR ==================== + + protected AbstractEnergyProjectileAbility( + EnergyDisplayData displayData, + EnergyCombatData combatData, + EnergyHomingData homingData, + EnergyLifespanData lifespanData + ) { + this.displayData = displayData; + this.combatData = combatData; + this.homingData = homingData; + this.lifespanData = lifespanData; + this.lightningData = new EnergyLightningData(); + this.trajectoryData = new EnergyTrajectoryData(); + initProjectiles(1); + } + + // ==================== ABSTRACT METHODS ==================== + + /** + * Create a single entity for the given projectile index. + * Called during windup (tick 1) and burst refire (onExecute when entities are null). + */ + protected abstract E createEntity(EntityLivingBase caster, EntityLivingBase target, + Vec3 spawnPos, EnergyDisplayData resolved, int index); + + /** + * Fire an entity (start moving toward target). Entity is guaranteed non-null and alive. + */ + protected abstract void fireEntity(E entity, EntityLivingBase target); + + /** + * Setup entity for charging animation during windup (non-preview). + */ + protected abstract void setupEntityCharging(E entity, ProjectileData projData, int index); + + /** + * Setup entity for preview mode during windup. + */ + protected abstract void setupEntityPreview(E entity, EntityLivingBase caster, + EnergyDisplayData resolved, ProjectileData projData, int index); + + /** + * Create typed array (Java generics can't create generic arrays). + */ + protected abstract E[] createEntityArray(int size); + + /** + * Get the telegraph radius for this projectile type. + */ + protected abstract float getProjectileTelegraphRadius(); + + /** + * Add type-specific GUI field definitions (Type tab). + * Called before shared visual tab definitions. + */ + @SideOnly(Side.CLIENT) + protected abstract void addTypeDefinitions(List defs); + + /** + * Write type-specific fields to NBT (e.g., orbSize, discRadius). + * Shared data classes are written by the base class. + */ + protected abstract void writeTypeSpecificNBT(NBTTagCompound nbt); + + /** + * Read type-specific fields from NBT. + * Shared data classes are read by the base class. + */ + protected abstract void readTypeSpecificNBT(NBTTagCompound nbt); + + // ==================== OVERRIDABLE HOOKS ==================== + + /** + * Get the default anchor point for a projectile index. + * Override for types with different anchor defaults. + */ + protected AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + /** + * Get the spawn position for a projectile. Override for types that need + * an offset distance (e.g., Beam uses offsetDist=1.0). + */ + protected Vec3 getSpawnPosition(EntityLivingBase caster, int index) { + return AnchorPointHelper.calculateAnchorPosition(caster, projectiles[index].anchor); + } + + // ==================== PROJECTILE MANAGEMENT ==================== + + protected void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { return projectileCount; } + + public int getFireDelay() { return fireDelay; } + public void setFireDelay(int delay) { this.fireDelay = Math.max(0, delay); } + + /** @deprecated Use {@link #getFireDelay()} */ + public int getDualFireDelay() { return fireDelay; } + /** @deprecated Use {@link #setFireDelay(int)} */ + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + protected int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } + + // ==================== ENTITY CREATION ==================== + + /** + * Create all entities for this ability. + * Sets effects, source ability, and sibling links. + */ + protected E[] createAllEntities(EntityLivingBase caster, EntityLivingBase target) { + E[] newEntities = createEntityArray(projectileCount); + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = getSpawnPosition(caster, i); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + newEntities[i] = createEntity(caster, target, spawnPos, resolved, i); + newEntities[i].setEffects(this.effects); + newEntities[i].setSourceAbility(this); + } + return newEntities; + } + + /** + * Fire an entity if it's valid. + */ + protected void fireEntitySafe(E entity, EntityLivingBase target) { + if (entity != null && !entity.isDead) { + fireEntity(entity, target); + } + } + + // ==================== LIFECYCLE ==================== + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (caster.worldObj.isRemote && !isPreview()) return; + + if (tick == 1) { + entities = createAllEntities(caster, target); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + setupEntityPreview(entities[i], caster, resolved, projectiles[i], i); + } else { + setupEntityCharging(entities[i], projectiles[i], i); + } + spawnAbilityEntity(entities[i]); + } + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target) { + // Create fresh entities if needed: + // - entities == null: windup was skipped (burst without replay animations) + // - isBurstRefire(): previous burst entities may still be alive, + // so we must create new ones for each burst iteration + if (entities == null || isBurstRefire()) { + // Non-overlap burst refire: kill old entities before creating new ones + if (isBurstRefire() && !burstOverlap && entities != null) { + cleanup(); + } + entities = createAllEntities(caster, target); + for (E entity : entities) { + spawnAbilityEntity(entity); + } + } + + // Fire first projectile immediately + fireEntitySafe(entities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireEntitySafe(entities[i], target); + } + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) { + if (entities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireEntitySafe(entities[i], target); + } + } + } + + // Check if all entities are dead or unreachable + boolean allDead = true; + for (E entity : entities) { + if (entity == null || entity.isDead) continue; + + // Check if entity was removed from world (chunk unload, etc.) + if (tick > 5 && entity.worldObj != null + && entity.worldObj.getEntityByID(entity.getEntityId()) != entity) { + entity.setDead(); + continue; + } + + allDead = false; + break; + } + + // Failsafe timeout: force completion if active phase exceeded max possible flight time + if (!allDead) { + int lastFireTick = fireDelay > 0 ? fireDelay * (projectileCount - 1) : 0; + int maxFlightTime = lifespanData.maxLifetime > 0 ? lifespanData.maxLifetime : 200; + if (tick > lastFireTick + maxFlightTime + 20) { + cleanup(); + allDead = true; + } + } + + if (allDead) { + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + } + + @Override + public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + if (entities != null) { + for (int i = 0; i < entities.length; i++) { + if (entities[i] != null && !entities[i].isDead) { + entities[i].setDead(); + } + entities[i] = null; + } + } + entities = null; + } + + // ==================== TELEGRAPH ==================== + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { + return null; + } + + Telegraph telegraph = Telegraph.circle(getProjectileTelegraphRadius()); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(target.getEntityId()); + + return instance; + } + + @Override + public float getTelegraphRadius() { + return getProjectileTelegraphRadius(); + } + + // ==================== NBT ==================== + + @Override + public final void writeTypeNBT(NBTTagCompound nbt) { + // Type-specific fields + writeTypeSpecificNBT(nbt); + + // Shared fields + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared data classes + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + combatData.writeNBT(nbt); + homingData.writeNBT(nbt); + lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } + } + + @Override + public final void readTypeNBT(NBTTagCompound nbt) { + // Type-specific fields + readTypeSpecificNBT(nbt); + + // Shared fields + int count = nbt.getInteger("projectileCount"); + initProjectiles(count); + this.fireDelay = nbt.getInteger("fireDelay"); + + // Shared data classes + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + combatData.readNBT(nbt); + homingData.readNBT(nbt); + lifespanData.readNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } + + // ==================== PREVIEW ==================== + + @Override + public int getMaxPreviewDuration() { + return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; + } + + // ==================== API GETTERS & SETTERS ==================== + + // Combat data + @Override public float getDamage() { return combatData.damage; } + @Override public void setDamage(float damage) { combatData.damage = damage; } + + @Override public float getKnockback() { return combatData.knockback; } + @Override public void setKnockback(float knockback) { combatData.knockback = knockback; } + + @Override public float getKnockbackUp() { return combatData.knockbackUp; } + @Override public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } + + @Override public boolean isExplosive() { return combatData.explosive; } + @Override public void setExplosive(boolean explosive) { combatData.explosive = explosive; } + + @Override public float getExplosionRadius() { return combatData.explosionRadius; } + @Override public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } + + @Override public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + @Override public void setExplosionDamageFalloff(float falloff) { combatData.explosionDamageFalloff = falloff; } + + // Lifespan data + @Override public float getMaxDistance() { return lifespanData.maxDistance; } + @Override public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } + + @Override public int getMaxLifetime() { return lifespanData.maxLifetime; } + @Override public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } + + // Homing data + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean homing) { homingData.homing = homing; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float strength) { homingData.homingStrength = strength; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float range) { homingData.homingRange = range; } + + // Display data - primary colors + @Override public int getInnerColor() { return displayData.innerColor; } + @Override public void setInnerColor(int color) { displayData.innerColor = color; } + + @Override public int getOuterColor() { return displayData.outerColor; } + @Override public void setOuterColor(int color) { displayData.outerColor = color; } + + @Override public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + @Override public void setOuterColorEnabled(boolean enabled) { displayData.outerColorEnabled = enabled; } + + @Override public float getOuterColorWidth() { return displayData.outerColorWidth; } + @Override public void setOuterColorWidth(float width) { displayData.outerColorWidth = width; } + + @Override public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + @Override public void setOuterColorAlpha(float alpha) { displayData.outerColorAlpha = alpha; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float speed) { displayData.rotationSpeed = speed; } + + // Lightning data + @Override public boolean hasLightningEffect() { return lightningData.lightningEffect; } + @Override public void setLightningEffect(boolean enabled) { lightningData.lightningEffect = enabled; } + + @Override public float getLightningDensity() { return lightningData.lightningDensity; } + @Override public void setLightningDensity(float density) { lightningData.lightningDensity = density; } + + @Override public float getLightningRadius() { return lightningData.lightningRadius; } + @Override public void setLightningRadius(float radius) { lightningData.lightningRadius = radius; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int fadeTime) { lightningData.lightningFadeTime = fadeTime; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint point) { projectiles[0].anchor.anchorPoint = point; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } + + @Override public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } + @Override public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } + + // ==================== GUI FIELD DEFINITIONS ==================== + + @SideOnly(Side.CLIENT) + @Override + public final void getAbilityDefinitions(List defs) { + // Type-specific fields first + addTypeDefinitions(defs); + + // Shared visual tab - primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Shared visual tab - effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Shared visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v) + .min(Float.NEGATIVE_INFINITY), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + .min(Float.NEGATIVE_INFINITY) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount).min(Float.NEGATIVE_INFINITY)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java index 3ba858acc..bcb7a7958 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/Telegraph.java @@ -150,6 +150,12 @@ public class Telegraph { return new Telegraph("", TelegraphType.POINT); } + public static Telegraph square(float radius) { + Telegraph t = new Telegraph("", TelegraphType.SQUARE); + t.radius = radius; + return t; + } + // ═══════════════════════════════════════════════════════════════════ // GETTERS & SETTERS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java index 4a2fe4b12..dd080f093 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java +++ b/src/main/java/kamkeel/npcs/controllers/data/telegraph/TelegraphType.java @@ -29,6 +29,11 @@ public enum TelegraphType { */ POINT, + /** + * Filled square (uses radius as half-size) + */ + SQUARE, + /** * No telegraph */ diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index 60175169a..db57660e4 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -45,10 +46,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Whether to render tail orb (only when anchored) private boolean renderTailOrb = true; - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; + // Charging state (beam-specific) private float chargeOffsetDistance = 1.0f; // Trail fading for non-anchored beams (comet effect) @@ -56,9 +54,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { private int trailFadeTime = 20; // Ticks for trail to fully fade private List trailPointAges = new ArrayList<>(); - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - // Debug logging private static final boolean DEBUG_LOGGING = false; @@ -66,34 +61,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if beam is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. * @param anchoredMode If true, origin follows owner and tail orb is rendered. @@ -137,23 +104,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { } // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * getSpeed(); - this.motionY = (dy / len) * getSpeed(); - this.motionZ = (dz / len) * getSpeed(); - } - } else { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - this.motionY = -Math.sin(pitch) * getSpeed(); - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + calculateInitialVelocity(owner, target, x, y, z); } public void setupCharging(EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { @@ -218,28 +169,41 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); - // Update start position to current position + // Origin (tail) stays at the charged position startX = posX; startY = posY; startZ = posZ; + // Reset head offset to origin + headOffsetX = 0; + headOffsetY = 0; + headOffsetZ = 0; + prevHeadOffsetX = 0; + prevHeadOffsetY = 0; + prevHeadOffsetZ = 0; + + // Origin no longer follows owner after firing + attachedToOwner = false; + // Sync prev position to prevent visual jump on first frame prevPosX = posX; prevPosY = posY; prevPosZ = posZ; + // Reset trail + trailPoints.clear(); + trailPointAges.clear(); + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + // Fire forward based on owner facing direction Entity owner = getOwnerEntity(); if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = 0; // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - motionY = -Math.sin(pitch) * getSpeed(); - motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); + motionX = -Math.sin(yaw) * getSpeed(); + motionY = 0; + motionZ = Math.cos(yaw) * getSpeed(); } else { motionX = getSpeed(); motionY = 0; @@ -255,10 +219,11 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * For non-anchored beams: origin fixed at charged position, head starts there */ public void startFiring(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Origin (tail) stays at the charged position - where the orb was // This is the same for both anchored and non-anchored modes startX = posX; @@ -415,38 +380,33 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { /** * Update during charging state - follow owner based on anchor point. + * Beam-specific: positions based on chargeOffsetDistance and updates startX/Y/Z. */ - private void updateCharging() { + @Override + protected void updateCharging() { chargeTick++; Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; + if (owner != null) { + Vec3 pos; + if (owner instanceof EntityLivingBase) { + pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData, chargeOffsetDistance); + } else { + float yaw = (float) Math.toRadians(owner.rotationYaw); + double offsetX = -Math.sin(yaw) * chargeOffsetDistance; + double offsetZ = Math.cos(yaw) * chargeOffsetDistance; + pos = Vec3.createVectorHelper( + owner.posX + offsetX, + owner.posY + owner.getEyeHeight() * 0.7, + owner.posZ + offsetZ + ); + } + + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + startX = pos.xCoord; + startY = pos.yCoord; + startZ = pos.zCoord; } - - // Calculate position based on anchor point - Vec3 pos; - if (owner instanceof EntityLivingBase) { - pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData, chargeOffsetDistance); - } else { - // Fallback for non-living entities (shouldn't happen normally) - float yaw = (float) Math.toRadians(owner.rotationYaw); - double offsetX = -Math.sin(yaw) * chargeOffsetDistance; - double offsetZ = Math.cos(yaw) * chargeOffsetDistance; - pos = Vec3.createVectorHelper( - owner.posX + offsetX, - owner.posY + owner.getEyeHeight() * 0.7, - owner.posZ + offsetZ - ); - } - - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - - // Also update origin for when firing starts - startX = pos.xCoord; - startY = pos.yCoord; - startZ = pos.zCoord; } /** @@ -530,7 +490,8 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { addTrailPoint(); } - private void updateHoming() { + @Override + protected void updateHoming() { if (!isHoming()) return; Entity target = getTargetEntity(); @@ -584,6 +545,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; @@ -633,10 +597,22 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return beamWidth; } + public void setBeamWidth(float beamWidth) { + this.beamWidth = beamWidth; + } + public float getHeadSize() { return headSize; } + public void setHeadSize(float headSize) { + this.headSize = headSize; + } + + public void setAttachedToOwner(boolean attached) { + this.attachedToOwner = attached; + } + /** * Get interpolated head offset for smooth rendering. * Returns offset RELATIVE to origin. @@ -686,24 +662,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { return attachedToOwner; } - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - /** * Whether trail should fade (comet effect for non-anchored beams). */ @@ -739,12 +697,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { this.prevHeadOffsetZ = this.headOffsetZ; this.attachedToOwner = !nbt.hasKey("AttachedToOwner") || nbt.getBoolean("AttachedToOwner"); this.renderTailOrb = !nbt.hasKey("RenderTailOrb") || nbt.getBoolean("RenderTailOrb"); - // Read charging state and sync to data watcher - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + readChargingNBT(nbt); this.chargeOffsetDistance = nbt.hasKey("ChargeOffsetDistance") ? nbt.getFloat("ChargeOffsetDistance") : 1.0f; this.fadeTrail = nbt.hasKey("FadeTrail") && nbt.getBoolean("FadeTrail"); this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20; @@ -752,6 +705,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Read trail points (relative to origin) trailPoints.clear(); + trailPointAges.clear(); if (nbt.hasKey("Trail")) { NBTTagList trailList = nbt.getTagList("Trail", 10); for (int i = 0; i < trailList.tagCount(); i++) { @@ -763,6 +717,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { )); } } + + // Read trail point ages (must match trailPoints size for fading trail) + if (nbt.hasKey("TrailAges")) { + int[] ages = nbt.getIntArray("TrailAges"); + for (int age : ages) { + trailPointAges.add(age); + } + } + // If trail points exist but ages don't (legacy data), initialize ages to 0 + while (trailPointAges.size() < trailPoints.size()) { + trailPointAges.add(0); + } } @Override @@ -774,15 +740,11 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { nbt.setDouble("HeadOffsetZ", headOffsetZ); nbt.setBoolean("AttachedToOwner", attachedToOwner); nbt.setBoolean("RenderTailOrb", renderTailOrb); - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); + writeChargingNBT(nbt); nbt.setFloat("ChargeOffsetDistance", chargeOffsetDistance); nbt.setBoolean("FadeTrail", fadeTrail); nbt.setInteger("TrailFadeTime", trailFadeTime); - this.anchorData.writeNBT(nbt); - // Write trail points NBTTagList trailList = new NBTTagList(); for (Vec3 point : trailPoints) { @@ -793,5 +755,12 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { trailList.appendTag(pointNbt); } nbt.setTag("Trail", trailList); + + // Write trail point ages for fading trail sync + int[] ages = new int[trailPointAges.size()]; + for (int i = 0; i < trailPointAges.size(); i++) { + ages[i] = trailPointAges.get(i); + } + nbt.setIntArray("TrailAges", ages); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index bbd77abd0..dd499f122 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -31,50 +32,16 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { // Disc shape properties private float discRadius = 1.0f; // Width of disc private float discThickness = 0.2f; // Height of disc + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; + // Charging state (disc-specific target sizes) private float targetDiscRadius = 1.0f; // Full radius to grow to during charging private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging - private EnergyAnchorData anchorData = new EnergyAnchorData(); - - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; public EntityAbilityDisc(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if disc is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. */ @@ -99,23 +66,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.discThickness = discThickness; // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * getSpeed(); - this.motionY = (dy / len) * getSpeed(); - this.motionZ = (dz / len) * getSpeed(); - } - } else { - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); - this.motionY = -Math.sin(pitch) * getSpeed(); - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); - } + calculateInitialVelocity(owner, target, x, y, z); } /** @@ -123,21 +74,13 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * The disc will grow from 0 to discRadius over chargeDuration ticks. * Position follows the owner based on anchor point. */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; + public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { this.targetDiscRadius = this.discRadius; this.targetDiscThickness = this.discThickness; + super.setupCharging(anchor, chargeDuration); + this.vertical = vertical; this.discRadius = 0.01f; this.discThickness = 0.01f; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; } /** @@ -145,7 +88,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Follows anchor point and animations like in the real game. * Can be fired when transitioning to active phase. */ - public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { + public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, boolean vertical) { this.setPreviewMode(true); this.setPreviewOwner(owner); @@ -158,6 +101,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.chargeDuration = chargeDuration; this.chargeTick = 0; this.anchorData = anchor; + this.vertical = vertical; // Store target size and start at 0 for grow effect this.targetDiscRadius = discRadius; @@ -186,8 +130,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); // Update start position to current position @@ -220,10 +162,11 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Update start position to current position startX = posX; startY = posY; @@ -354,43 +297,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.posZ += motionZ; } - private void updateHoming() { - if (!isHoming()) return; - - Entity target = getTargetEntity(); - if (target == null || !target.isEntityAlive()) return; - - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (dist <= getHomingRange() && dist > 0) { - // Calculate effective homing strength - increases when closer to commit to target - float effectiveStrength = getHomingStrength(); - if (dist < getHomingRange() * 0.3) { - effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); - } else if (dist < getHomingRange() * 0.6) { - effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); - } - - double desiredVX = (dx / dist) * getSpeed(); - double desiredVY = (dy / dist) * getSpeed(); - double desiredVZ = (dz / dist) * getSpeed(); - - motionX += (desiredVX - motionX) * effectiveStrength; - motionY += (desiredVY - motionY) * effectiveStrength; - motionZ += (desiredVZ - motionZ) * effectiveStrength; - - double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); - if (vLen > 0) { - motionX = (motionX / vLen) * getSpeed(); - motionY = (motionY / vLen) * getSpeed(); - motionZ = (motionZ / vLen) * getSpeed(); - } - } - } - private void updateReturnToOwner() { Entity owner = getOwnerEntity(); @@ -439,6 +345,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; @@ -480,23 +389,19 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { /** * Update during charging state - follow owner based on anchor point. + * Overrides base to grow disc-specific radius/thickness instead of just size. */ - private void updateCharging() { + @Override + protected void updateCharging() { chargeTick++; - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - // Grow size based on charge progress float progress = getChargeProgress(); this.discRadius = targetDiscRadius * progress; this.discThickness = targetDiscThickness * progress; this.size = this.discRadius; // Base size for interpolation - // Calculate position based on anchor point, offset downward by half radius to center + Entity owner = getOwnerEntity(); if (owner instanceof EntityLivingBase) { Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); setPosition(pos.xCoord, pos.yCoord, pos.zCoord); @@ -506,42 +411,70 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { updateRotation(); } - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - // ==================== GETTERS ==================== public float getDiscRadius() { return discRadius; } + public void setDiscRadius(float radius) { + this.discRadius = radius; + } + public float getDiscThickness() { return discThickness; } + public void setDiscThickness(float thickness) { + this.discThickness = thickness; + } + public boolean isBoomerang() { return boomerang; } + public void setBoomerang(boolean boomerang) { + this.boomerang = boomerang; + } + + public int getBoomerangDelay() { + return boomerangDelay; + } + + public void setBoomerangDelay(int delay) { + this.boomerangDelay = delay; + } + public boolean isReturning() { return returning; } + public boolean isVertical() { + return vertical; + } + + public void setVertical(boolean vertical) { + this.vertical = vertical; + } + + /** + * Get the yaw angle (degrees) from motion vector for vertical disc orientation. + * During charging, uses owner's facing direction. + */ + public float getTravelYaw() { + if (isCharging()) { + Entity owner = previewMode ? previewOwner : getOwnerEntity(); + if (owner != null) { + return owner.rotationYaw; + } + } + double speed = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (speed > 0.001) { + return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); + } + return 0.0f; + } + // ==================== NBT ==================== @Override @@ -550,13 +483,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40; this.discRadius = nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f; this.discThickness = nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f; + this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + // Charging state (common fields handled by base) + readChargingNBT(nbt); this.targetDiscRadius = nbt.hasKey("TargetDiscRadius") ? nbt.getFloat("TargetDiscRadius") : this.discRadius; this.targetDiscThickness = nbt.hasKey("TargetDiscThickness") ? nbt.getFloat("TargetDiscThickness") : this.discThickness; } @@ -567,11 +497,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { nbt.setInteger("BoomerangDelay", boomerangDelay); nbt.setFloat("DiscRadius", discRadius); nbt.setFloat("DiscThickness", discThickness); + nbt.setBoolean("Vertical", vertical); nbt.setBoolean("Returning", returning); - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); + // Charging state (common fields handled by base) + writeChargingNBT(nbt); nbt.setFloat("TargetDiscRadius", targetDiscRadius); nbt.setFloat("TargetDiscThickness", targetDiscThickness); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 1a036573e..5adabc4b6 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -1,9 +1,9 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -36,54 +36,19 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // Direction (normalized) private double dirX, dirY, dirZ; + // Lock vertical direction after firing (only update yaw, keep pitch fixed) + private boolean lockVerticalDirection = false; + // Track hit entities to avoid double-damage private Set hitEntities = new HashSet<>(); // End point for rendering private double endX, endY, endZ; - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); - private float targetSize = 1.0f; // Full size to grow to during charging - - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - public EntityAbilityLaser(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if orb is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor with all parameters using data classes. */ @@ -130,25 +95,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endZ = z; } - /** - * Setup this orb in charging mode (for windup phase). - * The orb will grow from 0 to orbSize over chargeDuration ticks. - * Position follows the owner based on anchor point. - */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.targetSize = this.size; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - } - @Override protected void updateRotation() { // Laser doesn't rotate @@ -167,6 +113,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { return; } + // Track owner's anchor position and rotation each tick + // so the laser follows the NPC's facing direction + updateLaserOriginAndDirection(); + if (!fullyExtended) { // Expand the laser currentLength += expansionSpeed; @@ -189,27 +139,76 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } else { // Laser is fully extended, count down linger time ticksSinceFullExtension++; + + // Update end point during linger (origin/direction may still change) + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + if (ticksSinceFullExtension >= lingerTicks) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); } } } - public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; + /** + * Update laser origin and direction from the owner's current anchor position and rotation. + * Called each tick so the laser follows the NPC when tracking a target. + */ + private void updateLaserOriginAndDirection() { + Entity owner = getOwnerEntity(); + if (owner == null || !(owner instanceof EntityLivingBase)) return; + EntityLivingBase livingOwner = (EntityLivingBase) owner; + + // Update origin from anchor point + if (anchorData != null) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData); + startX = pos.xCoord; + startY = pos.yCoord; + startZ = pos.zCoord; + } else { + startX = owner.posX; + startY = owner.posY + owner.height * 0.7; + startZ = owner.posZ; + } + + // Update direction from owner's current rotation + float yaw = (float) Math.toRadians(owner.rotationYaw); + if (lockVerticalDirection) { + // Only update horizontal direction (yaw), keep vertical (pitch) fixed + double horizontalLen = Math.sqrt(dirX * dirX + dirZ * dirZ); + if (horizontalLen < 0.001) horizontalLen = 1.0; + dirX = -Math.sin(yaw) * horizontalLen; + dirZ = Math.cos(yaw) * horizontalLen; + } else { + float pitch = (float) Math.toRadians(owner.rotationPitch); + dirX = -Math.sin(yaw) * Math.cos(pitch); + dirY = -Math.sin(pitch); + dirZ = Math.cos(yaw) * Math.cos(pitch); + } + + // Keep entity positioned at origin + prevPosX = startX; + prevPosY = startY; + prevPosZ = startZ; + setPosition(startX, startY, startZ); + } + + public void startMoving(EntityLivingBase target) { setCharging(false); - // Update start position to current position + // Initialize from current anchor position + // updateLaserOriginAndDirection() will keep these updated each tick startX = posX; startY = posY; startZ = posZ; - // Always derive direction from the owner's current yaw/pitch. - // This ensures the laser fires in the direction the NPC is visually facing, - // which matches the telegraph line direction regardless of Lock Movement mode. + // Set initial direction from owner's rotation Entity owner = getOwnerEntity(); - if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); @@ -217,7 +216,6 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.dirY = -Math.sin(pitch); this.dirZ = Math.cos(yaw) * Math.cos(pitch); } else if (target != null) { - // Fallback: aim at target if owner is somehow unavailable double dx = target.posX - startX; double dy = (target.posY + target.getEyeHeight() - 0.4) - startY; double dz = target.posZ - startZ; @@ -229,12 +227,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } } - setPosition(endX, endY, endZ); - - // Initialize end point - this.endX = posX; - this.endY = posY; - this.endZ = posZ; + // Initialize end point at start (will expand from here) + this.endX = startX; + this.endY = startY; + this.endZ = startZ; } private void checkBlockCollision() { @@ -244,6 +240,9 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(start, end, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } // Laser stops at block currentLength = (float) Math.sqrt( (blockHit.hitVec.xCoord - startX) * (blockHit.hitVec.xCoord - startX) + @@ -271,53 +270,15 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } } - /** - * Update during charging state - follow owner based on anchor point. - */ - private void updateCharging() { - chargeTick++; - - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - - // Grow size based on charge progress - float progress = getChargeProgress(); - this.size = targetSize * progress; - - // Calculate position based on anchor point, offset downward by half size to center - if (owner instanceof EntityLivingBase) { - Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - } - } - - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - private void checkEntityCollisionAlongLine() { - // Check collision along the entire laser line - // Use a slightly expanded AABB for the full line - double minX = Math.min(startX, endX) - laserWidth; - double minY = Math.min(startY, endY) - laserWidth; - double minZ = Math.min(startZ, endZ) - laserWidth; - double maxX = Math.max(startX, endX) + laserWidth; - double maxY = Math.max(startY, endY) + laserWidth; - double maxZ = Math.max(startZ, endZ) + laserWidth; + // Expand search AABB by entity sizes to ensure we find all potential targets + double expand = Math.max(laserWidth, 1.0); + double minX = Math.min(startX, endX) - expand; + double minY = Math.min(startY, endY) - expand; + double minZ = Math.min(startZ, endZ) - expand; + double maxX = Math.max(startX, endX) + expand; + double maxY = Math.max(startY, endY) + expand; + double maxZ = Math.max(startZ, endZ) + expand; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); @@ -328,7 +289,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { if (shouldIgnoreEntity(entity)) continue; if (hitEntities.contains(entity.getEntityId())) continue; - // Check if entity is close to the laser line + // Check if entity's bounding box intersects with the laser line if (isEntityOnLine(entity)) { hitEntities.add(entity.getEntityId()); applyDamage(entity); @@ -339,46 +300,94 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } /** - * Check if an entity intersects with the laser line. + * Check if an entity's bounding box intersects with the laser line. + * Uses separate XZ (horizontal) and Y (vertical) checks against + * the entity's full bounding box rather than just its center point. */ private boolean isEntityOnLine(EntityLivingBase entity) { - // Get entity center double ex = entity.posX; - double ey = entity.posY + entity.height * 0.5; double ez = entity.posZ; - // Vector from start to entity + // Project entity XZ position onto the laser line direction double vx = ex - startX; - double vy = ey - startY; double vz = ez - startZ; - - // Project onto line direction - double dot = vx * dirX + vy * dirY + vz * dirZ; - - // Clamp to line segment + // Project using horizontal direction components only + double dirLenXZ = Math.sqrt(dirX * dirX + dirZ * dirZ); + double dot; + if (dirLenXZ > 0.001) { + dot = (vx * dirX + vz * dirZ) / (dirLenXZ * dirLenXZ) * dirLenXZ; + // Remap to full 3D parameter + dot = (vx * dirX + vz * dirZ + (entity.posY + entity.height * 0.5 - startY) * dirY); + } else { + // Laser fires nearly straight up/down - use full 3D projection + dot = vx * dirX + (entity.posY + entity.height * 0.5 - startY) * dirY + vz * dirZ; + } dot = Math.max(0, Math.min(dot, currentLength)); - // Closest point on line + // Closest point on laser line at this parameter double closestX = startX + dirX * dot; double closestY = startY + dirY * dot; double closestZ = startZ + dirZ * dot; - // Distance from entity to closest point - double distSq = (ex - closestX) * (ex - closestX) + - (ey - closestY) * (ey - closestY) + - (ez - closestZ) * (ez - closestZ); + // XZ distance check: entity center vs laser line point + // Use minimum collision width so visually thin lasers still hit reliably + double xzDistSq = (ex - closestX) * (ex - closestX) + (ez - closestZ) * (ez - closestZ); + double effectiveWidth = Math.max(laserWidth, 0.5); + double hitRadiusXZ = effectiveWidth * 0.5 + entity.width * 0.5; + if (xzDistSq > hitRadiusXZ * hitRadiusXZ) return false; - // Hit if within laser width + entity radius - double hitRadius = laserWidth * 0.5 + entity.width * 0.5; - return distSq <= hitRadius * hitRadius; + // Y overlap check: laser point vs entity's full height range + double entityMinY = entity.boundingBox.minY; + double entityMaxY = entity.boundingBox.maxY; + double laserHalfWidth = effectiveWidth * 0.5; + + // Check if laser Y is within entity's height range (expanded by laser half-width) + if (closestY < entityMinY - laserHalfWidth) return false; + if (closestY > entityMaxY + laserHalfWidth) return false; + + return true; } // ==================== GETTERS FOR RENDERER ==================== + public void setLockVerticalDirection(boolean lock) { + this.lockVerticalDirection = lock; + } + + public boolean isLockVerticalDirection() { + return lockVerticalDirection; + } + public float getLaserWidth() { return laserWidth; } + public void setLaserWidth(float width) { + this.laserWidth = width; + } + + public float getExpansionSpeed() { + return expansionSpeed; + } + + public void setExpansionSpeed(float speed) { + this.expansionSpeed = speed; + } + + public int getLingerTicks() { + return lingerTicks; + } + + public void setLingerTicks(int ticks) { + this.lingerTicks = ticks; + } + + public void setDirection(double x, double y, double z) { + this.dirX = x; + this.dirY = y; + this.dirZ = z; + } + public float getCurrentLength() { return currentLength; } @@ -447,14 +456,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endY = nbt.getDouble("EndY"); this.endZ = nbt.getDouble("EndZ"); - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; - this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; - anchorData.readNBT(nbt); + readChargingNBT(nbt); } @Override @@ -471,12 +473,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { nbt.setDouble("EndY", endY); nbt.setDouble("EndZ", endZ); - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); - nbt.setFloat("TargetSize", targetSize); - anchorData.writeNBT(nbt); + writeChargingNBT(nbt); } /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index 73e8c26f3..2eb5c0084 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -3,6 +3,7 @@ package kamkeel.npcs.entity; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; +import noppes.npcs.EventHooks; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; @@ -20,47 +21,10 @@ import java.util.List; */ public class EntityAbilityOrb extends EntityAbilityProjectile { - // Charging state (during windup) - private boolean charging = false; - private int chargeDuration = 40; - private int chargeTick = 0; - private float targetSize = 1.0f; // Full size to grow to during charging - - // Data watcher index for charging state (synced to clients) - private static final int DW_CHARGING = 20; - public EntityAbilityOrb(World world) { super(world); } - @Override - protected void entityInit() { - super.entityInit(); - // Register data watcher for charging state - this.dataWatcher.addObject(DW_CHARGING, (byte) 0); - } - - /** - * Check if orb is in charging state (synced via data watcher). - * In preview mode, uses local field since data watcher isn't synced. - */ - public boolean isCharging() { - if (previewMode) { - return this.charging; - } - return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; - } - - /** - * Set charging state (server only, synced to clients via data watcher). - */ - private void setCharging(boolean value) { - this.charging = value; - if (!worldObj.isRemote) { - this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); - } - } - /** * Full constructor using data classes for grouped parameters. */ @@ -77,43 +41,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { this.homingData = homing; // Calculate initial velocity toward target - if (target != null) { - double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; - double dz = target.posZ - z; - double len = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (len > 0) { - this.motionX = (dx / len) * homing.speed; - this.motionY = (dy / len) * homing.speed; - this.motionZ = (dz / len) * homing.speed; - } - } else { - // Fire in NPC's facing direction - float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * homing.speed; - this.motionY = -Math.sin(pitch) * homing.speed; - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * homing.speed; - } - } - - /** - * Setup this orb in charging mode (for windup phase). - * The orb will grow from 0 to orbSize over chargeDuration ticks. - * Position follows the owner based on anchor point. - */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { - setCharging(true); - this.chargeDuration = chargeDuration; - this.chargeTick = 0; - this.anchorData = anchor; - this.targetSize = this.size; - this.size = 0.01f; - this.renderCurrentSize = 0.01f; - this.prevRenderSize = 0.01f; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; + calculateInitialVelocity(owner, target, x, y, z); } /** @@ -161,8 +89,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Start preview firing (simulates firing toward a point in front of NPC). */ public void startPreviewFiring() { - if (!isCharging()) return; - setCharging(false); // Update start position to current position @@ -196,10 +122,11 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Called by ability when windup ends. */ public void startMoving(EntityLivingBase target) { - if (!isCharging()) return; - setCharging(false); + // For player casters, snap to look vector for crosshair-aligned launch + snapToPlayerLookVector(); + // Update start position to current position startX = posX; startY = posY; @@ -299,47 +226,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { return true; } - private void updateHoming() { - if (!isHoming()) return; - - Entity target = getTargetEntity(); - if (target == null || !target.isEntityAlive()) return; - - double dx = target.posX - posX; - double dy = (target.posY + target.getEyeHeight()) - posY; - double dz = target.posZ - posZ; - double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - - if (dist <= getHomingRange() && dist > 0) { - // Calculate effective homing strength - increases when closer to commit to target - // This prevents orbiting behavior at close range - float effectiveStrength = getHomingStrength(); - if (dist < getHomingRange() * 0.3) { - // Within 30% of homing range, dramatically increase strength to commit - effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); - } else if (dist < getHomingRange() * 0.6) { - // Within 60% of homing range, moderately increase strength - effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); - } - - double desiredVX = (dx / dist) * getSpeed(); - double desiredVY = (dy / dist) * getSpeed(); - double desiredVZ = (dz / dist) * getSpeed(); - - motionX += (desiredVX - motionX) * effectiveStrength; - motionY += (desiredVY - motionY) * effectiveStrength; - motionZ += (desiredVZ - motionZ) * effectiveStrength; - - // Normalize to maintain speed - double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); - if (vLen > 0) { - motionX = (motionX / vLen) * getSpeed(); - motionY = (motionY / vLen) * getSpeed(); - motionZ = (motionZ / vLen) * getSpeed(); - } - } - } - private void checkBlockCollision() { Vec3 currentPos = Vec3.createVectorHelper(posX, posY, posZ); Vec3 nextPos = Vec3.createVectorHelper(posX + motionX, posY + motionY, posZ + motionZ); @@ -347,6 +233,9 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { MovingObjectPosition blockHit = worldObj.func_147447_a(currentPos, nextPos, false, true, false); if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileBlockImpact(this, blockHit.blockX, blockHit.blockY, blockHit.blockZ); + } hasHit = true; if (isExplosive()) { posX = blockHit.hitVec.xCoord; @@ -384,47 +273,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { } } - /** - * Update during charging state - follow owner based on anchor point. - */ - private void updateCharging() { - chargeTick++; - - Entity owner = getOwnerEntity(); - if (owner == null || owner.isDead) { - setDead(); - return; - } - - // Grow size based on charge progress - float progress = getChargeProgress(); - this.size = targetSize * progress; - - // Calculate position based on anchor point, offset downward by half size to center - if (owner instanceof EntityLivingBase) { - Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); - setPosition(pos.xCoord, pos.yCoord, pos.zCoord); - } - } - - /** - * Get the charge progress (0-1). - */ - public float getChargeProgress() { - if (chargeDuration <= 0) return 1.0f; - return Math.min(1.0f, (float) chargeTick / chargeDuration); - } - - /** - * Get interpolated charge progress for smooth rendering. - */ - public float getInterpolatedChargeProgress(float partialTicks) { - if (chargeDuration <= 0) return 1.0f; - float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); - float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); - return prevProgress + (currProgress - prevProgress) * partialTicks; - } - // ==================== GETTERS ==================== // Legacy getter for renderer compatibility @@ -436,22 +284,11 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { - // Charging state - boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); - this.charging = isCharging; - this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); - this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; - this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; - this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; + readChargingNBT(nbt); } @Override protected void writeProjectileNBT(NBTTagCompound nbt) { - // Charging state - nbt.setBoolean("Charging", isCharging()); - nbt.setInteger("ChargeDuration", chargeDuration); - nbt.setInteger("ChargeTick", chargeTick); - anchorData.writeNBT(nbt); - nbt.setFloat("TargetSize", targetSize); + writeChargingNBT(nbt); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 7080ce2ef..99c66edaa 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -8,8 +8,9 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilityEffect; import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.IAbilityDamageHandler; + import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -17,14 +18,19 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; import net.minecraft.world.World; +import noppes.npcs.EventHooks; import noppes.npcs.NpcDamageSource; -import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntity; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.scripted.NpcAPI; +import java.lang.ref.WeakReference; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -34,7 +40,38 @@ import java.util.Map; * * Design inspired by LouisXIV's energy attack system. */ -public abstract class EntityAbilityProjectile extends Entity implements IEnergyProjectile, IEntityAdditionalSpawnData { +public abstract class EntityAbilityProjectile extends Entity implements IEntityAdditionalSpawnData { + + // ==================== ACTIVE PROJECTILE TRACKING ==================== + private static final Map>> activeProjectiles = new HashMap<>(); + + public static void trackProjectile(EntityAbilityProjectile projectile) { + int ownerId = projectile.getOwnerEntityId(); + if (ownerId < 0) return; + List> refs = activeProjectiles.get(ownerId); + if (refs == null) { + refs = new ArrayList<>(); + activeProjectiles.put(ownerId, refs); + } + refs.add(new WeakReference<>(projectile)); + } + + public static List getActiveProjectiles(int ownerEntityId) { + List> refs = activeProjectiles.get(ownerEntityId); + if (refs == null) return Collections.emptyList(); + List result = new ArrayList<>(); + Iterator> it = refs.iterator(); + while (it.hasNext()) { + EntityAbilityProjectile p = it.next().get(); + if (p == null || p.isDead) { + it.remove(); + } else { + result.add(p); + } + } + if (refs.isEmpty()) activeProjectiles.remove(ownerEntityId); + return result; + } // ==================== VISUAL PROPERTIES ==================== protected float size = 1.0f; @@ -73,7 +110,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP protected double startX, startY, startZ; protected int ownerEntityId = -1; protected int targetEntityId = -1; - protected int siblingEntityId = -1; // ==================== STATE ==================== protected boolean hasHit = false; @@ -83,6 +119,13 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP /** The ability that spawned this projectile. Transient, not saved to NBT. */ protected transient Ability sourceAbility = null; + // ==================== CHARGING STATE ==================== + protected boolean charging = false; + protected int chargeDuration = 40; + protected int chargeTick = 0; + protected float targetSize = 1.0f; + protected static final int DW_CHARGING = 20; + // ==================== ROTATION INTERPOLATION ==================== public float prevRotationValX, prevRotationValY, prevRotationValZ; public float rotationValX, rotationValY, rotationValZ; @@ -107,7 +150,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP /** * Initialize common properties using data classes. Call from subclass constructors. */ - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, EntityAbilityProjectile sibling, + protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, double x, double y, double z, float size, EnergyDisplayData display, EnergyCombatData combat, EnergyLightningData lightning, EnergyLifespanData lifespan, @@ -119,7 +162,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.ownerEntityId = owner.getEntityId(); this.targetEntityId = target != null ? target.getEntityId() : -1; - this.siblingEntityId = sibling != null ? sibling.getEntityId() : -1; // Visual this.size = size; @@ -135,18 +177,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.prevRenderSize = size; } - // Initialize projectile without a sibling - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, float size, - EnergyDisplayData display, EnergyCombatData combat, - EnergyLightningData lightning, EnergyLifespanData lifespan, - EnergyTrajectoryData trajectory) { - initProjectile(owner, target, null, x, y, z, size, display, combat, lightning, lifespan, trajectory); - } - @Override protected void entityInit() { - // No DataWatcher needed - using IEntityAdditionalSpawnData with NBT + this.dataWatcher.addObject(DW_CHARGING, (byte) 0); } @Override @@ -176,6 +209,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Skip super.onUpdate() in preview mode to avoid world checks if (!previewMode) { super.onUpdate(); + + // Track on first server tick + if (ticksExisted == 1 && !worldObj.isRemote) { + trackProjectile(this); + } } // Update rotation @@ -186,16 +224,20 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Skip lifetime/distance checks in preview mode if (!previewMode) { - // Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct + // Only self-destruct if the owner is confirmed dead/killed. + // A null owner (unloaded/out of chunk) is NOT treated as dead — + // the projectile keeps acting normally and deathWorldTime handles lifetime. if (ownerEntityId >= 0 && ticksExisted > 5) { Entity owner = worldObj.getEntityByID(ownerEntityId); - if (owner == null || owner.isDead) { - this.setDead(); - return; - } - if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { - this.setDead(); - return; + if (owner != null) { + if (owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } } } @@ -206,12 +248,18 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Check lifespan using world time (survives chunk unload/reload) if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); return; } // Check max distance (subclass can override if needed) if (checkMaxDistance()) { + if (!worldObj.isRemote) { + EventHooks.onEnergyProjectileExpired(this); + } this.setDead(); return; } @@ -224,6 +272,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP // Subclass-specific update updateProjectile(); + + // Fire tick event (server-side, non-preview only) + if (!previewMode && !worldObj.isRemote) { + EventHooks.onEnergyProjectileTick(this); + } } /** @@ -326,19 +379,25 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP protected void applyDamage(EntityLivingBase target, float dmg, float kb) { if (previewMode) return; // Skip damage in preview mode + + // Fire entity impact event (may cancel or modify damage) + if (!worldObj.isRemote) { + float result = EventHooks.onEnergyProjectileEntityImpact(this, target, dmg); + if (result < 0) return; // Event was cancelled + dmg = result; + } + Entity owner = getOwnerEntity(); - // Check for external damage handler (e.g., DBC Addon) + // Check for ability extenders (e.g., DBC Addon damage routing) boolean handled = false; if (sourceAbility != null && owner instanceof EntityLivingBase) { - IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); - if (handler != null) { - double dx = target.posX - posX; - double dz = target.posZ - posZ; - float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; - handled = handler.handleDamage(sourceAbility, (EntityLivingBase) owner, target, - dmg, kb, kbUp, dx, dz); - } + double dx = target.posX - posX; + double dz = target.posZ - posZ; + float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; + handled = AbilityController.Instance.fireOnAbilityDamage( + sourceAbility, (EntityLivingBase) owner, target, + dmg, kb, kbUp, dx, dz); } if (!handled) { @@ -428,6 +487,194 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP } } + // ==================== LAUNCH HELPERS ==================== + + /** + * For player casters, snap the projectile to a position along the player's look vector. + * This ensures projectiles launch aligned with the crosshair rather than from the hand anchor. + * Only affects player casters; NPC projectiles launch from their anchor position as configured. + * Should be called in startMoving/startFiring BEFORE setting startX/Y/Z. + */ + protected void snapToPlayerLookVector() { + Entity owner = getOwnerEntity(); + if (!(owner instanceof EntityPlayer)) return; + + Vec3 look = owner.getLookVec(); + double eyeY = owner.posY + owner.getEyeHeight(); + float frontDist = Math.max(0.5f, size * 0.5f); + + double newX = owner.posX + look.xCoord * frontDist; + double newY = eyeY + look.yCoord * frontDist; + double newZ = owner.posZ + look.zCoord * frontDist; + + setPosition(newX, newY, newZ); + prevPosX = newX; + prevPosY = newY; + prevPosZ = newZ; + } + + // ==================== CHARGING METHODS ==================== + + /** + * Check if entity is in charging state (synced via data watcher). + * In preview mode, uses local field since data watcher isn't synced. + */ + public boolean isCharging() { + if (previewMode) return this.charging; + return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; + } + + /** + * Set charging state (server only, synced to clients via data watcher). + */ + protected void setCharging(boolean value) { + this.charging = value; + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); + } + } + + public float getChargeProgress() { + if (chargeDuration <= 0) return 1.0f; + return Math.min(1.0f, (float) chargeTick / chargeDuration); + } + + public float getInterpolatedChargeProgress(float partialTicks) { + if (chargeDuration <= 0) return 1.0f; + float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); + float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); + return prevProgress + (currProgress - prevProgress) * partialTicks; + } + + /** + * Setup this entity in charging mode (for windup phase). + * Grows from 0 to current size over chargeDuration ticks. + * Subclasses with different charging behavior should override or use their own method. + */ + public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + setCharging(true); + this.chargeDuration = chargeDuration; + this.chargeTick = 0; + this.anchorData = anchor; + this.targetSize = this.size; + this.size = 0.01f; + this.renderCurrentSize = 0.01f; + this.prevRenderSize = 0.01f; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + } + + /** + * Update during charging state - grow size and follow anchor. + * Default implementation grows {@code size} from 0 to {@code targetSize}. + * Override in subclasses for type-specific charging (Disc, Beam). + * + * Note: Owner death checks are handled by onUpdate() before this is called. + */ + protected void updateCharging() { + chargeTick++; + float progress = getChargeProgress(); + this.size = targetSize * progress; + Entity owner = getOwnerEntity(); + if (owner instanceof EntityLivingBase) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + } + } + + // ==================== HOMING ==================== + + /** + * Update homing toward target. Uses position-based homing with distance-scaled strength. + * Override in subclasses for type-specific homing (e.g. Beam uses head offset). + */ + protected void updateHoming() { + if (!isHoming()) return; + Entity target = getTargetEntity(); + if (target == null || !target.isEntityAlive()) return; + + double dx = target.posX - posX; + double dy = (target.posY + target.getEyeHeight()) - posY; + double dz = target.posZ - posZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + + if (dist <= getHomingRange() && dist > 0) { + float effectiveStrength = getHomingStrength(); + if (dist < getHomingRange() * 0.3) { + effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); + } else if (dist < getHomingRange() * 0.6) { + effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); + } + + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); + + motionX += (desiredVX - motionX) * effectiveStrength; + motionY += (desiredVY - motionY) * effectiveStrength; + motionZ += (desiredVZ - motionZ) * effectiveStrength; + + double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); + if (vLen > 0) { + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); + } + } + } + + // ==================== VELOCITY HELPERS ==================== + + /** + * Calculate initial velocity toward target or forward based on owner facing. + * Call from subclass constructors after initProjectile(). + */ + protected void calculateInitialVelocity(EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z) { + if (target != null) { + double dx = target.posX - x; + double dy = (target.posY + target.getEyeHeight()) - y; + double dz = target.posZ - z; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + this.motionX = (dx / len) * getSpeed(); + this.motionY = (dy / len) * getSpeed(); + this.motionZ = (dz / len) * getSpeed(); + } + } else { + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + this.motionY = -Math.sin(pitch) * getSpeed(); + this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); + } + } + + // ==================== CHARGING NBT ==================== + + /** + * Read common charging state from NBT. Call from subclass readProjectileNBT(). + */ + protected void readChargingNBT(NBTTagCompound nbt) { + boolean isChargingVal = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); + this.charging = isChargingVal; + this.dataWatcher.updateObject(DW_CHARGING, (byte) (isChargingVal ? 1 : 0)); + this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; + this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; + } + + /** + * Write common charging state to NBT. Call from subclass writeProjectileNBT(). + */ + protected void writeChargingNBT(NBTTagCompound nbt) { + nbt.setBoolean("Charging", isCharging()); + nbt.setInteger("ChargeDuration", chargeDuration); + nbt.setInteger("ChargeTick", chargeTick); + nbt.setFloat("TargetSize", targetSize); + } + // ==================== ENTITY HELPERS ==================== public Entity getOwnerEntity() { @@ -439,12 +686,14 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP return worldObj.getEntityByID(ownerEntityId); } - @Override public int getOwnerEntityId() { return ownerEntityId; } - @Override + public void setOwnerEntityId(int id) { + this.ownerEntityId = id; + } + public IEntity getOwner() { if (previewMode) return null; if (getOwnerEntity() == null) return null; @@ -459,42 +708,27 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.previewOwner = owner; } - @Override public int getTargetEntityId() { return targetEntityId; } + public void setTargetEntityId(int id) { + this.targetEntityId = id; + } + public Entity getTargetEntity() { if (targetEntityId == -1) return null; return worldObj.getEntityByID(targetEntityId); } - @Override public IEntity getTarget() { if (getTargetEntity() == null) return null; return NpcAPI.Instance().getIEntity(getTargetEntity()); } - @Override - public int getSiblingEntityId() { - return siblingEntityId; - } - - @Override - public void setSiblingEntityId(int siblingEntityId) { - if (!(worldObj.getEntityByID(siblingEntityId) instanceof EntityAbilityProjectile)) return; - - this.siblingEntityId = siblingEntityId; - } - - @Override - public IEnergyProjectile getSibling() { - if (siblingEntityId == -1) return null; - return (EntityAbilityProjectile) worldObj.getEntityByID(siblingEntityId); - } - /** * Check if an entity should be ignored for collision. + * Ignores: the owner, same-faction NPCs, and other projectiles from the same caster. */ protected boolean shouldIgnoreEntity(Entity entity) { Entity owner = getOwnerEntity(); @@ -506,168 +740,144 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP if (ownerNpc.faction.id == targetNpc.faction.id) return true; } - if (entity.getEntityId() == getSiblingEntityId()) - return true; + // Ignore other projectiles from the same caster (e.g. multi-projectile abilities) + if (entity instanceof EntityAbilityProjectile) { + EntityAbilityProjectile other = (EntityAbilityProjectile) entity; + if (other.ownerEntityId == this.ownerEntityId) return true; + } return false; } - // ==================== VISUAL GETTERS ==================== + // ==================== VISUAL GETTERS & SETTERS ==================== - @Override - public float getSize() { - return size; + public float getSize() { return size; } + public void setProjectileSize(float size) { + this.size = size; + this.renderCurrentSize = size; + this.prevRenderSize = size; } - @Override - public int getInnerColor() { - return displayData.getInnerColor(); + /** + * Set the start position for distance calculations. + * Used by factory methods when creating projectiles without the full constructor. + */ + public void setStartPosition(double x, double y, double z) { + this.startX = x; + this.startY = y; + this.startZ = z; } - @Override - public int getOuterColor() { - return displayData.getOuterColor(); - } + public int getInnerColor() { return displayData.getInnerColor(); } + public void setInnerColor(int color) { displayData.setInnerColor(color); } - @Override - public boolean isOuterColorEnabled() { - return displayData.isOuterColorEnabled(); - } + public int getOuterColor() { return displayData.getOuterColor(); } + public void setOuterColor(int color) { displayData.setOuterColor(color); } - @Override - public float getOuterColorWidth() { - return displayData.getOuterColorWidth(); - } + public boolean isOuterColorEnabled() { return displayData.isOuterColorEnabled(); } + public void setOuterColorEnabled(boolean enabled) { displayData.setOuterColorEnabled(enabled); } - @Override - public float getOuterColorAlpha() { - return displayData.getOuterColorAlpha(); - } + public float getOuterColorWidth() { return displayData.getOuterColorWidth(); } + public void setOuterColorWidth(float width) { displayData.setOuterColorWidth(width); } - @Override - public float getRotationSpeed() { - return displayData.getRotationSpeed(); - } + public float getOuterColorAlpha() { return displayData.getOuterColorAlpha(); } + public void setOuterColorAlpha(float alpha) { displayData.setOuterColorAlpha(alpha); } + + public float getRotationSpeed() { return displayData.getRotationSpeed(); } + public void setRotationSpeed(float speed) { displayData.setRotationSpeed(speed); } // ==================== ROTATION GETTERS ==================== - @Override public float getInterpolatedRotationX(float partialTicks) { return this.prevRotationValX + (this.rotationValX - this.prevRotationValX) * partialTicks; } - @Override public float getInterpolatedRotationY(float partialTicks) { return this.prevRotationValY + (this.rotationValY - this.prevRotationValY) * partialTicks; } - @Override public float getInterpolatedRotationZ(float partialTicks) { return this.prevRotationValZ + (this.rotationValZ - this.prevRotationValZ) * partialTicks; } - @Override public float getInterpolatedSize(float partialTicks) { return this.prevRenderSize + (this.renderCurrentSize - this.prevRenderSize) * partialTicks; } - // ==================== LIGHTNING GETTERS ==================== + // ==================== LIGHTNING GETTERS & SETTERS ==================== - @Override - public boolean hasLightningEffect() { - return lightningData.isLightningEffect(); - } + public boolean hasLightningEffect() { return lightningData.isLightningEffect(); } + public void setLightningEffect(boolean enabled) { lightningData.setLightningEffect(enabled); } - @Override - public float getLightningDensity() { - return lightningData.getLightningDensity(); - } + public float getLightningDensity() { return lightningData.getLightningDensity(); } + public void setLightningDensity(float density) { lightningData.setLightningDensity(density); } - @Override - public float getLightningRadius() { - return lightningData.getLightningRadius(); - } + public float getLightningRadius() { return lightningData.getLightningRadius(); } + public void setLightningRadius(float radius) { lightningData.setLightningRadius(radius); } - @Override - public int getLightningFadeTime() { - return lightningData.getLightningFadeTime(); - } + public int getLightningFadeTime() { return lightningData.getLightningFadeTime(); } + public void setLightningFadeTime(int ticks) { lightningData.setLightningFadeTime(ticks); } - // ==================== LIFESPAN GETTERS ==================== + // ==================== LIFESPAN GETTERS & SETTERS ==================== - @Override public float getMaxDistance() { return lifespanData.getMaxDistance(); } + public void setMaxDistance(float distance) { lifespanData.setMaxDistance(distance); } - @Override public int getMaxLifetime() { return lifespanData.getMaxLifetime(); } + public void setMaxLifetime(int ticks) { lifespanData.setMaxLifetime(ticks); } - // ==================== COMBAT GETTERS ==================== + // ==================== COMBAT GETTERS & SETTERS ==================== - @Override public float getDamage() { return combatData.getDamage(); } + public void setCombatDamage(float damage) { combatData.setDamage(damage); } - @Override public float getKnockback() { return combatData.knockback; } + public void setCombatKnockback(float knockback) { combatData.setKnockback(knockback); } - @Override public float getKnockbackUp() { return combatData.knockbackUp; } + public void setCombatKnockbackUp(float knockbackUp) { combatData.setKnockbackUp(knockbackUp); } - @Override public boolean isExplosive() { return combatData.isExplosive(); } + public void setExplosive(boolean explosive) { combatData.setExplosive(explosive); } - @Override public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float radius) { combatData.setExplosionRadius(radius); } - @Override public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float falloff) { combatData.setExplosionDamageFalloff(falloff); } - // ==================== HOMING GETTERS ==================== + // ==================== HOMING GETTERS & SETTERS ==================== - @Override public boolean isHoming() { return homingData.isHoming(); } + public void setHomingEnabled(boolean homing) { homingData.setHoming(homing); } - @Override public float getHomingStrength() { return homingData.getHomingStrength(); } + public void setHomingStrength(float strength) { homingData.setHomingStrength(strength); } - @Override public float getHomingRange() { return homingData.getHomingRange(); } + public void setHomingRange(float range) { homingData.setHomingRange(range); } - // ==================== TRAJECTORY GETTERS ==================== + // ==================== SPEED & ANCHOR GETTERS & SETTERS ==================== - - - // ==================== ANCHOR GETTERS ==================== - - @Override public float getSpeed() { return homingData.getSpeed(); } + public void setSpeed(float speed) { homingData.setSpeed(speed); } public AnchorPoint getAnchorPoint() { return anchorData.getAnchorPoint(); } - @Override public int getAnchor() { return anchorData.getAnchor(); } - - @Override public float getAnchorOffsetX() { return anchorData.getAnchorOffsetX(); } - - @Override public float getAnchorOffsetY() { return anchorData.getAnchorOffsetY(); } - - @Override public float getAnchorOffsetZ() { return anchorData.getAnchorOffsetZ(); } // ==================== MOVEMENT GETTERS ==================== - @Override public double getStartX() { return startX; } + public double getStartX() { return startX; } + public double getStartY() { return startY; } + public double getStartZ() { return startZ; } - @Override public double getStartY() { return startY; } + // ==================== STATE GETTERS ==================== - @Override public double getStartZ() { return startZ; } - - @Override public double getMotionX() { return motionX; } - - @Override public double getMotionY() { return motionY; } - - @Override public double getMotionZ() { return motionZ; } + public boolean getHasHit() { return hasHit; } // ==================== BRIGHTNESS ==================== @@ -719,16 +929,15 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP this.ownerEntityId = nbt.getInteger("OwnerId"); this.targetEntityId = nbt.getInteger("TargetId"); - this.siblingEntityId = nbt.getInteger("SiblingId"); this.motionX = nbt.getDouble("MotionX"); this.motionY = nbt.getDouble("MotionY"); this.motionZ = nbt.getDouble("MotionZ"); - if (this.worldObj != null && this.worldObj.isRemote) { - this.renderCurrentSize = this.size; - this.prevRenderSize = this.size; - } + // Always initialize render size from NBT size so entities + // loading in from outside render distance render correctly + this.renderCurrentSize = this.size; + this.prevRenderSize = this.size; anchorData.readNBT(nbt); combatData.readNBT(nbt); @@ -762,7 +971,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP nbt.setInteger("OwnerId", ownerEntityId); nbt.setInteger("TargetId", targetEntityId); - nbt.setInteger("SiblingId", targetEntityId); nbt.setDouble("MotionX", motionX); nbt.setDouble("MotionY", motionY); @@ -795,7 +1003,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP NBTTagCompound compound = new NBTTagCompound(); this.writeEntityToNBT(compound); cpw.mods.fml.common.network.ByteBufUtils.writeTag(buffer, compound); - } catch (Exception ignored) {} + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error writing ability projectile spawn data", e); + } } @Override @@ -805,7 +1015,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEnergyP if (compound != null) { this.readEntityFromNBT(compound); } - } catch (Exception ignored) {} + } catch (Exception e) { + noppes.npcs.LogWriter.error("Error reading ability projectile spawn data", e); + } } // ==================== COLLISION SETTINGS ==================== diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index 8eceb11de..6f0068d26 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -60,6 +60,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa private int maxTicks = 400; private long deathWorldTime = -1; + // Preview mode + private boolean previewMode = false; + private EntityLivingBase previewOwner = null; + // Damage state private transient int ticksSinceDamage = 0; private transient Set hitThisTick = new HashSet<>(); @@ -140,15 +144,19 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa return; } - // Follow owner Entity owner = getOwner(); - if (owner == null) { + if (owner != null && owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { this.setDead(); return; } - // Update position to follow owner - this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + if (owner != null) { + this.setPosition(owner.posX, owner.posY + beamHeight, owner.posZ); + } // Check if sweep is done if (completedRotations >= numberOfRotations) { @@ -281,7 +289,16 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa target.velocityChanged = true; } + /** + * Set up preview mode. Owner is stored directly since world entity lookup won't work. + */ + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + private Entity getOwner() { + if (previewMode && previewOwner != null) return previewOwner; if (ownerEntityId == -1) return null; return worldObj.getEntityByID(ownerEntityId); } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java new file mode 100644 index 000000000..34156e362 --- /dev/null +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityZone.java @@ -0,0 +1,842 @@ +package kamkeel.npcs.entity; + +import cpw.mods.fml.common.network.ByteBufUtils; +import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.AxisAlignedBB; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; +import noppes.npcs.NpcDamageSource; +import noppes.npcs.entity.EntityNPCInterface; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +/** + * Shared zone entity for Trap and Hazard abilities. + * ZoneType distinguishes behavior: TRAP (proximity-triggered burst) vs HAZARD (persistent AoE). + */ +public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnData { + + // ═══════════════════════════════════════════════════════════════════ + // ENUMS + // ═══════════════════════════════════════════════════════════════════ + + public enum ZoneType { TRAP, HAZARD } + public enum ZoneShape { + CIRCLE, SQUARE; + + @Override + public String toString() { + switch (this) { + case CIRCLE: return "ability.shape.circle"; + case SQUARE: return "ability.shape.square"; + default: return name(); + } + } + } + + public enum AccentStyle { + STATIC, SWAYING, FLICKERING; + + @Override + public String toString() { + switch (this) { + case STATIC: return "ability.accentStyle.static"; + case SWAYING: return "ability.accentStyle.swaying"; + case FLICKERING: return "ability.accentStyle.flickering"; + default: return name(); + } + } + } + + public enum ParticleMotion { + RISING, DRIFTING, SPARKS; + + @Override + public String toString() { + switch (this) { + case RISING: return "ability.particleMotion.rising"; + case DRIFTING: return "ability.particleMotion.drifting"; + case SPARKS: return "ability.particleMotion.sparks"; + default: return name(); + } + } + } + + private static final double GROUND_OFFSET = 0.005; + private static final byte TRIGGER_FLASH_STATUS = 60; + + // ═══════════════════════════════════════════════════════════════════ + // COMMON PROPERTIES + // ═══════════════════════════════════════════════════════════════════ + + private ZoneType zoneType = ZoneType.TRAP; + private ZoneShape shape = ZoneShape.CIRCLE; + + private int ownerEntityId = -1; + + private float radius = 4.0f; + + private int durationTicks = 200; + private int maxTicks = 200; + + private int innerColor = 0xFF6600; + private int outerColor = 0xFF0000; + private boolean outerColorEnabled = true; + + private float zoneHeight = 2.0f; + + private float particleDensity = 1.0f; + private float particleScale = 1.0f; + private float animSpeed = 1.0f; + private float lightningDensity = 1.0f; + + // Visual layer fields + private boolean groundFill = true; + private float groundAlpha = 0.25f; + private boolean rings = true; + private int ringCount = 3; + private boolean border = true; + private float borderSpeed = 1.0f; + private boolean accents = true; + private int accentStyle = 0; + private boolean lightning = false; + private boolean particles = true; + private int particleMotion = 0; + private String particleDir = ""; + private int particleSize = 32; + private boolean particleGlow = true; + + private long deathWorldTime = -1; + private List effects = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // TRAP-SPECIFIC PROPERTIES + // ═══════════════════════════════════════════════════════════════════ + + private int armTime = 20; + private float triggerRadius = 2.0f; + private int maxTriggers = 1; + private int triggerCooldown = 20; + private float damage = 6.0f; + private float damageRadius = 0.0f; + private float knockback = 0.5f; + private boolean visible = true; + + // ═══════════════════════════════════════════════════════════════════ + // HAZARD-SPECIFIC PROPERTIES + // ═══════════════════════════════════════════════════════════════════ + + private float damagePerSecond = 1.0f; + private int damageInterval = 20; + private boolean ignoreInvulnFrames = false; + private boolean affectsCaster = false; + + // ═══════════════════════════════════════════════════════════════════ + // RUNTIME STATE + // ═══════════════════════════════════════════════════════════════════ + + private transient boolean armed = false; + private transient int triggerCount = 0; + private transient int ticksSinceLastTrigger = 0; + private transient Set triggeredEntities = new HashSet<>(); + private transient int triggerFlashTick = -1; + + private transient int ticksSinceDamage = 0; + private transient Set damagedThisTick = new HashSet<>(); + + private boolean previewMode = false; + private EntityLivingBase previewOwner = null; + + // ═══════════════════════════════════════════════════════════════════ + // CONSTRUCTORS + // ═══════════════════════════════════════════════════════════════════ + + public EntityAbilityZone(World world) { + super(world); + this.setSize(0.1f, 0.1f); + this.noClip = true; + this.isImmuneToFire = true; + this.ignoreFrustumCheck = true; + } + + private EntityAbilityZone(World world, ZoneType type, EntityLivingBase owner, + double x, double y, double z) { + this(world); + this.zoneType = type; + this.ownerEntityId = owner.getEntityId(); + // Snap to ground with tiny offset to prevent z-clipping + double groundY = Ability.findGroundLevel(world, x, y, z) + GROUND_OFFSET; + this.setPosition(x, groundY, z); + } + + public static EntityAbilityZone createTrap(World world, EntityLivingBase owner, + double x, double y, double z, + ZoneShape shape, + float triggerRadius, int armTime, int maxTriggers, + int triggerCooldown, float damage, float damageRadius, + float knockback, int durationTicks, + int innerColor, int outerColor, boolean outerColorEnabled, + float zoneHeight, + float particleDensity, float particleScale, + float animSpeed, float lightningDensity, + boolean visible, + List effects) { + EntityAbilityZone zone = new EntityAbilityZone(world, ZoneType.TRAP, owner, x, y, z); + zone.shape = shape; + zone.radius = triggerRadius; + zone.triggerRadius = triggerRadius; + zone.armTime = armTime; + zone.maxTriggers = maxTriggers; + zone.triggerCooldown = triggerCooldown; + zone.damage = damage; + zone.damageRadius = damageRadius; + zone.knockback = knockback; + zone.durationTicks = durationTicks; + zone.maxTicks = durationTicks; + zone.innerColor = innerColor; + zone.outerColor = outerColor; + zone.outerColorEnabled = outerColorEnabled; + zone.zoneHeight = zoneHeight; + zone.particleDensity = particleDensity; + zone.particleScale = particleScale; + zone.animSpeed = animSpeed; + zone.lightningDensity = lightningDensity; + zone.visible = visible; + if (effects != null) { + for (AbilityEffect e : effects) { + zone.effects.add(e.copy()); + } + } + zone.ticksSinceLastTrigger = triggerCooldown; + return zone; + } + + public static EntityAbilityZone createHazard(World world, EntityLivingBase owner, + double x, double y, double z, + ZoneShape shape, + float radius, + float damagePerSecond, int damageInterval, + boolean ignoreInvulnFrames, boolean affectsCaster, + int durationTicks, + int innerColor, int outerColor, boolean outerColorEnabled, + float zoneHeight, + float particleDensity, float particleScale, + float animSpeed, float lightningDensity, + List effects) { + EntityAbilityZone zone = new EntityAbilityZone(world, ZoneType.HAZARD, owner, x, y, z); + zone.shape = shape; + zone.radius = radius; + zone.damagePerSecond = damagePerSecond; + zone.damageInterval = damageInterval; + zone.ignoreInvulnFrames = ignoreInvulnFrames; + zone.affectsCaster = affectsCaster; + zone.durationTicks = durationTicks; + zone.maxTicks = durationTicks; + zone.innerColor = innerColor; + zone.outerColor = outerColor; + zone.outerColorEnabled = outerColorEnabled; + zone.zoneHeight = zoneHeight; + zone.particleDensity = particleDensity; + zone.particleScale = particleScale; + zone.animSpeed = animSpeed; + zone.lightningDensity = lightningDensity; + if (effects != null) { + for (AbilityEffect e : effects) { + zone.effects.add(e.copy()); + } + } + zone.ticksSinceDamage = damageInterval; + return zone; + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY LIFECYCLE + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void entityInit() {} + + @Override + public void handleHealthUpdate(byte id) { + if (id == TRIGGER_FLASH_STATUS) { + this.triggerFlashTick = this.ticksExisted; + } else { + super.handleHealthUpdate(id); + } + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + super.onUpdate(); + + if (deathWorldTime < 0 && worldObj != null) { + deathWorldTime = worldObj.getTotalWorldTime() + maxTicks; + } + + if (deathWorldTime > 0 && worldObj.getTotalWorldTime() >= deathWorldTime) { + this.setDead(); + return; + } + + if (!worldObj.isRemote && !previewMode) { + switch (zoneType) { + case TRAP: + tickTrap(); + break; + case HAZARD: + tickHazard(); + break; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // TRAP LOGIC + // ═══════════════════════════════════════════════════════════════════ + + private void tickTrap() { + if (!armed) { + if (ticksExisted >= armTime) { + armed = true; + } + return; + } + + ticksSinceLastTrigger++; + + if (maxTriggers > 0 && triggerCount >= maxTriggers) { + this.setDead(); + return; + } + + if (ticksSinceLastTrigger < triggerCooldown) { + return; + } + + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + posX - triggerRadius, posY - 0.5, posZ - triggerRadius, + posX + triggerRadius, posY + zoneHeight, posZ + triggerRadius + ); + + Entity owner = getOwner(); + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner) continue; + if (entity.isDead) continue; + if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; + + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + + boolean inRange; + if (shape == ZoneShape.SQUARE) { + inRange = Math.abs(dx) <= triggerRadius && Math.abs(dz) <= triggerRadius; + } else { + double dist = Math.sqrt(dx * dx + dz * dz); + inRange = dist <= triggerRadius; + } + + if (inRange) { + triggerTrap(entity); + return; + } + } + } + + private void triggerTrap(EntityLivingBase triggerer) { + Entity owner = getOwner(); + Set affected = new HashSet<>(); + + if (damageRadius > 0) { + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + posX - damageRadius, posY - 0.5, posZ - damageRadius, + posX + damageRadius, posY + zoneHeight, posZ + damageRadius + ); + + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, box); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner) continue; + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + if (shape == ZoneShape.SQUARE) { + if (Math.abs(dx) <= damageRadius && Math.abs(dz) <= damageRadius) { + affected.add(entity); + } + } else { + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist <= damageRadius) { + affected.add(entity); + } + } + } + } else { + affected.add(triggerer); + } + + boolean anyDamaged = false; + for (EntityLivingBase entity : affected) { + boolean hit = applyDamage(entity, owner, damage); + if (hit) { + anyDamaged = true; + } + + if (hit && knockback > 0) { + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + double len = Math.sqrt(dx * dx + dz * dz); + if (len > 0) { + entity.addVelocity((dx / len) * knockback * 0.5, 0.1, (dz / len) * knockback * 0.5); + entity.velocityChanged = true; + } + } + + if (hit) { + applyEffects(entity); + } + } + + if (anyDamaged) { + triggerCount++; + ticksSinceLastTrigger = 0; + triggeredEntities.add(triggerer.getUniqueID()); + triggerFlashTick = ticksExisted; + worldObj.setEntityState(this, TRIGGER_FLASH_STATUS); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // HAZARD LOGIC + // ═══════════════════════════════════════════════════════════════════ + + private void tickHazard() { + damagedThisTick.clear(); + ticksSinceDamage++; + + if (ticksSinceDamage < damageInterval) { + return; + } + ticksSinceDamage = 0; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + posX - radius, posY - 0.5, posZ - radius, + posX + radius, posY + zoneHeight, posZ + radius + ); + + Entity owner = getOwner(); + @SuppressWarnings("unchecked") + List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + for (EntityLivingBase entity : entities) { + if (owner != null && entity == owner && !affectsCaster) continue; + if (damagedThisTick.contains(entity.getEntityId())) continue; + if (!isInZone(entity)) continue; + + if (damagePerSecond > 0) { + if (ignoreInvulnFrames) { + entity.hurtResistantTime = 0; + } + applyDamage(entity, owner, damagePerSecond); + } + + applyEffects(entity); + damagedThisTick.add(entity.getEntityId()); + } + } + + private boolean isInZone(EntityLivingBase entity) { + double dx = entity.posX - posX; + double dz = entity.posZ - posZ; + + switch (shape) { + case CIRCLE: + return Math.sqrt(dx * dx + dz * dz) <= radius; + case SQUARE: + return Math.abs(dx) <= radius && Math.abs(dz) <= radius; + default: + return Math.sqrt(dx * dx + dz * dz) <= radius; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // DAMAGE + // ═══════════════════════════════════════════════════════════════════ + + private boolean applyDamage(EntityLivingBase target, Entity owner, float dmg) { + if (dmg <= 0) return false; + + if (owner instanceof EntityNPCInterface) { + return target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg); + } else if (owner instanceof EntityPlayer) { + return target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg); + } else if (owner instanceof EntityLivingBase) { + return target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg); + } else { + return target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg); + } + } + + private void applyEffects(EntityLivingBase entity) { + if (entity == null || effects.isEmpty()) return; + for (AbilityEffect effect : effects) { + effect.apply(entity); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // ENTITY HELPERS + // ═══════════════════════════════════════════════════════════════════ + + private Entity getOwner() { + if (previewMode && previewOwner != null) return previewOwner; + if (ownerEntityId == -1) return null; + return worldObj.getEntityByID(ownerEntityId); + } + + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + + // ═══════════════════════════════════════════════════════════════════ + // RENDERING SUPPORT + // ═══════════════════════════════════════════════════════════════════ + + @Override + @SideOnly(Side.CLIENT) + public boolean isInRangeToRenderDist(double distance) { + return distance < 16384.0D; + } + + @Override + public boolean shouldRenderInPass(int pass) { + return pass == 1; + } + + @Override + public float getBrightness(float partialTicks) { + return 1.0f; + } + + @Override + @SideOnly(Side.CLIENT) + public int getBrightnessForRender(float partialTicks) { + return 0xF000F0; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS FOR RENDERER + // ═══════════════════════════════════════════════════════════════════ + + public ZoneType getZoneType() { return zoneType; } + public ZoneShape getShape() { return shape; } + public float getRadius() { return radius; } + public int getInnerColor() { return innerColor; } + public int getOuterColor() { return outerColor; } + public boolean isOuterColorEnabled() { return outerColorEnabled; } + public float getZoneHeight() { return zoneHeight; } + public boolean isArmed() { return armed || ticksExisted >= armTime; } + public boolean isVisible() { return visible; } + public int getTriggerFlashTick() { return triggerFlashTick; } + public int getDurationTicks() { return durationTicks; } + public int getMaxTicks() { return maxTicks; } + public float getParticleDensity() { return particleDensity; } + public float getParticleScale() { return particleScale; } + public float getAnimSpeed() { return animSpeed; } + public float getLightningDensity() { return lightningDensity; } + + public boolean isGroundFill() { return groundFill; } + public float getGroundAlpha() { return groundAlpha; } + public boolean isRings() { return rings; } + public int getRingCount() { return ringCount; } + public boolean isBorder() { return border; } + public float getBorderSpeed() { return borderSpeed; } + public boolean isAccents() { return accents; } + public int getAccentStyle() { return accentStyle; } + public boolean isLightning() { return lightning; } + public boolean isParticles() { return particles; } + public int getParticleMotion() { return particleMotion; } + public String getParticleDir() { return particleDir; } + public int getParticleSize() { return particleSize; } + public boolean isParticleGlow() { return particleGlow; } + + public void applyVisual(boolean groundFill, float groundAlpha, + boolean rings, int ringCount, + boolean border, float borderSpeed, + boolean accents, int accentStyle, + boolean lightning, + boolean particles, int particleMotion, + String particleDir, int particleSize, boolean particleGlow) { + this.groundFill = groundFill; + this.groundAlpha = groundAlpha; + this.rings = rings; + this.ringCount = ringCount; + this.border = border; + this.borderSpeed = borderSpeed; + this.accents = accents; + this.accentStyle = accentStyle; + this.lightning = lightning; + this.particles = particles; + this.particleMotion = particleMotion; + this.particleDir = particleDir != null ? particleDir : ""; + this.particleSize = particleSize; + this.particleGlow = particleGlow; + } + + // ═══════════════════════════════════════════════════════════════════ + // NBT SERIALIZATION + // ═══════════════════════════════════════════════════════════════════ + + @Override + protected void readEntityFromNBT(NBTTagCompound nbt) { + this.zoneType = ZoneType.values()[nbt.getInteger("ZoneType")]; + try { + this.shape = ZoneShape.valueOf(nbt.getString("ShapeName")); + } catch (Exception e) { + this.shape = ZoneShape.CIRCLE; + } + + this.ownerEntityId = nbt.getInteger("OwnerId"); + this.radius = nbt.getFloat("Radius"); + this.durationTicks = nbt.getInteger("Duration"); + this.maxTicks = nbt.getInteger("MaxTicks"); + this.innerColor = nbt.getInteger("InnerColor"); + this.outerColor = nbt.getInteger("OuterColor"); + this.outerColorEnabled = nbt.getBoolean("OuterColorEnabled"); + this.zoneHeight = nbt.getFloat("ZoneHeight"); + this.particleDensity = nbt.getFloat("ParticleDensity"); + this.particleScale = nbt.getFloat("ParticleScale"); + this.animSpeed = nbt.getFloat("AnimSpeed"); + this.lightningDensity = nbt.getFloat("LightningDensity"); + this.deathWorldTime = nbt.getLong("DeathWorldTime"); + + // Visual layer fields + this.groundFill = nbt.getBoolean("GroundFill"); + this.groundAlpha = nbt.getFloat("GroundAlpha"); + this.rings = nbt.getBoolean("Rings"); + this.ringCount = nbt.getInteger("RingCount"); + this.border = nbt.getBoolean("Border"); + this.borderSpeed = nbt.getFloat("BorderSpeed"); + this.accents = nbt.getBoolean("Accents"); + this.accentStyle = nbt.getInteger("AccentStyle"); + this.lightning = nbt.getBoolean("Lightning"); + this.particles = nbt.getBoolean("Particles"); + this.particleMotion = nbt.getInteger("ParticleMotion"); + this.particleDir = nbt.getString("ParticleDir"); + this.particleSize = nbt.getInteger("ParticleSize"); + this.particleGlow = nbt.getBoolean("ParticleGlow"); + + // Trap + this.armTime = nbt.getInteger("ArmTime"); + this.triggerRadius = nbt.getFloat("TriggerRadius"); + this.maxTriggers = nbt.getInteger("MaxTriggers"); + this.triggerCooldown = nbt.getInteger("TriggerCooldown"); + this.damage = nbt.getFloat("Damage"); + this.damageRadius = nbt.getFloat("DamageRadius"); + this.knockback = nbt.getFloat("Knockback"); + this.visible = nbt.getBoolean("Visible"); + + // Hazard + this.damagePerSecond = nbt.getFloat("DamagePerSecond"); + this.damageInterval = nbt.getInteger("DamageInterval"); + this.ignoreInvulnFrames = nbt.getBoolean("IgnoreInvuln"); + this.affectsCaster = nbt.getBoolean("AffectsCaster"); + + // Effects + effects.clear(); + if (nbt.hasKey("Effects")) { + NBTTagList effectList = nbt.getTagList("Effects", 10); + for (int i = 0; i < effectList.tagCount(); i++) { + AbilityEffect effect = AbilityEffect.fromNBT(effectList.getCompoundTagAt(i)); + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + } + } + + @Override + protected void writeEntityToNBT(NBTTagCompound nbt) { + nbt.setInteger("ZoneType", zoneType.ordinal()); + nbt.setString("ShapeName", shape.name()); + nbt.setInteger("OwnerId", ownerEntityId); + nbt.setFloat("Radius", radius); + nbt.setInteger("Duration", durationTicks); + nbt.setInteger("MaxTicks", maxTicks); + nbt.setInteger("InnerColor", innerColor); + nbt.setInteger("OuterColor", outerColor); + nbt.setBoolean("OuterColorEnabled", outerColorEnabled); + nbt.setFloat("ZoneHeight", zoneHeight); + nbt.setFloat("ParticleDensity", particleDensity); + nbt.setFloat("ParticleScale", particleScale); + nbt.setFloat("AnimSpeed", animSpeed); + nbt.setFloat("LightningDensity", lightningDensity); + nbt.setLong("DeathWorldTime", deathWorldTime); + + // Visual layer fields + nbt.setBoolean("GroundFill", groundFill); + nbt.setFloat("GroundAlpha", groundAlpha); + nbt.setBoolean("Rings", rings); + nbt.setInteger("RingCount", ringCount); + nbt.setBoolean("Border", border); + nbt.setFloat("BorderSpeed", borderSpeed); + nbt.setBoolean("Accents", accents); + nbt.setInteger("AccentStyle", accentStyle); + nbt.setBoolean("Lightning", lightning); + nbt.setBoolean("Particles", particles); + nbt.setInteger("ParticleMotion", particleMotion); + nbt.setString("ParticleDir", particleDir); + nbt.setInteger("ParticleSize", particleSize); + nbt.setBoolean("ParticleGlow", particleGlow); + + // Trap + nbt.setInteger("ArmTime", armTime); + nbt.setFloat("TriggerRadius", triggerRadius); + nbt.setInteger("MaxTriggers", maxTriggers); + nbt.setInteger("TriggerCooldown", triggerCooldown); + nbt.setFloat("Damage", damage); + nbt.setFloat("DamageRadius", damageRadius); + nbt.setFloat("Knockback", knockback); + nbt.setBoolean("Visible", visible); + + // Hazard + nbt.setFloat("DamagePerSecond", damagePerSecond); + nbt.setInteger("DamageInterval", damageInterval); + nbt.setBoolean("IgnoreInvuln", ignoreInvulnFrames); + nbt.setBoolean("AffectsCaster", affectsCaster); + + // Effects + NBTTagList effectList = new NBTTagList(); + for (AbilityEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + nbt.setTag("Effects", effectList); + } + + // ═══════════════════════════════════════════════════════════════════ + // SPAWN DATA (ByteBuf for client sync) + // ═══════════════════════════════════════════════════════════════════ + + @Override + public void writeSpawnData(ByteBuf buffer) { + buffer.writeInt(zoneType.ordinal()); + ByteBufUtils.writeUTF8String(buffer, shape.name()); + buffer.writeInt(ownerEntityId); + buffer.writeFloat(radius); + buffer.writeInt(durationTicks); + buffer.writeInt(maxTicks); + buffer.writeInt(innerColor); + buffer.writeInt(outerColor); + buffer.writeBoolean(outerColorEnabled); + buffer.writeFloat(zoneHeight); + buffer.writeFloat(particleDensity); + buffer.writeFloat(particleScale); + buffer.writeFloat(animSpeed); + buffer.writeFloat(lightningDensity); + + // Visual layer fields + buffer.writeBoolean(groundFill); + buffer.writeFloat(groundAlpha); + buffer.writeBoolean(rings); + buffer.writeInt(ringCount); + buffer.writeBoolean(border); + buffer.writeFloat(borderSpeed); + buffer.writeBoolean(accents); + buffer.writeInt(accentStyle); + buffer.writeBoolean(lightning); + buffer.writeBoolean(particles); + buffer.writeInt(particleMotion); + ByteBufUtils.writeUTF8String(buffer, particleDir); + buffer.writeInt(particleSize); + buffer.writeBoolean(particleGlow); + + // Trap-specific + buffer.writeInt(armTime); + buffer.writeBoolean(visible); + + // Effects + NBTTagCompound effectsNbt = new NBTTagCompound(); + NBTTagList effectList = new NBTTagList(); + for (AbilityEffect effect : effects) { + effectList.appendTag(effect.writeNBT()); + } + effectsNbt.setTag("Effects", effectList); + ByteBufUtils.writeTag(buffer, effectsNbt); + } + + @Override + public void readSpawnData(ByteBuf buffer) { + this.zoneType = ZoneType.values()[buffer.readInt()]; + String shapeName = ByteBufUtils.readUTF8String(buffer); + try { + this.shape = ZoneShape.valueOf(shapeName); + } catch (Exception e) { + this.shape = ZoneShape.CIRCLE; + } + this.ownerEntityId = buffer.readInt(); + this.radius = buffer.readFloat(); + this.durationTicks = buffer.readInt(); + this.maxTicks = buffer.readInt(); + this.innerColor = buffer.readInt(); + this.outerColor = buffer.readInt(); + this.outerColorEnabled = buffer.readBoolean(); + this.zoneHeight = buffer.readFloat(); + this.particleDensity = buffer.readFloat(); + this.particleScale = buffer.readFloat(); + this.animSpeed = buffer.readFloat(); + this.lightningDensity = buffer.readFloat(); + + // Visual layer fields + this.groundFill = buffer.readBoolean(); + this.groundAlpha = buffer.readFloat(); + this.rings = buffer.readBoolean(); + this.ringCount = buffer.readInt(); + this.border = buffer.readBoolean(); + this.borderSpeed = buffer.readFloat(); + this.accents = buffer.readBoolean(); + this.accentStyle = buffer.readInt(); + this.lightning = buffer.readBoolean(); + this.particles = buffer.readBoolean(); + this.particleMotion = buffer.readInt(); + this.particleDir = ByteBufUtils.readUTF8String(buffer); + this.particleSize = buffer.readInt(); + this.particleGlow = buffer.readBoolean(); + + this.armTime = buffer.readInt(); + this.visible = buffer.readBoolean(); + + // Effects + NBTTagCompound effectsNbt = ByteBufUtils.readTag(buffer); + effects.clear(); + if (effectsNbt != null && effectsNbt.hasKey("Effects")) { + NBTTagList effectList = effectsNbt.getTagList("Effects", 10); + for (int i = 0; i < effectList.tagCount(); i++) { + AbilityEffect effect = AbilityEffect.fromNBT(effectList.getCompoundTagAt(i)); + if (effect != null && effect.isValid()) { + effects.add(effect); + } + } + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index bcfd18abd..dee4a3a94 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -26,6 +26,7 @@ import kamkeel.npcs.network.packets.data.SoundManagementPacket; import kamkeel.npcs.network.packets.data.SwingPlayerArmPacket; import kamkeel.npcs.network.packets.data.UpdateAnimationsPacket; import kamkeel.npcs.network.packets.data.VillagerListPacket; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; @@ -96,6 +97,7 @@ import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; +import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket; import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket; @@ -516,6 +518,7 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new CustomAbilityGetPacket()); REQUEST_PACKET.registerPacket(new CustomAbilityRemovePacket()); REQUEST_PACKET.registerPacket(new CustomAbilitySavePacket()); + REQUEST_PACKET.registerPacket(new BuiltInAbilityGetPacket()); // Other Packets REQUEST_PACKET.registerPacket(new IsGuiOpenInform()); @@ -586,6 +589,7 @@ public class PacketHandler { DATA_PACKET.registerPacket(new TelegraphSpawnPacket()); DATA_PACKET.registerPacket(new TelegraphRemovePacket()); DATA_PACKET.registerPacket(new PlayerAbilitySyncPacket()); + DATA_PACKET.registerPacket(new PlayerAbilityStatePacket()); } public void registerPlayerPackets() { diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java index 18321d0a4..8362cb3c5 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumDataPacket.java @@ -63,6 +63,7 @@ public enum EnumDataPacket { TELEGRAPH_SPAWN, TELEGRAPH_REMOVE, PLAYER_ABILITY_SYNC, + PLAYER_ABILITY_STATE, // Auction System AUCTION_DATA, diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java index 2f3e6ea94..25ba2bba6 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java @@ -205,6 +205,7 @@ public enum EnumRequestPacket { CustomAbilityGet, CustomAbilityRemove, CustomAbilitySave, + BuiltInAbilityGet, Hammer, RecipeScript, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java new file mode 100644 index 000000000..03c0b82b4 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/data/ability/PlayerAbilityStatePacket.java @@ -0,0 +1,84 @@ +package kamkeel.npcs.network.packets.data.ability; + +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.PacketHandler; +import kamkeel.npcs.network.enums.EnumDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.client.ClientAbilityState; + +import java.io.IOException; + +/** + * Lightweight packet syncing ability lock state from server to client. + * Sent every tick during ability execution when flags change, and once when ability ends. + * + * Flags byte layout: + * bit 0: movement locked (suppress WASD, zero motion) + * bit 1: rotation locked (freeze yaw/pitch) + * bit 2: has ability movement (ability controls motion — suppress WASD but don't zero) + * bit 3: position locked (freeze position) + */ +public final class PlayerAbilityStatePacket extends AbstractPacket { + public static final String packetName = "Data|PlayerAbilityState"; + + public static final byte FLAG_MOVEMENT_LOCKED = 1; + public static final byte FLAG_ROTATION_LOCKED = 2; + public static final byte FLAG_HAS_ABILITY_MOVEMENT = 4; + public static final byte FLAG_POSITION_LOCKED = 8; + + private byte flags; + private float lockedYaw; + private float lockedPitch; + + public PlayerAbilityStatePacket() { + } + + public PlayerAbilityStatePacket(byte flags, float lockedYaw, float lockedPitch) { + this.flags = flags; + this.lockedYaw = lockedYaw; + this.lockedPitch = lockedPitch; + } + + @Override + public Enum getType() { + return EnumDataPacket.PLAYER_ABILITY_STATE; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.DATA_PACKET; + } + + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(flags); + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + out.writeFloat(lockedYaw); + out.writeFloat(lockedPitch); + } + } + + @SideOnly(Side.CLIENT) + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + byte flags = in.readByte(); + float yaw = 0, pitch = 0; + if ((flags & FLAG_ROTATION_LOCKED) != 0) { + yaw = in.readFloat(); + pitch = in.readFloat(); + } + ClientAbilityState.update(flags, yaw, pitch); + } + + /** + * Send the current ability state to the player's client. + */ + public static void sendToPlayer(EntityPlayerMP player, byte flags, float lockedYaw, float lockedPitch) { + PacketHandler.Instance.sendToPlayer(new PlayerAbilityStatePacket(flags, lockedYaw, lockedPitch), player); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java index 48ac3391b..a58b896f4 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -59,6 +59,16 @@ public final class SpecialKeyStatePacket extends AbstractPacket { // Trigger ability activation on key press (rising edge) if (keyDown && !wasDown) { + // Don't activate if player has a GUI open (not the default inventory) + if (player.openContainer != null && !(player.openContainer instanceof net.minecraft.inventory.ContainerPlayer)) { + return; + } + + // Don't activate if player is riding an entity (mount) + if (player.ridingEntity != null) { + return; + } + data.abilityData.activateAbility(player); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java new file mode 100644 index 000000000..6e565f3de --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/BuiltInAbilityGetPacket.java @@ -0,0 +1,70 @@ +package kamkeel.npcs.network.packets.request.ability; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +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; +import net.minecraft.nbt.NBTTagCompound; + +import java.io.IOException; + +/** + * Request packet to get a specific built-in ability by name. + * Built-in abilities are registered presets with fixed configurations. + */ +public final class BuiltInAbilityGetPacket extends AbstractPacket { + public static String packetName = "Request|BuiltInAbilityGet"; + + private String abilityName; + + public BuiltInAbilityGetPacket() { + } + + public BuiltInAbilityGetPacket(String abilityName) { + this.abilityName = abilityName; + } + + @Override + public Enum getType() { + return EnumRequestPacket.BuiltInAbilityGet; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, abilityName); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + + if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player)) + return; + + String name = ByteBufUtils.readString(in); + Ability ability = AbilityController.Instance.getAbilityByDisplayName(name); + if (ability != null) { + NBTTagCompound compound = ability.writeNBT(); + compound.setBoolean("BuiltIn", true); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java index 8febd9fc0..6097c7483 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/ability/CustomAbilitiesGetPacket.java @@ -47,5 +47,6 @@ public final class CustomAbilitiesGetPacket extends AbstractPacket { return; NoppesUtilServer.sendCustomAbilitiesData((EntityPlayerMP) player); + NoppesUtilServer.sendBuiltInAbilitiesData((EntityPlayerMP) player); } } diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index 3ec5560ba..3c9b10f1d 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -2,6 +2,7 @@ package kamkeel.npcs.util; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.EnergyAnchorData; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.Vec3; import noppes.npcs.constants.EnumAnimationPart; @@ -18,6 +19,12 @@ import noppes.npcs.entity.data.ModelScalePart; */ public class AnchorPointHelper { + // Y offset correction for the local client player. + // EntityPlayerSP.posY is at feet, but the renderer adds yOffset (1.62) visually, + // so anchor positions computed from posY appear ~1.6 blocks too high for the local player. + // Remote players and NPCs don't have this discrepancy. + private static final float CLIENT_PLAYER_Y_OFFSET = -1.6F; + // Default biped model constants (in model units, 1 unit = 1/16 block) private static final float MODEL_SCALE = 1f / 16f; @@ -37,6 +44,7 @@ public class AnchorPointHelper { private static final float ARM_HEIGHT = 0.75f; private static final float ABOVE_HEAD_HEIGHT = 1.2f; private static final float CHEST_HEIGHT = 0.65f; + private static final float EYE_HEIGHT = 0.85f; // Distance in front for FRONT anchor private static final float DEFAULT_FRONT_DISTANCE = 1.0f; @@ -67,7 +75,7 @@ public class AnchorPointHelper { float anchorZ = anchorData.anchorOffsetZ; double x = entity.posX; - double y = entity.posY; + double y = entity.posY + getClientPlayerYCorrection(entity); double z = entity.posZ; float headYaw = (float) Math.toRadians(entity.rotationYawHead); @@ -98,11 +106,32 @@ public class AnchorPointHelper { case CHEST: y += height * CHEST_HEIGHT; break; + + case EYE: + y += entity.getEyeHeight(); + break; } - x += anchorX * scale; - y += anchorY * scale; - z += anchorZ * scale; + // Rotate offsets relative to entity's body yaw + // +X = entity's right, +Y = up, +Z = entity's forward + Vec3 rotatedOffset = rotateOffsetByYaw(anchorX * scale, anchorY * scale, anchorZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; + + // Apply FULL_MODEL rotation if active + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + Vec3 rotated = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotated.xCoord, + entity.posY + rotated.yCoord, + entity.posZ + rotated.zCoord + ); + } return Vec3.createVectorHelper(x, y, z); } @@ -119,6 +148,18 @@ public class AnchorPointHelper { return 1f; } + /** + * Returns Y offset correction for the local client player. + * On the client, EntityPlayerSP.posY is at feet level but the renderer adds yOffset (1.62), + * causing anchor positions to appear ~1.6 blocks too high. This matches DBC's correction. + */ + private static double getClientPlayerYCorrection(EntityLivingBase entity) { + if (entity.worldObj.isRemote && entity instanceof EntityPlayerSP) { + return CLIENT_PLAYER_Y_OFFSET; + } + return 0.0; + } + // Default arm scale (no scaling) private static final ModelScalePart DEFAULT_ARM_SCALE = new ModelScalePart(); @@ -135,16 +176,32 @@ public class AnchorPointHelper { /** * Calculate hand position using animation data if available. + * Applies FULL_MODEL rotation if an active animation has it. */ private static Vec3 calculateHandPosition(EntityLivingBase entity, EnergyAnchorData anchor, boolean rightHand, float scale) { // Try to get animated position first - Vec3 animatedPos = getAnimatedHandPosition(entity, anchor, rightHand, scale); - if (animatedPos != null) { - return animatedPos; + Vec3 pos = getAnimatedHandPosition(entity, anchor, rightHand, scale); + if (pos == null) { + // Fallback to static position + pos = calculateFallbackHandPosition(entity, anchor, rightHand, scale); } - // Fallback to static position - return calculateFallbackHandPosition(entity, anchor, rightHand, scale); + // Apply FULL_MODEL rotation if active + FramePart fullModel = getFullModelPart(entity); + if (fullModel != null) { + double dx = pos.xCoord - entity.posX; + double dy = pos.yCoord - entity.posY; + double dz = pos.zCoord - entity.posZ; + float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); + Vec3 rotated = applyFullModelToWorldOffset(fullModel, entity, dx, dy, dz, bodyYaw, scale); + return Vec3.createVectorHelper( + entity.posX + rotated.xCoord, + entity.posY + rotated.yCoord, + entity.posZ + rotated.zCoord + ); + } + + return pos; } /** @@ -243,12 +300,14 @@ public class AnchorPointHelper { // Final world position double worldX = entity.posX + worldOffsetX; - double worldY = entity.posY + shoulderHeight - blockY; + double worldY = entity.posY + getClientPlayerYCorrection(entity) + shoulderHeight - blockY; double worldZ = entity.posZ + worldOffsetZ; - worldX += anchor.anchorOffsetX * scale; - worldY += anchor.anchorOffsetY * scale; - worldZ += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + worldX += rotatedOffset.xCoord; + worldY += rotatedOffset.yCoord; + worldZ += rotatedOffset.zCoord; return Vec3.createVectorHelper(worldX, worldY, worldZ); } @@ -314,12 +373,14 @@ public class AnchorPointHelper { double armLengthOffset = armScale.scaleY * 0.3 * scale; double x = entity.posX + lateralX + forwardX; - double y = entity.posY + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; + double y = entity.posY + getClientPlayerYCorrection(entity) + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; double z = entity.posZ + lateralZ + forwardZ; - x += anchor.anchorOffsetX * scale; - y += anchor.anchorOffsetY * scale; - z += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; return Vec3.createVectorHelper(x, y, z); } @@ -340,8 +401,119 @@ public class AnchorPointHelper { return ABOVE_HEAD_HEIGHT; case CHEST: return CHEST_HEIGHT; + case EYE: + return EYE_HEIGHT; default: return FRONT_HEIGHT; } } + + /** + * Rotate an offset vector by the entity's body yaw so offsets are entity-relative. + * +X = entity's right, +Y = up, +Z = entity's forward. + * @param bodyYawRad body yaw in radians + */ + private static Vec3 rotateOffsetByYaw(double offsetX, double offsetY, double offsetZ, float bodyYawRad) { + double cos = Math.cos(bodyYawRad); + double sin = Math.sin(bodyYawRad); + double worldX = -offsetX * cos - offsetZ * sin; + double worldZ = -offsetX * sin + offsetZ * cos; + return Vec3.createVectorHelper(worldX, offsetY, worldZ); + } + + // ==================== FULL_MODEL ANIMATION SUPPORT ==================== + + /** + * Get the FULL_MODEL FramePart if the entity has an active animation with it. + * Returns null if no FULL_MODEL animation is active. + */ + private static FramePart getFullModelPart(EntityLivingBase entity) { + AnimationData animData = AnimationData.getData(entity); + if (animData == null || !animData.isActive() || animData.animation == null) { + return null; + } + Frame frame = (Frame) animData.animation.currentFrame(); + if (frame == null) { + return null; + } + FramePart part = frame.frameParts.get(EnumAnimationPart.FULL_MODEL); + return part; + } + + /** + * Apply FULL_MODEL rotation to a world-space offset from entity position. + * Converts the offset to model space, applies FULL_MODEL rotation and pivots, + * then converts back to world space. + * + * The rendering pipeline is: entity_pos * body_yaw * scale(-1,-1,1) * FULL_MODEL * parts + * Combined body_yaw + scale maps model space to world space: + * worldX = mx*cos(yaw) + mz*sin(yaw) + * worldY = -my (model Y-down → world Y-up) + * worldZ = mx*sin(yaw) - mz*cos(yaw) + * This transform is its own inverse for X,Z. + * + * FULL_MODEL rotation order matches renderer: vertex sees Z, then Y, then X. + */ + private static Vec3 applyFullModelToWorldOffset(FramePart fullModel, EntityLivingBase entity, + double worldDX, double worldDY, double worldDZ, + float bodyYaw, float scale) { + float[] rotations = getRotations(fullModel, entity); + float[] pivots = getPivots(fullModel, entity); + + // Quick exit if no transform needed + boolean hasRotation = rotations[0] != 0 || rotations[1] != 0 || rotations[2] != 0; + boolean hasPivot = pivots[0] != 0 || pivots[1] != 0 || pivots[2] != 0; + if (!hasRotation && !hasPivot) { + return Vec3.createVectorHelper(worldDX, worldDY, worldDZ); + } + + // Convert world offset to model space + // Body yaw + scale combined transform is an involution (self-inverse) for X,Z + double cosYaw = Math.cos(bodyYaw); + double sinYaw = Math.sin(bodyYaw); + + double mx = worldDX * cosYaw + worldDZ * sinYaw; + double mz = worldDX * sinYaw - worldDZ * cosYaw; + double my = -worldDY; // Invert Y (world Y-up → model Y-down) + + // Apply FULL_MODEL rotations (vertex order: Z first, then Y, then X) + // Matches renderer: glRotatef(X), glRotatef(Y), glRotatef(Z) → vertex sees Z,Y,X + + // Z rotation + double cosZ = Math.cos(rotations[2]); + double sinZ = Math.sin(rotations[2]); + double nx = mx * cosZ - my * sinZ; + double ny = mx * sinZ + my * cosZ; + mx = nx; + my = ny; + + // Y rotation + double cosY = Math.cos(rotations[1]); + double sinY = Math.sin(rotations[1]); + nx = mx * cosY + mz * sinY; + double nz = -mx * sinY + mz * cosY; + mx = nx; + mz = nz; + + // X rotation + double cosX = Math.cos(rotations[0]); + double sinX = Math.sin(rotations[0]); + ny = my * cosX - mz * sinX; + nz = my * sinX + mz * cosX; + my = ny; + mz = nz; + + // Apply pivots in model space (after rotation, matching GL vertex ordering) + // Renderer: glTranslatef(px, -py, pz) → pivot Y is negated for model Y-down space + mx += pivots[0] * MODEL_SCALE * scale; + my -= pivots[1] * MODEL_SCALE * scale; + mz += pivots[2] * MODEL_SCALE * scale; + + // Convert back to world space (same involution for X,Z; invert Y back) + double newDX = mx * cosYaw + mz * sinYaw; + double newDZ = mx * sinYaw - mz * cosYaw; + double newDY = -my; + + return Vec3.createVectorHelper(newDX, newDY, newDZ); + } } diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java index 69dbd1991..e1cbfaf79 100644 --- a/src/main/java/kamkeel/npcs/util/Register.java +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -11,7 +11,8 @@ import java.util.function.Supplier; public class Register { public static final Map> REGISTERED_NAMESPACES = new LinkedHashMap<>(); - private final String registryKey; + public static final Map NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>(); + protected final String registryKey; protected final String namespace; protected final Map> entries = new LinkedHashMap<>(); @@ -28,50 +29,51 @@ public class Register { public static boolean isEmpty(String registryKey) { if (REGISTERED_NAMESPACES.isEmpty()) return true; - if (REGISTERED_NAMESPACES.get(registryKey).isEmpty()) return true; + List list = REGISTERED_NAMESPACES.get(registryKey); + if (list == null || list.isEmpty()) return true; return false; } - public List catalogue() { - List list = new ArrayList<>(); - for (String regKey : REGISTERED_NAMESPACES.keySet()) { - List nameSp = REGISTERED_NAMESPACES.get(regKey); - for (String name : nameSp) { - List nameSpContent = catalogue(regKey, name); - list.addAll(nameSpContent); - } - } - - return list; - } - - public List catalogue(String namespace) { - return catalogue(registryKey, namespace); - } - - public List catalogue(String registryKey, String namespace) { - List list = new ArrayList<>(); - for (Map.Entry> entry : entries.entrySet()) { - if (entry.getKey().startsWith(registryKey + "." + namespace + ":")) - list.add(entry.getValue().get()); - } - - return list; - } - public static class Abilities extends Register { + protected final Map uniqueNames = new LinkedHashMap<>(); + protected final Set typeOnly = new HashSet<>(); + private Abilities(String namespace) { super("ability", namespace); } + @Override + public Ability register(String factoryName, Supplier factory) { + String name = registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(name, factory); + uniqueNames.put(name, factoryName); + return factory.get(); + } + + /** + * Register a type only (shell template, no built-in preset). + * The type will appear in the ability type picker but won't be + * available as a pre-configured ability by name. + */ + public Ability registerType(String factoryName, Supplier factory) { + String name = registryKey + "." + namespace + "." + factoryName.trim().toLowerCase().replaceAll(" ", "_"); + entries.put(name, factory); + uniqueNames.put(name, factoryName); + typeOnly.add(name); + return factory.get(); + } + public void register() { for (Map.Entry> entry : entries.entrySet()) { - AbilityController.Instance.registerType(entry.getValue().get().getTypeId(), entry.getValue()); + AbilityController.Instance.registerType(entry.getKey(), entry.getValue()); + if (!typeOnly.contains(entry.getKey())) { + AbilityController.Instance.registerAbility(uniqueNames.get(entry.getKey()), entry.getValue().get()); + } } } - public static Register.Abilities create(String namespace) { + public static Register.Abilities create(String namespace, String displayName) { if (!REGISTERED_NAMESPACES.containsKey("ability")) REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); @@ -80,6 +82,7 @@ public class Register { } REGISTERED_NAMESPACES.get("ability").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); return new Register.Abilities(namespace); } @@ -100,6 +103,16 @@ public class Register { return super.register(factoryName, factory); } + public Animation[] registerBundle(String factoryName, Supplier factory, String... appendixes) { + List animations = new ArrayList<>(); + for (String appendix : appendixes) { + entries.put(registryKey + "." + namespace + "." + factoryName + "_" + appendix, factory); + animations.add(factory.get()); + } + + return animations.toArray(new Animation[0]); + } + public void register() { try { String path = "/assets/" + namespace + "/" + animationsPath; diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index 0bc081429..caf86c7b5 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -91,6 +91,7 @@ import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; import noppes.npcs.entity.old.EntityNPCDwarfFemale; import noppes.npcs.entity.old.EntityNPCDwarfMale; import noppes.npcs.entity.old.EntityNPCElfFemale; @@ -117,7 +118,7 @@ import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; -@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta1") +@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11-beta3") public class CustomNpcs { @SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy") @@ -292,6 +293,7 @@ public class CustomNpcs { registerNewEntity(EntityAbilityLaser.class, "abilitylaser", 64, 3, true); registerNewEntity(EntityAbilityBeam.class, "abilitybeam", 64, 3, true); registerNewEntity(EntityAbilitySweeper.class, "abilitysweeper", 64, 3, true); + registerNewEntity(EntityAbilityZone.class, "abilityzone", 64, 3, true); new RecipeController(); diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 3f8cb5357..78692162f 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -44,7 +44,7 @@ public class DataAbilities { /** * Whether the ability system is enabled for this NPC */ - public boolean enabled = false; + public boolean enabled = true; /** * Minimum cooldown ticks between abilities (global minimum) @@ -90,6 +90,24 @@ public class DataAbilities { private transient float lockedRenderYawOffset = 0; private transient float lockedPitch = 0; + /** + * Locked position values for movement lock. + * Stored when entering a locked phase, applied after super.onLivingUpdate() + * to override any position changes from AI/physics. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + + /** + * Hit scan state - forces NPC to face target. + * Set during tickCurrentAbility(), applied after super.onLivingUpdate() + * to override AI look helper rotation. + */ + private transient boolean hitScanActive = false; + private transient EntityLivingBase hitScanTarget = null; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -107,10 +125,33 @@ public class DataAbilities { * Should be called every tick from onLivingUpdate(). */ public void tick() { - if (!enabled || npc.worldObj.isRemote || npc.isKilled()) { + if (npc.worldObj.isRemote) { return; } + // Force-stop any running ability when NPC is killed or abilities are disabled + if (!enabled || npc.isKilled()) { + if (currentAbility != null) { + removeTelegraph(currentAbility); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + currentAbility = null; + lastTarget = null; + } else { + // No ability but locks could be orphaned + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + return; + } + + // Safety: release orphaned locks if no ability is actively executing + if (currentAbility == null || !currentAbility.isExecuting()) { + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + // Tick current ability if executing if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(); @@ -130,39 +171,75 @@ public class DataAbilities { // Fire tick event for scripts fireTickEvent(currentAbility, target); + // Fire extender tick hook (e.g., per-tick resource drain) + if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, npc, target, + currentAbility.getPhase(), currentAbility.getCurrentTick())) { + interruptCurrentAbility(null, 0); + return; + } + // Handle phase-specific logic switch (currentAbility.getPhase()) { case WINDUP: - currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up telegraph, sound, animation, locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(currentAbility, target); + playAbilitySound(currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } + currentAbility.onWindUpTick(npc, target, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { - // Just entered ACTIVE phase - lock telegraph position if it was following + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { + // Just entered ACTIVE phase - lock telegraph positions if they were following // This commits the ability to its current target position - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { + for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } - // Remove telegraph - it has served its purpose - removeTelegraph(currentAbility); + // Remove telegraph unless the ability keeps it during active phase + // (e.g., sweeping attacks where the telegraph shows the ongoing danger zone) + if (!currentAbility.keepTelegraphDuringActive()) { + removeTelegraph(currentAbility); + } - // Handle rotation lock transition from WINDUP to ACTIVE + // Handle rotation control transition from WINDUP to ACTIVE if (currentAbility.isRotationLockedDuringActive()) { - // ACTIVE or WINDUP_AND_ACTIVE: capture (or keep) rotation lock if (!rotationLocked) { captureLockedRotation(); } } else if (rotationLocked) { - // WINDUP only: release the lock now that windup is over - releaseLockedRotation(); + releaseRotationControl(); + } + + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(); + } + } else if (positionLocked) { + releaseLockedPosition(); } // Play active sound and animation - playAbilitySound(currentAbility.getActiveSound()); + // Abilities that keep telegraph during active manage their own sound timing + if (!currentAbility.keepTelegraphDuringActive()) { + playAbilitySound(currentAbility.getActiveSound()); + } playAbilityAnimation(currentAbility.getActiveAnimation()); + // Snap NPC to face target before execute so startMoving() reads correct rotation + if (currentAbility.isHitScanForCurrentPhase() && target != null) { + faceTarget(target); + } + // Fire execute event (cancelable) AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( npc.wrappedNPC, currentAbility, target); @@ -172,7 +249,7 @@ public class DataAbilities { } // Call onExecute - currentAbility.onExecute(npc, target, npc.worldObj); + currentAbility.onExecute(npc, target); // Check if ability completed during onExecute (signalCompletion was called) if (currentAbility.getPhase() == AbilityPhase.IDLE) { @@ -180,13 +257,38 @@ public class DataAbilities { return; } } - currentAbility.onActiveTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); + currentAbility.onActiveTick(npc, target, currentAbility.getCurrentTick()); // Check if ability completed during onActiveTick (signalCompletion was called) if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(target); return; } + + // Auto-complete for burst overlap mode (entities fly independently) + // This allows entity-spawning abilities to immediately chain next burst + // without each type needing to check burst state in their onActiveTick() + // Wait until all staggered projectiles have been fired before auto-completing + if (currentAbility.isBurstEnabled() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + + // Check if ability entered burst delay during onActiveTick or overlap auto-complete + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + // Release all locks - free movement/rotation during delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + if (hitScanActive) releaseRotationControl(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: @@ -199,6 +301,15 @@ public class DataAbilities { break; } + // Update hit scan state - actual facing is deferred to applyRotationControl() + // which runs AFTER super.onLivingUpdate() to override AI look helper + if (currentAbility != null && currentAbility.isExecuting() + && currentAbility.isHitScanForCurrentPhase() && target != null) { + enableHitScan(target); + } else if (hitScanActive) { + releaseRotationControl(); + } + // Apply movement control if ability is still executing if (currentAbility != null && currentAbility.isExecuting()) { applyMovementControl(); @@ -235,6 +346,12 @@ public class DataAbilities { private void handleAbilityCompletion(EntityLivingBase target) { if (currentAbility == null) return; + // Remove any remaining telegraphs (for abilities that keep telegraph during active) + removeTelegraph(currentAbility); + + // Fire extender complete hook + AbilityController.Instance.fireOnAbilityComplete(currentAbility, npc, target, false); + // Call onComplete callback currentAbility.onComplete(npc, target); @@ -243,8 +360,9 @@ public class DataAbilities { npc.wrappedNPC, currentAbility, target); NpcAPI.EVENT_BUS.post(completeEvent); - // Release rotation lock before cleanup - releaseLockedRotation(); + // Release locks before cleanup + releaseRotationControl(); + releaseLockedPosition(); // Clean up and roll cooldown (this sets currentAbility to null) onAbilityComplete(); @@ -259,8 +377,9 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock - releaseLockedRotation(); + // Release locks + releaseRotationControl(); + releaseLockedPosition(); // Calculate cooldown: random(min, max) + ability offset int abilityCooldownOffset = currentAbility.getCooldownTicks(); @@ -349,6 +468,11 @@ public class DataAbilities { * Check if a specific ability is eligible for use. */ private boolean isAbilityEligible(Ability ability, EntityLivingBase target) { + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Check enabled if (!ability.isEnabled()) { return false; @@ -387,6 +511,11 @@ public class DataAbilities { return false; } + // Fire extender start hook (e.g., resource cost checks) + if (!AbilityController.Instance.fireOnAbilityStart(ability, npc, target)) { + return false; + } + currentAbility = ability; lastTarget = target; ability.start(target); @@ -399,6 +528,9 @@ public class DataAbilities { if (ability.isRotationLockedDuringWindup()) { captureLockedRotation(); } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } spawnTelegraph(ability, target); playAbilitySound(ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); @@ -416,6 +548,9 @@ public class DataAbilities { if (ability.isRotationLockedDuringActive()) { captureLockedRotation(); } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } // Play active sound and animation playAbilitySound(ability.getActiveSound()); @@ -429,7 +564,7 @@ public class DataAbilities { } // Call onExecute - ability.onExecute(npc, target, npc.worldObj); + ability.onExecute(npc, target); // Check if ability completed during onExecute if (ability.getPhase() == AbilityPhase.IDLE) { @@ -486,26 +621,27 @@ public class DataAbilities { } /** - * Spawn and send telegraph for an ability. + * Spawn and send telegraphs for an ability. */ private void spawnTelegraph(Ability ability, EntityLivingBase target) { - TelegraphInstance telegraph = ability.createTelegraph(npc, target); - if (telegraph != null) { - ability.setTelegraphInstance(telegraph); - // Send to all nearby players - TelegraphSpawnPacket.sendToTracking(telegraph, npc); + List telegraphs = ability.createTelegraphs(npc, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, npc); + } } } /** - * Remove telegraph when ability ends or is interrupted. + * Remove telegraphs when ability ends or is interrupted. */ private void removeTelegraph(Ability ability) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), npc); - ability.setTelegraphInstance(null); } + ability.setTelegraphInstances(null); } // ═══════════════════════════════════════════════════════════════════ @@ -625,8 +761,12 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock - releaseLockedRotation(); + // Release locks + releaseRotationControl(); + releaseLockedPosition(); + + // Fire extender complete hook (interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, npc, lastTarget, true); // Fire interrupt event AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( @@ -648,7 +788,8 @@ public class DataAbilities { if (currentAbility != null) { removeTelegraph(currentAbility); stopAbilityAnimation(); - releaseLockedRotation(); + releaseRotationControl(); + releaseLockedPosition(); currentAbility.interrupt(); currentAbility = null; lastTarget = null; @@ -668,6 +809,11 @@ public class DataAbilities { return false; } + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Stop any currently executing ability stopCurrentAbility(); @@ -940,15 +1086,15 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // ROTATION LOCKING + // ROTATION CONTROL // ═══════════════════════════════════════════════════════════════════ - /** Bit flag for rotation lock in the existing data watcher slot 15 bitfield */ - private static final int ROTATION_LOCKED_FLAG = 16; + /** Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 */ + private static final int ROTATION_CONTROLLED_FLAG = 16; /** * Capture current rotation values to lock NPC's look direction. - * Called when entering a locked phase (WINDUP or ACTIVE depending on LockMovementType). + * Called when entering a LOCKED rotation phase. */ private void captureLockedRotation() { lockedYaw = npc.rotationYaw; @@ -956,41 +1102,79 @@ public class DataAbilities { lockedRenderYawOffset = npc.renderYawOffset; lockedPitch = npc.rotationPitch; rotationLocked = true; - npc.setBoolFlag(true, ROTATION_LOCKED_FLAG); + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); } /** - * Release the rotation lock. - * Called when leaving the locked phase or ability completes. + * Release rotation control (both locked and hit scan). */ - private void releaseLockedRotation() { + private void releaseRotationControl() { rotationLocked = false; - npc.setBoolFlag(false, ROTATION_LOCKED_FLAG); + hitScanActive = false; + hitScanTarget = null; + npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG); } /** - * Apply locked rotation values to the NPC. - * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override - * any rotation changes made by the look helper, AI tasks, or body smoothing. - * Runs on both client and server. + * Enable hit scan tracking for the given target. */ - public void applyLockedRotation() { + private void enableHitScan(EntityLivingBase target) { + if (!hitScanActive) { + hitScanActive = true; + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); + } + hitScanTarget = target; + } + + /** + * Snap the NPC to face the target instantly. + */ + private void faceTarget(EntityLivingBase target) { + double dx = target.posX - npc.posX; + double dz = target.posZ - npc.posZ; + double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight()); + double distXZ = Math.sqrt(dx * dx + dz * dz); + + float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI); + float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI); + + npc.rotationYaw = yaw; + npc.rotationYawHead = yaw; + npc.renderYawOffset = yaw; + npc.rotationPitch = pitch; + npc.prevRotationYaw = yaw; + npc.prevRotationYawHead = yaw; + npc.prevRenderYawOffset = yaw; + npc.prevRotationPitch = pitch; + } + + /** + * Apply rotation control after super.onLivingUpdate() and super.onUpdate(). + * Handles both LOCKED (freeze at captured values) and TRACK (face target) modes. + * + * Server: computes the correct rotation (locked values or target facing). + * Client: trusts the server-synced rotation values and prevents body smoothing override. + */ + public void applyRotationControl() { if (npc.worldObj.isRemote) { - // Client-side: check bit 16 in the existing flags data watcher (slot 15) - boolean flagActive = npc.getBoolFlag(ROTATION_LOCKED_FLAG); - if (!flagActive) { + // Client: check single flag for any rotation control + if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) { rotationLocked = false; return; } - // First tick the flag is active: capture current rotation values - if (!rotationLocked) { - lockedYaw = npc.rotationYaw; - lockedYawHead = npc.rotationYawHead; - lockedRenderYawOffset = npc.renderYawOffset; - lockedPitch = npc.rotationPitch; - rotationLocked = true; - } - // Force all rotation values back to locked state + // Trust server rotation, prevent body smoothing from overriding + npc.prevRotationYaw = npc.rotationYaw; + npc.prevRotationYawHead = npc.rotationYawHead; + npc.renderYawOffset = npc.rotationYawHead; + npc.prevRenderYawOffset = npc.rotationYawHead; + npc.prevRotationPitch = npc.rotationPitch; + return; + } + + // Server: apply the appropriate rotation + if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) { + faceTarget(hitScanTarget); + } else if (rotationLocked) { npc.rotationYaw = lockedYaw; npc.rotationYawHead = lockedYawHead; npc.renderYawOffset = lockedRenderYawOffset; @@ -999,32 +1183,89 @@ public class DataAbilities { npc.prevRotationYawHead = lockedYawHead; npc.prevRenderYawOffset = lockedRenderYawOffset; npc.prevRotationPitch = lockedPitch; + } + } + + /** + * Check if rotation is currently controlled (locked or tracking target). + * Used by AI tasks to determine if they should try to change NPC look direction. + */ + public boolean isRotationLocked() { + return rotationLocked || hitScanActive; + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** Bit flag for position lock in data watcher slot 15 */ + private static final int POSITION_LOCKED_FLAG = 32; + + /** + * Capture current position to lock NPC in place. + * Called when entering a phase with movement lock. + */ + private void captureLockedPosition() { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + npc.setBoolFlag(true, POSITION_LOCKED_FLAG); + } + + /** + * Release the position lock. + * Called when leaving the locked phase or ability completes. + */ + private void releaseLockedPosition() { + positionLocked = false; + npc.setBoolFlag(false, POSITION_LOCKED_FLAG); + } + + /** + * Apply locked position values to the NPC. + * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override + * any position changes from AI pathfinding, physics, or entity collisions. + * Runs on both client and server. + */ + public void applyLockedPosition() { + if (npc.worldObj.isRemote) { + // Client-side: check flag via data watcher + boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG); + if (!flagActive) { + positionLocked = false; + return; + } + // First tick the flag is active: capture current position + if (!positionLocked) { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + } + // Snap position back and set prev to prevent interpolation jitter + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; return; } // Server-side: use stored locked values - if (!rotationLocked) { + if (!positionLocked) { return; } - // Force rotation back to locked values - npc.rotationYaw = lockedYaw; - npc.rotationYawHead = lockedYawHead; - npc.renderYawOffset = lockedRenderYawOffset; - npc.rotationPitch = lockedPitch; - - // Also set prev values to prevent interpolation jitter - npc.prevRotationYaw = lockedYaw; - npc.prevRotationYawHead = lockedYawHead; - npc.prevRenderYawOffset = lockedRenderYawOffset; - npc.prevRotationPitch = lockedPitch; - } - - /** - * Check if rotation is currently locked. - */ - public boolean isRotationLocked() { - return rotationLocked; + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/DataStats.java b/src/main/java/noppes/npcs/DataStats.java index 0d085d823..7db32bc66 100644 --- a/src/main/java/noppes/npcs/DataStats.java +++ b/src/main/java/noppes/npcs/DataStats.java @@ -20,6 +20,7 @@ public class DataStats { public EnumPotionType potionType = EnumPotionType.None; public int potionDuration = 5; //20 = 1 second public int potionAmp = 0; + public int potionManualId = 0; public double maxHealth = 20; public int respawnTime = 20; @@ -45,6 +46,7 @@ public class DataStats { public boolean pPhysics = true, pXlr8 = false, pGlows = false, pExplode = false; public boolean pRender3D = false, pSpin = false, pStick = false, pBurnItem = false; public EnumPotionType pEffect = EnumPotionType.None; + public int pManualId = 0; public EnumParticleType pTrail = EnumParticleType.None; public ScriptParticle pCustom = new ScriptParticle(""); public int pEffAmp = 0; @@ -88,6 +90,8 @@ public class DataStats { compound.setInteger("PotionEffect", potionType.ordinal()); compound.setInteger("PotionDuration", potionDuration); compound.setInteger("PotionAmp", potionAmp); + if (potionType == EnumPotionType.Manual) + compound.setInteger("PotionManualId", potionManualId); compound.setInteger("MaxFiringRange", rangedRange); compound.setInteger("FireRate", fireRate); @@ -122,6 +126,8 @@ public class DataStats { compound.setTag("pCustom", pCustom.writeToNBT()); if (pEffect == EnumPotionType.Fire) compound.setBoolean("pBurnItem", pBurnItem); + if (pEffect == EnumPotionType.Manual) + compound.setInteger("pManualId", pManualId); compound.setBoolean("ImmuneToFire", immuneToFire); compound.setBoolean("PotionImmune", potionImmune); @@ -145,7 +151,7 @@ public class DataStats { aggroRange = compound.getInteger("AggroRange"); respawnTime = compound.getInteger("RespawnTime"); spawnCycle = compound.getInteger("SpawnCycle"); - creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumPotionType.values().length]; + creatureType = EnumCreatureAttribute.values()[compound.getInteger("CreatureType") % EnumCreatureAttribute.values().length]; ignoreCobweb = compound.getBoolean("IgnoreCobweb"); healthRegen = compound.getFloat("HealthRegen"); combatRegen = compound.getFloat("CombatRegen"); @@ -155,9 +161,11 @@ public class DataStats { swingWarmUp = ValueUtil.clamp(compound.getInteger("SwingWarmup"), 0, 1000); attackRange = compound.getInteger("AttackRange"); knockback = compound.getInteger("KnockBack"); - potionType = EnumPotionType.values()[compound.getInteger("PotionEffect") % EnumPotionType.values().length]; + potionType = EnumPotionType.fromOrdinal(compound.getInteger("PotionEffect")); potionDuration = compound.getInteger("PotionDuration"); potionAmp = compound.getInteger("PotionAmp"); + if (potionType == EnumPotionType.Manual) + potionManualId = compound.getInteger("PotionManualId"); rangedRange = compound.getInteger("MaxFiringRange"); fireRate = compound.getInteger("FireRate"); @@ -180,7 +188,7 @@ public class DataStats { pRender3D = compound.getBoolean("pRender3D"); pSpin = compound.getBoolean("pSpin"); pStick = compound.getBoolean("pStick"); - pEffect = EnumPotionType.values()[compound.getInteger("pEffect") % EnumPotionType.values().length]; + pEffect = EnumPotionType.fromOrdinal(compound.getInteger("pEffect")); pTrail = EnumParticleType.values()[compound.getInteger("pTrail") % EnumParticleType.values().length]; pEffAmp = compound.getInteger("pEffAmp"); fireSound = compound.getString("FiringSound"); @@ -195,6 +203,8 @@ public class DataStats { pCustom = ScriptParticle.fromNBT(compound.getCompoundTag("pCustom")); if (pEffect == EnumPotionType.Fire) pBurnItem = compound.getBoolean("pBurnItem"); + if (pEffect == EnumPotionType.Manual) + pManualId = compound.getInteger("pManualId"); immuneToFire = compound.getBoolean("ImmuneToFire"); potionImmune = compound.getBoolean("PotionImmune"); diff --git a/src/main/java/noppes/npcs/EventHooks.java b/src/main/java/noppes/npcs/EventHooks.java index 5f9d1388f..75b615671 100644 --- a/src/main/java/noppes/npcs/EventHooks.java +++ b/src/main/java/noppes/npcs/EventHooks.java @@ -1,6 +1,7 @@ package noppes.npcs; import cpw.mods.fml.common.eventhandler.Event; +import kamkeel.npcs.entity.EntityAbilityProjectile; import kamkeel.npcs.network.packets.data.AchievementPacket; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; @@ -16,7 +17,10 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.world.WorldEvent; +import noppes.npcs.api.IBlock; +import noppes.npcs.api.IPos; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IAnimatable; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntity; @@ -52,6 +56,7 @@ import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AnimationEvent; import noppes.npcs.scripted.event.BlockEvent; import noppes.npcs.scripted.event.CustomNPCsEvent; +import noppes.npcs.scripted.event.EnergyProjectileEvent; import noppes.npcs.scripted.event.ForgeEvent; import noppes.npcs.scripted.event.ItemEvent; import noppes.npcs.scripted.event.LinkedItemEvent; @@ -448,6 +453,110 @@ public class EventHooks { NpcAPI.EVENT_BUS.post(event); } + // ==================== ENERGY PROJECTILE EVENTS ==================== + + public static void onEnergyProjectileFired(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.FiredEvent event = new EnergyProjectileEvent.FiredEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_FIRED, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + public static void onEnergyProjectileTick(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + /** + * Fires the entity impact event. Returns the (possibly modified) damage, or -1 if cancelled. + */ + public static float onEnergyProjectileEntityImpact(EntityAbilityProjectile projectile, EntityLivingBase target, float damage) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + IEntity wrappedTarget = NpcAPI.Instance().getIEntity(target); + EnergyProjectileEvent.EntityImpactEvent event = new EnergyProjectileEvent.EntityImpactEvent(wrapped, wrappedTarget, damage); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + + if (event.isCanceled()) { + return -1; + } + return event.getDamage(); + } + + public static void onEnergyProjectileBlockImpact(EntityAbilityProjectile projectile, int blockX, int blockY, int blockZ) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + IPos pos = NpcAPI.Instance().getIPos(blockX, blockY, blockZ); + IWorld world = NpcAPI.Instance().getIWorld(projectile.worldObj); + IBlock block = NpcAPI.Instance().getIBlock(world, pos); + EnergyProjectileEvent.BlockImpactEvent event = new EnergyProjectileEvent.BlockImpactEvent(wrapped, block); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + + public static void onEnergyProjectileExpired(EntityAbilityProjectile projectile) { + IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile); + EnergyProjectileEvent.ExpiredEvent event = new EnergyProjectileEvent.ExpiredEvent(wrapped); + ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + + Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId()); + if (owner instanceof EntityNPCInterface) { + ((EntityNPCInterface) owner).script.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + } else if (owner instanceof EntityPlayer) { + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) owner); + if (handler != null) { + handler.callScript(EnumScriptType.ENERGY_PROJECTILE_EXPIRED, event); + } + } + + NpcAPI.EVENT_BUS.post(event); + } + public static void onPlayerInit(PlayerDataScript handler, IPlayer player) { PlayerEvent.InitEvent event = new PlayerEvent.InitEvent(player); handler.callScript(EnumScriptType.INIT, event); @@ -693,6 +802,31 @@ public class EventHooks { return NpcAPI.EVENT_BUS.post(event); } + public static boolean onPlayerAbilityStart(PlayerDataScript handler, PlayerAbilityEvent.StartEvent event) { + handler.callScript(EnumScriptType.ABILITY_START, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static boolean onPlayerAbilityExecute(PlayerDataScript handler, PlayerAbilityEvent.ExecuteEvent event) { + handler.callScript(EnumScriptType.ABILITY_EXECUTE, event); + return NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityTick(PlayerDataScript handler, PlayerAbilityEvent.TickEvent event) { + handler.callScript(EnumScriptType.ABILITY_TICK, event); + NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityInterrupt(PlayerDataScript handler, PlayerAbilityEvent.InterruptEvent event) { + handler.callScript(EnumScriptType.ABILITY_INTERRUPT, event); + NpcAPI.EVENT_BUS.post(event); + } + + public static void onPlayerAbilityComplete(PlayerDataScript handler, PlayerAbilityEvent.CompleteEvent event) { + handler.callScript(EnumScriptType.ABILITY_COMPLETE, event); + NpcAPI.EVENT_BUS.post(event); + } + public static boolean onPlayerAbilityHit(PlayerDataScript handler, PlayerAbilityEvent.HitEvent event) { handler.callScript(EnumScriptType.ABILITY_HIT, event); return NpcAPI.EVENT_BUS.post(event); diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index 4b93ad2b5..b54b4b245 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -2,6 +2,7 @@ package noppes.npcs; import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.packets.data.ParticlePacket; @@ -780,18 +781,38 @@ public class NoppesUtilServer { if (controller != null) { int index = 0; for (String typeId : controller.getTypes()) { + // Exclude built-in types from the NPC type list + if (controller.isBuiltInType(typeId)) continue; map.put(typeId, index++); } } sendScrollData(player, map, EnumScrollData.ABILITY_TYPES); } + public static void sendBuiltInAbilitiesData(EntityPlayerMP player) { + HashMap map = new HashMap(); + AbilityController controller = AbilityController.Instance; + if (controller != null) { + int index = 0; + for (String name : controller.getAbilityNames()) { + Ability ability = controller.getAbility(name); + if (ability != null) { + map.put(ability.getName(), index++); + } + } + } + sendScrollData(player, map, EnumScrollData.BUILTIN_ABILITIES); + } + public static void sendCustomAbilitiesData(EntityPlayerMP player) { HashMap map = new HashMap(); kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance; if (controller != null) { int index = 0; for (String uuid : controller.getCustomAbilityIds()) { + Ability ability = controller.getCustomAbility(uuid); + if (ability == null || !ability.getAllowedBy().allowsNpc()) continue; + String name = controller.getCustomAbilityName(uuid); if (name == null || name.isEmpty()) name = uuid; map.put(name + "\t" + uuid, index++); diff --git a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java index 0541f64c4..c0405c193 100644 --- a/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java +++ b/src/main/java/noppes/npcs/ScriptPlayerEventHandler.java @@ -8,6 +8,8 @@ import cpw.mods.fml.relauncher.Side; import kamkeel.npcs.addon.DBCAddon; import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.util.AttributeAttackUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -100,9 +102,17 @@ public class ScriptPlayerEventHandler { playerData.abilityData.tick(player); // Lock player movement during ability phases that require it + // Skip zeroing if the ability has its own movement (Charge/Dash/Slam) if (playerData.abilityData.isMovementLocked()) { - player.motionX = 0; - player.motionZ = 0; + Ability current = playerData.abilityData.getCurrentAbility(); + if (current == null || !current.hasAbilityMovement()) { + player.motionX = 0; + if (!AbilityController.Instance.isPlayerFlying(player)) { + player.motionY = Math.min(player.motionY, 0); + } + player.motionZ = 0; + player.velocityChanged = true; + } } if (playerData.updateClient) { @@ -322,6 +332,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Cancel any executing ability on dimension change + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.interruptCurrentAbility(); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(event.player); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.player); EventHooks.onPlayerChangeDim(handler, scriptPlayer, event.fromDim, event.toDim); @@ -472,6 +488,13 @@ public class ScriptPlayerEventHandler { if (event.entityLiving.worldObj instanceof WorldServer) { if (event.entityLiving instanceof EntityPlayerMP) { + // Cancel jump if movement is locked by an ability + PlayerData playerData = PlayerData.get((EntityPlayer) event.entityLiving); + if (playerData != null && playerData.abilityData.isMovementLocked()) { + event.entityLiving.motionY = 0; + event.entityLiving.velocityChanged = true; + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.entityLiving); EventHooks.onPlayerJump(handler, scriptPlayer); @@ -526,6 +549,8 @@ public class ScriptPlayerEventHandler { EntityPlayer player = (EntityPlayer) event.entityLiving; PlayerData playerData = PlayerData.get(player); + // Cancel any executing ability on death + playerData.abilityData.interruptCurrentAbility(); if (ConfigScript.ClearActionsOnDeath) playerData.actionManager.clear(); } @@ -596,6 +621,12 @@ public class ScriptPlayerEventHandler { } if (event.entityLiving instanceof EntityPlayerMP) { + // Handle ability damage interactions (Guard counter, damage reduction) + PlayerData pData = PlayerData.get((EntityPlayer) event.entityLiving); + if (pData != null && pData.abilityData != null && pData.abilityData.isExecutingAbility()) { + event.ammount = pData.abilityData.onDamage(event.source, event.ammount); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts((EntityPlayer) event.entityLiving); noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent pevent = new noppes.npcs.scripted.event.player.PlayerEvent.DamagedEvent((IPlayer) NpcAPI.Instance().getIEntity((EntityPlayer) event.entityLiving), source, event.ammount, event.source); cancel = EventHooks.onPlayerDamaged(handler, pevent); @@ -619,6 +650,12 @@ public class ScriptPlayerEventHandler { return; if (event.player.worldObj instanceof WorldServer && event.player instanceof EntityPlayerMP) { + // Cancel any executing ability on respawn + PlayerData playerData = PlayerData.get(event.player); + if (playerData != null) { + playerData.abilityData.interruptCurrentAbility(); + } + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(event.player); IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(event.player); EventHooks.onPlayerRespawn(handler, scriptPlayer); diff --git a/src/main/java/noppes/npcs/client/ClientAbilityState.java b/src/main/java/noppes/npcs/client/ClientAbilityState.java new file mode 100644 index 000000000..8092a69a3 --- /dev/null +++ b/src/main/java/noppes/npcs/client/ClientAbilityState.java @@ -0,0 +1,59 @@ +package noppes.npcs.client; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; + +/** + * Client-side state holder for player ability lock flags. + * Updated by {@link PlayerAbilityStatePacket} from the server. + * Read by {@link ClientTickHandler} to suppress WASD input and enforce rotation. + */ +@SideOnly(Side.CLIENT) +public class ClientAbilityState { + public static boolean movementLocked = false; + public static boolean rotationLocked = false; + public static boolean hasAbilityMovement = false; + public static boolean positionLocked = false; + public static float lockedYaw = 0; + public static float lockedPitch = 0; + + /** + * Update state from a received packet. + */ + public static void update(byte flags, float yaw, float pitch) { + movementLocked = (flags & PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED) != 0; + rotationLocked = (flags & PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED) != 0; + hasAbilityMovement = (flags & PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT) != 0; + positionLocked = (flags & PlayerAbilityStatePacket.FLAG_POSITION_LOCKED) != 0; + lockedYaw = yaw; + lockedPitch = pitch; + } + + /** + * Whether player WASD movement input should be suppressed. + * True when movement/position is locked or ability has its own movement. + */ + public static boolean shouldSuppressMovementInput() { + return movementLocked || hasAbilityMovement || positionLocked; + } + + /** + * Whether player camera rotation should be locked. + */ + public static boolean shouldLockRotation() { + return rotationLocked; + } + + /** + * Reset all state. Called on world change / disconnect. + */ + public static void reset() { + movementLocked = false; + rotationLocked = false; + hasAbilityMovement = false; + positionLocked = false; + lockedYaw = 0; + lockedPitch = 0; + } +} diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index a7a0f2b39..6fc690b5a 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -84,9 +84,20 @@ public class ClientEventHandler { @SubscribeEvent public void onMouse(MouseEvent event) { - if (Minecraft.getMinecraft().currentScreen != null) + Minecraft mc = Minecraft.getMinecraft(); + if (mc.currentScreen != null) return; + // Block mouse movement during ability rotation lock. + // Allow clicks (button >= 0) and scroll (dwheel != 0) to pass through. + if (mc.theWorld != null && mc.thePlayer != null + && ClientAbilityState.shouldLockRotation() + && (event.dx != 0 || event.dy != 0) + && event.button == -1 && event.dwheel == 0) { + event.setCanceled(true); + return; + } + ArrayList removeList = new ArrayList<>(); for (Map.Entry entry : disabledButtonTimes.entrySet()) { if (entry.getValue() > 0) { diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index e3f73ae9b..d4c729e02 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -153,12 +153,14 @@ import kamkeel.npcs.client.renderer.RenderAbilityDisc; import kamkeel.npcs.client.renderer.RenderAbilityLaser; import kamkeel.npcs.client.renderer.RenderAbilityBeam; import kamkeel.npcs.client.renderer.RenderAbilitySweeper; +import kamkeel.npcs.client.renderer.RenderAbilityZone; import kamkeel.npcs.client.renderer.lightning.LightningHandler; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.entity.EntityAbilityLaser; import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilitySweeper; +import kamkeel.npcs.entity.EntityAbilityZone; import noppes.npcs.client.renderer.blocks.BlockBannerRenderer; import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer; import noppes.npcs.client.renderer.blocks.BlockBeamRenderer; @@ -272,6 +274,7 @@ public class ClientProxy extends CommonProxy { RenderingRegistry.registerEntityRenderingHandler(EntityAbilityLaser.class, new RenderAbilityLaser()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilityBeam.class, new RenderAbilityBeam()); RenderingRegistry.registerEntityRenderingHandler(EntityAbilitySweeper.class, new RenderAbilitySweeper()); + RenderingRegistry.registerEntityRenderingHandler(EntityAbilityZone.class, new RenderAbilityZone()); RenderingRegistry.registerEntityRenderingHandler(EntityCustomNpc.class, new RenderCustomNpc()); @@ -511,6 +514,8 @@ public class ClientProxy extends CommonProxy { } else { abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; + abilityNpc.height = 1.8f; + abilityNpc.width = 0.6f; } return new GuiNpcManageAbilities(abilityNpc, npc != null); } diff --git a/src/main/java/noppes/npcs/client/ClientTickHandler.java b/src/main/java/noppes/npcs/client/ClientTickHandler.java index 203cef3e2..d993762ee 100644 --- a/src/main/java/noppes/npcs/client/ClientTickHandler.java +++ b/src/main/java/noppes/npcs/client/ClientTickHandler.java @@ -6,6 +6,7 @@ import cpw.mods.fml.common.gameevent.InputEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.common.gameevent.TickEvent.Phase; import kamkeel.npcs.client.renderer.lightning.LightningBolt; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.telegraph.TelegraphManager; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.player.CheckPlayerValue; @@ -13,6 +14,7 @@ import kamkeel.npcs.network.packets.player.InputDevicePacket; import kamkeel.npcs.network.packets.player.ScreenSizePacket; import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket; import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ContainerPlayer; @@ -56,13 +58,16 @@ public class ClientTickHandler { if ((this.prevWorld == null || mc.theWorld == null) && this.prevWorld != mc.theWorld) { if (mc.theWorld == null) { ClientCacheHandler.clearCache(); + ClientAbilityState.reset(); } this.prevWorld = mc.theWorld; } if (event.phase == Phase.START) { EntityPlayer player = mc.thePlayer; if (player != null) { - boolean specialKeyDown = ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); + // Only process special key when no GUI screen is open + boolean specialKeyDown = mc.currentScreen == null + && ClientProxy.SpecialKey != null && Keyboard.isKeyDown(ClientProxy.SpecialKey.getKeyCode()); if (specialKeyDown != lastSpecialKeyDown) { PlayerData data = CustomNpcs.proxy.getPlayerData(player); if (data != null) { @@ -72,6 +77,33 @@ public class ClientTickHandler { lastSpecialKeyDown = specialKeyDown; } + // Suppress player input during ability-controlled phases. + // Only suppress when no GUI screen is open (screens already capture input). + if (mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput()) { + // Unpress movement keybinds at the source BEFORE updatePlayerMoveState() reads them. + // This is more robust than just zeroing movementInput fields, because + // updatePlayerMoveState() reads directly from keybind pressed state. + KeyBinding.setKeyBindState(mc.gameSettings.keyBindForward.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindBack.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindLeft.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindRight.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindJump.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindSneak.getKeyCode(), false); + KeyBinding.setKeyBindState(mc.gameSettings.keyBindSprint.getKeyCode(), false); + + // Also zero the movementInput values directly as a safety net + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; + } + if (mc.currentScreen == null && ClientAbilityState.shouldLockRotation()) { + mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch; + } + if (player.ridingEntity instanceof EntityNPCInterface) { EntityNPCInterface mount = (EntityNPCInterface) player.ridingEntity; if (mount.advanced.role == EnumRoleType.Mount && mount.roleInterface instanceof RoleMount) { @@ -84,8 +116,43 @@ public class ClientTickHandler { } } if (event.phase == Phase.END) { - if (mc.thePlayer != null && mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) { - renderCNPCPlayer.itemRenderer.updateEquippedItem(); + if (mc.thePlayer != null) { + // Re-enforce ability locks AFTER entity update. + // EntityPlayerSP.onLivingUpdate() calls updatePlayerMoveState() which + // overwrites Phase.START suppression with actual keyboard state, causing + // client-predicted movement that fights the server lock. Undo it here. + // Skip when a GUI screen is open (screens already capture all input). + if (mc.currentScreen == null && ClientAbilityState.shouldSuppressMovementInput()) { + mc.thePlayer.movementInput.moveForward = 0; + mc.thePlayer.movementInput.moveStrafe = 0; + mc.thePlayer.movementInput.jump = false; + mc.thePlayer.movementInput.sneak = false; + + // Zero horizontal motion (unless ability provides its own movement) + if (!ClientAbilityState.hasAbilityMovement) { + mc.thePlayer.motionX = 0; + mc.thePlayer.motionZ = 0; + } + + // Prevent jumping when locked (allow gravity only if not flying) + if ((ClientAbilityState.movementLocked || ClientAbilityState.positionLocked) + && !ClientAbilityState.hasAbilityMovement + && !AbilityController.Instance.isPlayerFlying(mc.thePlayer)) { + mc.thePlayer.motionY = Math.min(mc.thePlayer.motionY, 0); + } + } + + if (mc.currentScreen == null && ClientAbilityState.shouldLockRotation()) { + mc.thePlayer.rotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.rotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.prevRotationYaw = ClientAbilityState.lockedYaw; + mc.thePlayer.prevRotationPitch = ClientAbilityState.lockedPitch; + mc.thePlayer.rotationYawHead = ClientAbilityState.lockedYaw; + } + + if (mc.theWorld != null && !mc.isGamePaused() && ClientEventHandler.hasOverlays(mc.thePlayer)) { + renderCNPCPlayer.itemRenderer.updateEquippedItem(); + } } return; } @@ -143,8 +210,9 @@ public class ClientTickHandler { @SubscribeEvent public void onKey(InputEvent.KeyInputEvent event) { + Minecraft mc = Minecraft.getMinecraft(); + if (ClientProxy.NPCButton.isPressed()) { - Minecraft mc = Minecraft.getMinecraft(); if (mc.currentScreen == null) { InventoryTabCustomNpc.tabHelper(); } else if (mc.currentScreen instanceof GuiCNPCInventory) @@ -155,10 +223,33 @@ public class ClientTickHandler { int key = Keyboard.getEventKey(); boolean keyDown = Keyboard.isKeyDown(key); + // Block movement keys during ability lock (only when no GUI is open and world exists). + // Non-movement keys (ESC, chat, inventory, etc.) always pass through. + if (mc.theWorld != null && mc.currentScreen == null && keyDown + && ClientAbilityState.shouldSuppressMovementInput() && isMovementKey(key)) { + // Unpress the keybind so vanilla doesn't process it + KeyBinding.setKeyBindState(key, false); + return; + } + InputDevicePacket.sendKeyboard(key, keyDown); } } + /** + * Check if a key code corresponds to a movement keybind (WASD, jump, sneak, sprint). + */ + private boolean isMovementKey(int keyCode) { + Minecraft mc = Minecraft.getMinecraft(); + return keyCode == mc.gameSettings.keyBindForward.getKeyCode() + || keyCode == mc.gameSettings.keyBindBack.getKeyCode() + || keyCode == mc.gameSettings.keyBindLeft.getKeyCode() + || keyCode == mc.gameSettings.keyBindRight.getKeyCode() + || keyCode == mc.gameSettings.keyBindJump.getKeyCode() + || keyCode == mc.gameSettings.keyBindSneak.getKeyCode() + || keyCode == mc.gameSettings.keyBindSprint.getKeyCode(); + } + private boolean isIgnoredKey(int key) { int[] var2 = this.ignoreKeys; int var3 = var2.length; diff --git a/src/main/java/noppes/npcs/client/fx/CustomFX.java b/src/main/java/noppes/npcs/client/fx/CustomFX.java index 7a296d8e8..79d5f452c 100644 --- a/src/main/java/noppes/npcs/client/fx/CustomFX.java +++ b/src/main/java/noppes/npcs/client/fx/CustomFX.java @@ -84,6 +84,10 @@ public class CustomFX extends EntityFX { this.imageData = ClientCacheHandler.getImageData(this.directory); } + public void setMaxAge(int age) { + this.particleMaxAge = age; + } + public static CustomFX fromScriptedParticle(ScriptParticle particle, World worldObj, Entity entity) { EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; if (entity == player) { diff --git a/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java b/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java new file mode 100644 index 000000000..80f6f687b --- /dev/null +++ b/src/main/java/noppes/npcs/client/fx/ZoneParticleFX.java @@ -0,0 +1,65 @@ +package noppes.npcs.client.fx; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.particle.EntityFX; +import net.minecraft.world.World; + +/** + * Simple particle for zone visual effects (Trap/Hazard styles). + * Uses vanilla particle atlas with color tinting. Fades out over lifetime. + */ +@SideOnly(Side.CLIENT) +public class ZoneParticleFX extends EntityFX { + + private final float startAlpha; + private final boolean glow; + + public ZoneParticleFX(World world, double x, double y, double z, + double motionX, double motionY, double motionZ, + float r, float g, float b, float alpha, + float scale, int maxAge, float gravity, boolean glow) { + super(world, x, y, z, 0, 0, 0); + this.motionX = motionX; + this.motionY = motionY; + this.motionZ = motionZ; + this.particleRed = r; + this.particleGreen = g; + this.particleBlue = b; + this.particleAlpha = alpha; + this.startAlpha = alpha; + this.particleScale = scale; + this.particleMaxAge = maxAge; + this.particleGravity = gravity; + this.glow = glow; + this.noClip = true; + this.setParticleTextureIndex(0); + } + + @Override + public int getBrightnessForRender(float partialTick) { + return glow ? 0xF000F0 : super.getBrightnessForRender(partialTick); + } + + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + + if (this.particleAge++ >= this.particleMaxAge) { + this.setDead(); + return; + } + + // Linear fade out + float lifeRatio = (float) this.particleAge / (float) this.particleMaxAge; + this.particleAlpha = this.startAlpha * (1.0f - lifeRatio); + + // Movement + this.motionY -= 0.04D * (double) this.particleGravity; + this.posX += this.motionX; + this.posY += this.motionY; + this.posZ += this.motionZ; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java index 3e194f85f..38777d9ab 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialog.java @@ -198,6 +198,5 @@ public class SubGuiNpcDialog extends SubGuiInterface implements ISubGuiListener, } public void save() { - PacketClient.sendClient(new DialogSavePacket(this.dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false)); } } diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java index 807a3e719..86f174bc4 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcDialogVisual.java @@ -521,8 +521,6 @@ public class SubGuiNpcDialogVisual extends SubGuiInterface implements ISubGuiLis public void save() { GuiNpcTextField.unfocus(); - if (dialog.id >= 0) - PacketClient.sendClient(new DialogSavePacket(((SubGuiNpcDialog) parent).dialogCategoryID, dialog.writeToNBT(new NBTTagCompound()), false)); } private DialogImage getSelectedImage() { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java index a128d3760..36cbfff37 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcMeleeProperties.java @@ -12,7 +12,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfieldListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; public SubGuiNpcMeleeProperties(DataStats stats) { this.stats = stats; @@ -42,18 +41,28 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi getTextField(4).integersOnly = true; getTextField(4).setMinMaxDefault(0, Integer.MAX_VALUE, 0); addLabel(new GuiNpcLabel(5, "stats.meleeeffect", guiLeft + 5, guiTop + 135)); - addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, potionNames, stats.potionType.ordinal())); + addButton(new GuiButtonBiDirectional(5, guiLeft + 85, guiTop + 130, 100, 20, EnumPotionType.getLangKeys(), stats.potionType.ordinal())); + if (stats.potionType == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(8, "effect.potionid", guiLeft + 198, guiTop + 119)); + addTextField(new GuiNpcTextField(8, this, fontRendererObj, guiLeft + 200, guiTop + 132, 40, 18, stats.potionManualId + "")); + getTextField(8).integersOnly = true; + getTextField(8).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + } + + int y = guiTop + 160; if (stats.potionType != EnumPotionType.None) { - addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, guiTop + 165)); - addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, guiTop + 160, 40, 18, stats.potionDuration + "")); + addLabel(new GuiNpcLabel(6, "gui.time", guiLeft + 5, y + 5)); + addTextField(new GuiNpcTextField(6, this, fontRendererObj, guiLeft + 85, y, 40, 18, stats.potionDuration + "")); getTextField(6).integersOnly = true; getTextField(6).setMinMaxDefault(1, Integer.MAX_VALUE, 5); if (stats.potionType != EnumPotionType.Fire) { - addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, guiTop + 195)); - addButton(new GuiButtonBiDirectional(7, guiLeft + 85, guiTop + 190, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); + y += 30; + addLabel(new GuiNpcLabel(7, "stats.amplify", guiLeft + 5, y + 5)); + addButton(new GuiButtonBiDirectional(7, guiLeft + 85, y, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.potionAmp)); } } - addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + 190, 60, 20, "gui.done")); + + addButton(new GuiNpcButton(66, guiLeft + 190, guiTop + ySize - 26, 60, 20, "gui.done")); } public void unFocused(GuiNpcTextField textfield) { @@ -67,13 +76,15 @@ public class SubGuiNpcMeleeProperties extends SubGuiInterface implements ITextfi stats.knockback = textfield.getInteger(); } else if (textfield.id == 6) { stats.potionDuration = textfield.getInteger(); + } else if (textfield.id == 8) { + stats.potionManualId = textfield.getInteger(); } } protected void actionPerformed(GuiButton guibutton) { GuiNpcButton button = (GuiNpcButton) guibutton; if (button.id == 5) { - stats.potionType = EnumPotionType.values()[button.getValue()]; + stats.potionType = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 7) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java index 8acb8fc8c..e0806a538 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcProjectiles.java @@ -15,7 +15,6 @@ import noppes.npcs.constants.EnumPotionType; public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { private DataStats stats; - private String[] potionNames = new String[]{"gui.none", "tile.fire.name", "potion.poison", "potion.hunger", "potion.weakness", "potion.moveSlowdown", "potion.confusion", "potion.blindness", "potion.wither"}; private String[] trailNames = new String[]{"gui.none", "trail.smoke", "trail.portal", "trail.redstone", "trail.lightning", "trail.largesmoke", "trail.magic", "trail.enchant", "trail.crit", "trail.explode", "trail.music", "trail.flame", "trail.lava", "trail.splash", @@ -76,22 +75,29 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL } addLabel(new GuiNpcLabel(7, "stats.rangedeffect", guiLeft + 210, y + 5)); - addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, potionNames, stats.pEffect.ordinal())); + addButton(new GuiButtonBiDirectional(4, guiLeft + 280, y, 100, 20, EnumPotionType.getLangKeys(), stats.pEffect.ordinal())); if (stats.pEffect != EnumPotionType.None) { int internalY = y + 30; + if (stats.pEffect == EnumPotionType.Manual) { + addLabel(new GuiNpcLabel(110, "effect.potionid", guiLeft + 210, internalY + 5)); + addTextField(new GuiNpcTextField(11, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pManualId + "")); + getTextField(11).integersOnly = true; + getTextField(11).setMinMaxDefault(0, Integer.MAX_VALUE, 0); + internalY += 30; + } addLabel(new GuiNpcLabel(50, "gui.time", guiLeft + 210, internalY + 5)); addTextField(new GuiNpcTextField(5, this, fontRendererObj, guiLeft + 330, internalY, 52, 20, stats.pDur + "")); getTextField(5).integersOnly = true; getTextField(5).setMinMaxDefault(1, Integer.MAX_VALUE, 5); - if (stats.pEffect != EnumPotionType.Fire) { - internalY += 30; - addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); - addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); - } else { + if (stats.pEffect == EnumPotionType.Fire) { internalY += 30; addLabel(new GuiNpcLabel(100, "stats.burnItem", guiLeft + 210, internalY + 5)); addButton(new GuiNpcButtonYesNo(100, guiLeft + 330, internalY, 52, 20, stats.pBurnItem)); + } else { + internalY += 30; + addLabel(new GuiNpcLabel(70, "stats.amplify", guiLeft + 210, internalY + 5)); + addButton(new GuiButtonBiDirectional(10, guiLeft + 280, internalY, 52, 20, new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}, stats.pEffAmp)); } } @@ -126,6 +132,8 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pSpeed = textfield.getInteger(); } else if (textfield.id == 5) { stats.pDur = textfield.getInteger(); + } else if (textfield.id == 11) { + stats.pManualId = textfield.getInteger(); } } @@ -146,7 +154,7 @@ public class SubGuiNpcProjectiles extends SubGuiInterface implements ITextfieldL stats.pArea = button.getValue(); } if (button.id == 4) { - stats.pEffect = EnumPotionType.values()[button.getValue()]; + stats.pEffect = EnumPotionType.fromOrdinal(button.getValue()); initGui(); } if (button.id == 5) { diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java b/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java index 6406733be..9d693db81 100644 --- a/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java +++ b/src/main/java/noppes/npcs/client/gui/SubGuiNpcQuest.java @@ -239,6 +239,5 @@ public class SubGuiNpcQuest extends SubGuiInterface implements ISubGuiListener, } public void save() { - PacketClient.sendClient(new QuestSavePacket(this.questCategoryID, quest.writeToNBT(new NBTTagCompound()), false)); } } diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java new file mode 100644 index 000000000..b8fb9e376 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiTrapPresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiTrapPresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"HIDDEN", "VENOM", "EXPLOSIVE", "CURSED", "SHOCK", "SNARE"}; + private static final String[] PRESET_LABELS = { + "ability.preset.hidden", "ability.preset.venom", "ability.preset.explosive", + "ability.preset.cursed", "ability.preset.shock", "ability.preset.snare" + }; + private static final int[] PRESET_COLORS = {0x888888, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiTrapPresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java new file mode 100644 index 000000000..f67ef3db1 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiZonePresetSelector.java @@ -0,0 +1,72 @@ +package noppes.npcs.client.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.SubGuiInterface; + +@SideOnly(Side.CLIENT) +public class SubGuiZonePresetSelector extends SubGuiInterface { + + public String selectedPreset = null; + + private static final String[] PRESET_NAMES = {"DEFAULT", "TOXIC", "INFERNO", "ARCANE", "ELECTRIC", "FROST"}; + private static final String[] PRESET_LABELS = { + "ability.preset.default", "ability.preset.toxic", "ability.preset.inferno", + "ability.preset.arcane", "ability.preset.electric", "ability.preset.frost" + }; + private static final int[] PRESET_COLORS = {0xCCCCCC, 0x44DD44, 0xFF6611, 0xAA44FF, 0x4488FF, 0x88CCFF}; + + public SubGuiZonePresetSelector() { + xSize = 170; + ySize = 135; + setBackground("menubg.png"); + } + + @Override + public void initGui() { + super.initGui(); + int btnW = 72; + int btnH = 20; + int gapY = 4; + int col1 = guiLeft + 7; + int col2 = col1 + btnW + 6; + int startY = guiTop + 22; + + for (int i = 0; i < 6; i++) { + int x = (i % 2 == 0) ? col1 : col2; + int y = startY + (i / 2) * (btnH + gapY); + addButton(new GuiNpcButton(i, x, y, btnW, btnH, PRESET_LABELS[i])); + } + + int cancelY = startY + 3 * (btnH + gapY) + 4; + addButton(new GuiNpcButton(10, guiLeft + xSize / 2 - 36, cancelY, 72, btnH, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton btn) { + super.actionPerformed(btn); + if (btn.id >= 0 && btn.id < 6) { + selectedPreset = PRESET_NAMES[btn.id]; + close(); + } else if (btn.id == 10) { + close(); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float f) { + super.drawScreen(mouseX, mouseY, f); + drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.applyPreset"), guiLeft + xSize / 2, guiTop + 8, 0xFFFFFF); + for (int i = 0; i < 6; i++) { + GuiNpcButton btn = getButton(i); + if (btn != null && btn.visible) { + int x = btn.xPosition + 4; + int y = btn.yPosition + 5; + drawRect(x, y, x + 10, y + 10, 0xFF000000 | PRESET_COLORS[i]); + } + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index e86370492..2e89d3d49 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -3,10 +3,12 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilitySlot; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; @@ -57,6 +59,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC private String search = ""; private int selectedAbilityIndex = -1; + // Existing preset names for duplicate checking + private final Set existingPresetNames = new HashSet<>(); + + // Pending variant selection + private String pendingTypeId = null; + public static int modIndex = 0; public static ScrollType scrollType = ScrollType.CNPC; @@ -64,6 +72,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC super(npc); PacketClient.sendClient(new AbilitiesGetAllPacket()); PacketClient.sendClient(new AbilitiesNpcGetPacket()); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); } public enum ScrollType { @@ -79,7 +88,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (Register.isEmpty("ability")) return "modded"; - return Register.REGISTERED_NAMESPACES.get("ability").get(modIndex); + String namespace = Register.REGISTERED_NAMESPACES.get("ability").get(modIndex); + String displayName = Register.NAMESPACE_DISPLAY_NAMES.get(namespace); + return displayName != null ? displayName : namespace; case ALL: return "filter.all"; default: return name(); } @@ -92,38 +103,38 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC int y = guiTop + 10; - // Enabled checkbox - addLabel(new GuiNpcLabel(100, "gui.enabled", guiLeft + 5, y + 5)); - addButton(new GuiNpcButton(100, guiLeft + 55, y, 50, 20, new String[]{"gui.no", "gui.yes"}, abilitiesEnabled ? 1 : 0)); + addButton(new GuiNpcButton(50, guiLeft + 5, y, 140, 20, scrollType.toString())); // Cooldown range: Min Cooldown and Max Cooldown (spaced apart more) - addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 115, y + 5)); - GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 165, y, 40, 20, "" + minCooldown); + addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 210, y + 5)); + GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 260, y, 40, 20, "" + minCooldown); minField.setIntegersOnly(); minField.setMinMaxDefault(0, 10000, 20); addTextField(minField); - addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 260, y + 5)); - GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 310, y, 40, 20, "" + maxCooldown); + addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 320, y + 5)); + GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown); maxField.setIntegersOnly(); maxField.setMinMaxDefault(0, 10000, 60); addTextField(maxField); y += 28; + // Enabled checkbox + addButton(new GuiNpcButton(100, guiLeft + 334, y + 145, 76, 20, new String[]{"gui.disabled", "gui.enabled"}, abilitiesEnabled ? 1 : 0)); + getButton(100).packedFGColour = abilitiesEnabled ? 0x00FF00 : 0xFF0000; + // Left scroll: available ability types addLabel(new GuiNpcLabel(1, "ability.availableTypes", guiLeft + 5, y)); if (availableTypesScroll == null) { availableTypesScroll = new GuiCustomScroll(this, 0); - availableTypesScroll.setSize(140, 103); + availableTypesScroll.setSize(140, 130); } availableTypesScroll.guiLeft = guiLeft + 5; availableTypesScroll.guiTop = y + 12; availableTypesScroll.setList(getFilteredTypeList()); addScroll(availableTypesScroll); - addButton(new GuiNpcButton(50, guiLeft + 5, y + 120, 140, 20, scrollType.toString())); - // Search bar for types addTextField(new GuiNpcTextField(4, this, fontRendererObj, guiLeft + 5, y + 145, 140, 18, search)); @@ -131,9 +142,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC addLabel(new GuiNpcLabel(2, "ability.npcAbilities", guiLeft + 210, y)); if (npcAbilitiesScroll == null) { npcAbilitiesScroll = new GuiCustomScroll(this, 1); - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } else { - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } npcAbilitiesScroll.guiLeft = guiLeft + 210; npcAbilitiesScroll.guiTop = y + 12; @@ -142,11 +153,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Center buttons: Add/Remove int centerX = guiLeft + 158; - addButton(new GuiNpcButton(70, centerX, y + 40, 40, 20, ">>>")); // Add - addButton(new GuiNpcButton(71, centerX, y + 62, 40, 20, "<<<")); // Remove + addButton(new GuiNpcButton(70, centerX, y + 15, 40, 20, ">>>")); // Add + addButton(new GuiNpcButton(71, centerX, y + 37, 40, 20, "<<<")); // Remove + getButton(71).setEnabled(selectedAbilityIndex >= 0); // Load button (under the add/remove arrows) - addButton(new GuiNpcButton(75, centerX, y + 90, 40, 20, "gui.load")); + addButton(new GuiNpcButton(75, centerX, y + 60, 40, 20, "gui.load")); // On/Off toggle for selected ability (under Load button) if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { @@ -156,9 +168,16 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC addButton(toggleBtn); } + // Check if selected ability is built-in (non-editable) + boolean selectedIsBuiltIn = false; + if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { + Ability sel = npcSlots.get(selectedAbilityIndex).getAbility(); + if (sel != null && sel.isBuiltIn()) selectedIsBuiltIn = true; + } + // Right side buttons: Edit and Up/Down carrots with Save button addButton(new GuiNpcButton(72, guiLeft + 210, y + 145, 55, 20, "gui.edit")); - getButton(72).setEnabled(selectedAbilityIndex >= 0); + getButton(72).setEnabled(selectedAbilityIndex >= 0 && !selectedIsBuiltIn); // Up/Down carrot buttons addButton(new GuiNpcButton(73, guiLeft + 270, y + 145, 20, 20, "<")); @@ -167,8 +186,8 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC getButton(74).setEnabled(selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size() - 1); // Save button (to the right of carrots, only enabled when ability is selected) - addButton(new GuiNpcButton(76, guiLeft + 320, y + 145, 50, 20, "gui.save")); - getButton(76).setEnabled(selectedAbilityIndex >= 0); + addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save")); + getButton(76).setEnabled(selectedAbilityIndex >= 0 && !selectedIsBuiltIn); } @Override @@ -178,6 +197,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Enabled toggle if (id == 100) { abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1; + initGui(); save(); return; } @@ -188,8 +208,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String displayName = availableTypesScroll.getSelected(); String typeId = displayNameToTypeId.get(displayName); if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } Ability newAbility = AbilityController.Instance.create(typeId); if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } newAbility.setId(UUID.randomUUID().toString()); npcSlots.add(AbilitySlot.inline(newAbility)); selectedAbilityIndex = npcSlots.size() - 1; @@ -225,6 +254,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } else { Ability ability = slot.getAbility(); if (ability != null) { + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } } @@ -274,9 +304,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Ability abilityToSave = npcSlots.get(selectedAbilityIndex).getAbility(); if (abilityToSave != null) { if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { + abilityToSave.setNpcInlineEdit(true); setSubGui(abilityToSave.createConfigGui(this)); } else { - setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave)); + setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames)); } } } @@ -286,9 +317,11 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Toggle selected ability on/off if (id == 77) { if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { - Ability ability = npcSlots.get(selectedAbilityIndex).getAbility(); + AbilitySlot slot = npcSlots.get(selectedAbilityIndex); + Ability ability = slot.getAbility(); if (ability != null) { - ability.setEnabled(((GuiNpcButton) guibutton).getValue() == 1); + boolean enabled = ((GuiNpcButton) guibutton).getValue() == 1; + slot.setEnabled(enabled); updateNpcAbilitiesList(); selectAbilityByIndex(selectedAbilityIndex); initGui(); @@ -301,7 +334,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (id == 50) { if (scrollType != ScrollType.MODDED) { ScrollType[] values = ScrollType.values(); - scrollType = values[(scrollType.ordinal() + 1) % values.length]; + ScrollType next = values[(scrollType.ordinal() + 1) % values.length]; + // Skip MODDED if no namespaces are registered + if (next == ScrollType.MODDED && Register.isEmpty("ability")) { + next = ScrollType.ALL; + } + scrollType = next; } else { List list = Register.REGISTERED_NAMESPACES.get("ability"); @@ -320,8 +358,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Map dummyMap = new HashMap<>(allAbilityTypes); filteredAbilityTypes.clear(); filteredAbilityTypes.putAll(getFilteredData(dummyMap)); - } + // Reset scroll position when changing category + if (availableTypesScroll != null) { + availableTypesScroll.resetScroll(); + } + } initGui(); } @@ -336,6 +378,16 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (availableTypesScroll != null) { availableTypesScroll.setList(getFilteredTypeList()); } + } else if (type == EnumScrollData.CUSTOM_ABILITIES) { + existingPresetNames.clear(); + for (String key : data.keySet()) { + int tabIndex = key.indexOf('\t'); + if (tabIndex > 0) { + existingPresetNames.add(key.substring(0, tabIndex)); + } else { + existingPresetNames.add(key); + } + } } initGui(); } @@ -423,6 +475,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String displayName = I18n.format(typeId); // Search matches either the display name or the typeId if (search.isEmpty() || displayName.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { + // Gray out built-in types to distinguish them from configurable types + if (AbilityController.Instance.isBuiltInType(typeId)) { + displayName = "\u00A77" + displayName; + } list.add(displayName); displayNameToTypeId.put(displayName, typeId); } @@ -435,8 +491,31 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC for (int i = 0; i < npcSlots.size(); i++) { list.add(getAbilityListEntry(i)); } + + // Sort: enabled first, then numerically by slot index + Collections.sort(list, new Comparator() { + @Override + public int compare(String a, String b) { + boolean aEnabled = a.startsWith("\u00A7a"); + boolean bEnabled = b.startsWith("\u00A7a"); + if (aEnabled != bEnabled) return aEnabled ? -1 : 1; + return extractIndex(a) - extractIndex(b); + } + + private int extractIndex(String entry) { + String stripped = entry.replaceAll("\u00A7.", "").trim(); + int dotIndex = stripped.indexOf("."); + if (dotIndex > 0) { + try { + return Integer.parseInt(stripped.substring(0, dotIndex).replaceAll("[^0-9]", "")); + } catch (NumberFormatException e) { } + } + return Integer.MAX_VALUE; + } + }); + if (npcAbilitiesScroll != null) { - npcAbilitiesScroll.setList(list); + npcAbilitiesScroll.setUnsortedList(list); } } @@ -471,6 +550,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (slot.isReference()) { return colorPrefix + (index + 1) + ". \u00A7e> " + nameDisplay + "\u00A7r"; } + if (ability.isBuiltIn()) { + return colorPrefix + (index + 1) + ". \u00A77" + nameDisplay + "\u00A7r"; + } return colorPrefix + (index + 1) + ". " + nameDisplay; } @@ -571,11 +653,13 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { if (scroll == npcAbilitiesScroll && selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { AbilitySlot slot = npcSlots.get(selectedAbilityIndex); + Ability ability = slot.getAbility(); + if (ability != null && ability.isBuiltIn()) return; if (slot.isReference()) { setSubGui(new SubGuiAbilityEditMode()); } else { - Ability ability = slot.getAbility(); if (ability != null) { + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } } @@ -605,7 +689,24 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiAbilityEditMode) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilitySlot.inline(newAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + save(); + } + } + pendingTypeId = null; + initGui(); + } else if (subgui instanceof SubGuiAbilityEditMode) { int mode = ((SubGuiAbilityEditMode) subgui).getResult(); if (mode < 0) return; // cancelled @@ -617,6 +718,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC Ability ability = slot.getAbility(); if (ability != null) { ability.setId(UUID.randomUUID().toString()); + ability.setNpcInlineEdit(true); setSubGui(ability.createConfigGui(this)); } updateNpcAbilitiesList(); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index c8802a1e0..bcfce7687 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -324,7 +324,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi @Override public void unFocused(GuiNpcTextField textField) { if (textField.id < DECLARATIVE_ID_START) return; - builder.handleTextFieldEvent(textField.id, textField); + if (builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); + } } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java index 9407d20c5..b8a4e0e66 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -7,24 +7,29 @@ import net.minecraft.client.gui.GuiButton; import noppes.npcs.client.gui.util.GuiNpcButton; import noppes.npcs.client.gui.util.GuiNpcLabel; import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.util.ISubGuiListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import java.util.Set; + /** * Confirmation dialog for saving an ability preset. * Uses packet-based communication for proper client-server architecture. */ -public class SubGuiAbilitySaveConfirm extends SubGuiInterface { +public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGuiListener { private final Ability ability; private final IAbilityConfigCallback callback; + private final Set existingNames; public SubGuiAbilitySaveConfirm(Ability ability) { - this(ability, null); + this(ability, null, null); } - public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback) { + public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback, Set existingNames) { this.ability = ability; this.callback = callback; + this.existingNames = existingNames; setBackground("menubg.png"); xSize = 200; @@ -52,14 +57,32 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface { int id = guibutton.id; if (id == 0) { - // Save the ability via packet - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); - if (callback != null) { - callback.onAbilitySaved(ability); + if (existingNames != null && existingNames.contains(ability.getName())) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return; } - close(); + doSave(); } else if (id == 1) { close(); } } + + private void doSave() { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + if (callback != null) { + callback.onAbilitySaved(ability); + } + close(); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiDuplicateNameConfirm) { + if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) { + doSave(); + } else { + close(); + } + } + } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java index 2bf724684..cce48bd32 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -5,22 +5,26 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import noppes.npcs.client.gui.util.GuiCustomScroll; import noppes.npcs.client.gui.util.GuiNpcButton; -import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * SubGui for selecting an ability type when creating a new ability. */ -public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener { +public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { private GuiCustomScroll scroll; private final HashMap displayNameToTypeId = new HashMap<>(); + private final HashMap allDisplayNameToTypeId = new HashMap<>(); private String selectedTypeId = null; + private String search = ""; public SubGuiAbilityTypeSelect() { setBackground("menubg.png"); @@ -32,32 +36,44 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS public void initGui() { super.initGui(); - addLabel(new GuiNpcLabel(0, "ability.selectType", guiLeft + 5, guiTop + 5)); + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); if (scroll == null) { scroll = new GuiCustomScroll(this, 0); - scroll.setSize(190, 165); + scroll.setSize(190, 145); } scroll.guiLeft = guiLeft + 5; - scroll.guiTop = guiTop + 16; + scroll.guiTop = guiTop + 26; addScroll(scroll); - List list = buildTypeList(); - scroll.setList(list); + buildAllTypes(); + scroll.setList(getFilteredTypeList()); addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.add")); getButton(0).setEnabled(scroll.hasSelected()); addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); } - private List buildTypeList() { - List list = new ArrayList<>(); - displayNameToTypeId.clear(); + private void buildAllTypes() { + allDisplayNameToTypeId.clear(); String[] types = AbilityController.Instance.getTypes(); for (String typeId : types) { + // Exclude built-in types — they cannot be created as custom presets + if (AbilityController.Instance.isBuiltInType(typeId)) continue; String displayName = I18n.format(typeId); - list.add(displayName); - displayNameToTypeId.put(displayName, typeId); + allDisplayNameToTypeId.put(displayName, typeId); + } + } + + private List getFilteredTypeList() { + List list = new ArrayList<>(); + displayNameToTypeId.clear(); + for (Map.Entry entry : allDisplayNameToTypeId.entrySet()) { + String displayName = entry.getKey(); + if (search.isEmpty() || displayName.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) { + list.add(displayName); + displayNameToTypeId.put(displayName, entry.getValue()); + } } return list; } @@ -89,6 +105,22 @@ public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomS } } + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + if (!search.equals(getTextField(10).getText())) { + search = getTextField(10).getText().toLowerCase(); + scroll.setList(getFilteredTypeList()); + scroll.resetScroll(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + public String getSelectedTypeId() { return selectedTypeId; } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java new file mode 100644 index 000000000..1c65d0dc6 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -0,0 +1,154 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +/** + * SubGui for selecting a variant/template when creating a new ability. + * Uses a scroll list with group headers for external addon variants. + */ +public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICustomScrollListener { + + private final List variants; + private int selectedIndex = -1; + + // Maps each scroll list index to a variant list index (-1 for non-selectable entries) + private final List scrollToVariantIndex = new ArrayList<>(); + + public SubGuiAbilityVariantSelect(List variants) { + this.variants = variants; + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8)); + + // Build the unsorted scroll list with group headers + List scrollList = new ArrayList<>(); + scrollToVariantIndex.clear(); + + boolean hasBaseVariants = false; + boolean hasGroupedVariants = false; + + for (AbilityVariant v : variants) { + if (v.getGroup() == null) + hasBaseVariants = true; + else + hasGroupedVariants = true; + } + + // Add base (non-grouped) variants first + for (int i = 0; i < variants.size(); i++) { + if (variants.get(i).getGroup() == null) { + scrollList.add(variants.get(i).getDisplayKey()); + scrollToVariantIndex.add(i); + } + } + + // Blank separator between base and grouped variants + if (hasBaseVariants && hasGroupedVariants) { + scrollList.add(""); + scrollToVariantIndex.add(-1); + } + + // Add grouped variants with group headers + String lastGroup = null; + for (int i = 0; i < variants.size(); i++) { + AbilityVariant v = variants.get(i); + if (v.getGroup() == null) + continue; + + if (!v.getGroup().equals(lastGroup)) { + scrollList.add(v.getGroup()); + scrollToVariantIndex.add(-1); + lastGroup = v.getGroup(); + } + + scrollList.add(v.getDisplayKey()); + scrollToVariantIndex.add(i); + } + + GuiCustomScroll scroll = new GuiCustomScroll(this, 0); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = guiTop + 22; + scroll.setUnsortedList(scrollList); + scroll.setSize(190, 155); + + // Mark blank separators and group headers as non-interactive colored entries + scroll.colors.put("", 0x000000); + if (lastGroup != null) { + for (int i = 0; i < variants.size(); i++) { + String group = variants.get(i).getGroup(); + if (group != null) + scroll.colors.put(group, 0xFFFF00); // Yellow + } + } + + // Restore selection in scroll + if (selectedIndex >= 0) { + for (int s = 0; s < scrollToVariantIndex.size(); s++) { + if (scrollToVariantIndex.get(s) == selectedIndex) { + scroll.selected = s; + break; + } + } + } + + addScroll(scroll); + + // Select / Cancel buttons + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(selectedIndex >= 0); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0 && scroll.selected >= 0 && scroll.selected < scrollToVariantIndex.size()) { + int variantIdx = scrollToVariantIndex.get(scroll.selected); + if (variantIdx >= 0) { + selectedIndex = variantIdx; + getButton(0).setEnabled(true); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (selectedIndex >= 0) { + close(); + } + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id == 0 && selectedIndex >= 0) { + close(); + } else if (id == 1) { + selectedIndex = -1; + close(); + } + } + + public int getSelectedIndex() { + return selectedIndex; + } + + public List getVariants() { + return variants; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java new file mode 100644 index 000000000..b16386c32 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java @@ -0,0 +1,47 @@ +package noppes.npcs.client.gui.advanced; + +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; + +/** + * Confirmation dialog shown when saving an ability preset with a name that already exists. + */ +public class SubGuiDuplicateNameConfirm extends SubGuiInterface { + + private boolean confirmed = false; + + public SubGuiDuplicateNameConfirm() { + setBackground("menubg.png"); + xSize = 220; + ySize = 80; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y)); + + y += 30; + addButton(new GuiNpcButton(0, guiLeft + 20, y, 80, 20, "gui.continue")); + addButton(new GuiNpcButton(1, guiLeft + 120, y, 80, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + close(); + } else if (guibutton.id == 1) { + confirmed = false; + close(); + } + } + + public boolean isConfirmed() { + return confirmed; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java index 9263cc880..aec4b766a 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -32,8 +32,8 @@ public class FieldDef { private String hoverText = null; // Numeric range - private float min = Float.MIN_VALUE; - private float max = Float.MAX_VALUE; + private float min = 0; + private float max = Float.POSITIVE_INFINITY; // Enum support private Class> enumClass; @@ -154,8 +154,8 @@ public class FieldDef { public static FieldDef colorSubGui(String label, Supplier getter, Consumer setter) { return subGuiField(label, - () -> new SubGuiColorSelector(getter.get()), - gui -> setter.accept(((SubGuiColorSelector) gui).color & 0x00FFFFFF)) + () -> new SubGuiColorSelector(getter.get() & 0xFFFFFF), + gui -> setter.accept((((SubGuiColorSelector) gui).color & 0x00FFFFFF) | (getter.get() & 0xFF000000))) .buttonLabel(() -> String.format("%06X", getter.get() & 0xFFFFFF)) .buttonTextColor(() -> getter.get() & 0xFFFFFF); } @@ -272,7 +272,7 @@ public class FieldDef { public String getHoverText() { return hoverText; } public float getMin() { return min; } public float getMax() { return max; } - public boolean hasRange() { return min != Float.MIN_VALUE || max != Float.MAX_VALUE; } + public boolean hasRange() { return min != Float.NEGATIVE_INFINITY || max != Float.POSITIVE_INFINITY; } public Class> getEnumClass() { return enumClass; } public String[] getStringEnumValues() { return stringEnumValues; } public Supplier getSubGuiFactory() { return subGuiFactory; } diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java index 42e117ecf..b1f123956 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -120,6 +120,9 @@ public class GuiFieldBuilder { continue; } + // Skip invisible fields + if (!def.isVisible()) continue; + // Section header if (def.getType() == FieldType.SECTION_HEADER) { y += 3; @@ -391,7 +394,7 @@ public class GuiFieldBuilder { /** * Handles text field unfocus events for declarative fields. - * Call from parent GUI's unFocused(). Returns true if the event was handled. + * Call from parent GUI's unFocused(). Returns true if the value actually changed. */ public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { FieldDef def = textFieldMap.get(textFieldId); @@ -399,14 +402,36 @@ public class GuiFieldBuilder { switch (def.getType()) { case FLOAT: - try { def.setValue(Float.parseFloat(field.getText())); } catch (NumberFormatException ignored) {} - return true; + try { + float newVal = Float.parseFloat(field.getText()); + Object old = def.getValue(); + float oldVal = old instanceof Number ? ((Number) old).floatValue() : 0f; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; case INT: - try { def.setValue(Integer.parseInt(field.getText())); } catch (NumberFormatException ignored) {} - return true; + try { + int newVal = Integer.parseInt(field.getText()); + Object old = def.getValue(); + int oldVal = old instanceof Number ? ((Number) old).intValue() : 0; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; case STRING: - def.setValue(field.getText()); - return true; + String newVal = field.getText(); + Object old = def.getValue(); + String oldVal = old != null ? old.toString() : ""; + if (!newVal.equals(oldVal)) { + def.setValue(newVal); + return true; + } + return false; default: return false; } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java index ac4675243..3ac3923b4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java @@ -65,16 +65,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void initGui() { super.initGui(); + // Toggle button - added FIRST to maintain stable buttonList index + // (prevents double-toggle when initGui() is called from actionPerformed) + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); + // Add/Remove buttons - only show for custom animations if (!showingBuiltIn) { this.addButton(new GuiNpcButton(0, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); this.addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 32, 45, 20, "gui.remove")); } - // Toggle button for Custom/Built-in - under Remove button - String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; - this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); - if (scrollAnimations == null) { scrollAnimations = new GuiCustomScroll(this, 0, 0); scrollAnimations.setSize(143, 185); @@ -200,11 +201,15 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol // Toggle button if (button.id == 10) { showingBuiltIn = !showingBuiltIn; - // Clear selection when switching views + // Clear selection and search when switching views selected = null; + search = ""; animation = new Animation(); currentIsBuiltIn = false; + playingAnimation = false; scrollAnimations.clear(); + // Re-request data to ensure both lists are populated + PacketClient.sendClient(new AnimationsGetPacket()); initGui(); return; } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java index 246e528f3..59adbdd91 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java @@ -85,11 +85,13 @@ public class GuiNPCManageFactions extends GuiNPCInterface2 implements IScrollDat addLabel(new GuiNpcLabel(3, "faction.hidden", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(3, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.hideFaction ? 1 : 0)); + getButton(3).setHoverText("faction.hidden.hover"); y += 23; addLabel(new GuiNpcLabel(4, "faction.attacked", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(4, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.getsAttacked ? 1 : 0)); + getButton(4).setHoverText("faction.attacked.hover"); y += 23; diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index 5296bb615..66e8ed46c 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -6,6 +6,7 @@ import kamkeel.npcs.controllers.data.ability.AbilityController; import java.util.UUID; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.ability.BuiltInAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket; import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket; @@ -16,7 +17,11 @@ import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.NoppesUtil; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect; +import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect; +import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; import noppes.npcs.client.gui.util.AbilityPreviewExecutor; import noppes.npcs.client.gui.util.GuiAbilityInterface; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -47,6 +52,7 @@ import java.util.Vector; * - Left side: 3D preview of NPC with ability effects * - Right side: Ability list with search * - Play/Pause/Stop buttons to preview abilities + * - Toggle between Custom and Built-in ability views */ public class GuiNpcManageAbilities extends GuiAbilityInterface implements ICustomScrollListener, ISubGuiListener, IAbilityConfigCallback, @@ -54,7 +60,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface // ==================== DATA ==================== private GuiCustomScroll scroll; - private HashMap abilityData = new HashMap<>(); + private HashMap customData = new HashMap<>(); + private HashMap builtInData = new HashMap<>(); /** Maps display name -> UUID for custom abilities */ private final HashMap displayToUuid = new HashMap<>(); private String selected = null; @@ -62,6 +69,17 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private String search = ""; private Ability selectedAbility = null; + // ==================== BUILT-IN TOGGLE ==================== + private boolean showingBuiltIn = false; + private boolean currentIsBuiltIn = false; + + // ==================== PENDING SAVE ==================== + private Ability pendingSaveAbility = null; + private boolean pendingNewCreation = false; + + // ==================== PENDING VARIANT ==================== + private String pendingTypeId = null; + // ==================== PREVIEW ==================== private AbilityPreviewExecutor previewExecutor; private long prevTick = 0; @@ -77,7 +95,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface previewExecutor = new AbilityPreviewExecutor(); previewExecutor.setParentGui(this); - // Request ability data from server + // Request ability data from server (sends both custom and built-in) PacketClient.sendClient(new CustomAbilitiesGetPacket()); // Enable animation data @@ -89,18 +107,26 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void initGui() { super.initGui(); - // Add button - addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); + // Toggle button — added FIRST to maintain stable buttonList index + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 52, 45, 20, toggleLabel)); - // Remove button - addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); - getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + if (!showingBuiltIn) { + // Add button — only for custom view + addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); - // Edit button - addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit")); - getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + // Remove button — only for custom view + addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); + getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + } - // Scroll list of saved abilities (right side) + // Edit button — hidden when viewing built-in + if (!showingBuiltIn && !currentIsBuiltIn) { + addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 74, 45, 20, "gui.edit")); + getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + } + + // Scroll list of abilities (right side) if (scroll == null) { scroll = new GuiCustomScroll(this, 0); scroll.setSize(143, 185); @@ -111,7 +137,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface // Update scroll list scroll.setList(getSearchList()); - if (selected != null && displayToUuid.containsKey(selected)) { + if (selected != null) { scroll.setSelected(selected); } @@ -123,9 +149,6 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface return; } - // ID/Name label (below search bar) - addLabel(new GuiNpcLabel(10, "ID: " + selectedAbility.getId(), guiLeft + 220, guiTop + 215)); - // Play/Pause/Stop buttons (below model preview area) String animTexture = "customnpcs:textures/gui/animation.png"; int playButtonOffsetX = 60; @@ -150,17 +173,34 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface } } + private HashMap getCurrentData() { + return showingBuiltIn ? builtInData : customData; + } + private List getSearchList() { - if (search.isEmpty()) { - return new ArrayList<>(displayToUuid.keySet()); - } - List list = new ArrayList<>(); - for (String name : displayToUuid.keySet()) { - if (name.toLowerCase().contains(search.toLowerCase())) { - list.add(name); + if (showingBuiltIn) { + if (search.isEmpty()) { + return new ArrayList<>(builtInData.keySet()); } + List list = new ArrayList<>(); + for (String name : builtInData.keySet()) { + if (name.toLowerCase().contains(search.toLowerCase())) { + list.add(name); + } + } + return list; + } else { + if (search.isEmpty()) { + return new ArrayList<>(displayToUuid.keySet()); + } + List list = new ArrayList<>(); + for (String name : displayToUuid.keySet()) { + if (name.toLowerCase().contains(search.toLowerCase())) { + list.add(name); + } + } + return list; } - return list; } @Override @@ -216,13 +256,30 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface int id = guibutton.id; - if (id == 2) { + // Toggle between custom and built-in views + if (id == 10) { + showingBuiltIn = !showingBuiltIn; + selected = null; + selectedUuid = null; + selectedAbility = null; + currentIsBuiltIn = false; + search = ""; + previewExecutor.stop(); + if (scroll != null) { + scroll.clear(); + } + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + initGui(); + return; + } + + if (id == 2 && !showingBuiltIn) { // Add — open type selection setSubGui(new SubGuiAbilityTypeSelect()); - } else if (id == 1 && selected != null && selectedUuid != null) { + } else if (id == 1 && !showingBuiltIn && selected != null && selectedUuid != null) { GuiYesNo guiyesno = new GuiYesNo(this, selected, StatCollector.translateToLocal("gui.delete"), 1); displayGuiScreen(guiyesno); - } else if (id == 100 && selectedAbility != null) { + } else if (id == 100 && !showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { // Edit previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); @@ -265,11 +322,20 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface String newSelection = scroll.getSelected(); if (newSelection != null && !newSelection.equals(selected)) { previewExecutor.stop(); - selected = newSelection; - selectedUuid = displayToUuid.get(selected); - if (selectedUuid != null) { - PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + + if (showingBuiltIn) { + // Fetch built-in ability by display name + selectedUuid = null; + currentIsBuiltIn = true; + PacketClient.sendClient(new BuiltInAbilityGetPacket(selected)); + } else { + // Fetch custom ability by UUID + selectedUuid = displayToUuid.get(selected); + currentIsBuiltIn = false; + if (selectedUuid != null) { + PacketClient.sendClient(new CustomAbilityGetPacket(selectedUuid)); + } } } } @@ -278,8 +344,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { if (scroll.id == 0 && selection != null && !selection.isEmpty()) { - // Double-click to edit - if (selectedAbility != null) { + // Double-click to edit — only for custom, non-built-in abilities + if (!showingBuiltIn && !currentIsBuiltIn && selectedAbility != null) { previewExecutor.stop(); setSubGui(selectedAbility.createConfigGui(this)); } @@ -290,7 +356,7 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void setData(Vector list, HashMap data, EnumScrollData type) { if (type == EnumScrollData.CUSTOM_ABILITIES) { String prevSelected = scroll != null ? scroll.getSelected() : null; - this.abilityData = data; + this.customData = data; displayToUuid.clear(); for (String key : data.keySet()) { // key format: "displayName\tUUID" @@ -303,18 +369,30 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface displayToUuid.put(key, key); } } - if (scroll != null) { + if (!showingBuiltIn && scroll != null) { scroll.setList(getSearchList()); if (prevSelected != null && displayToUuid.containsKey(prevSelected)) { scroll.setSelected(prevSelected); } } initGui(); + } else if (type == EnumScrollData.BUILTIN_ABILITIES) { + this.builtInData = data; + if (showingBuiltIn && scroll != null) { + scroll.setList(getSearchList()); + if (selected != null && builtInData.containsKey(selected)) { + scroll.setSelected(selected); + } + } + initGui(); } } @Override public void setGuiData(NBTTagCompound compound) { + // Check if this is a built-in ability response + currentIsBuiltIn = compound.hasKey("BuiltIn") && compound.getBoolean("BuiltIn"); + // Received ability data from server selectedAbility = AbilityController.Instance.fromNBT(compound); if (selectedAbility != null) { @@ -337,27 +415,111 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiAbilityTypeSelect) { - String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId(); - if (typeId != null) { - Ability newAbility = AbilityController.Instance.create(typeId); + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); newAbility.setId(UUID.randomUUID().toString()); - newAbility.setName(newAbility.getTypeId()); - // Save to server, then open config GUI - PacketClient.sendClient(new CustomAbilitySavePacket(newAbility.writeNBT())); - selectedAbility = newAbility; - selected = newAbility.getName(); - selectedUuid = newAbility.getId(); - previewExecutor.stop(); - setSubGui(selectedAbility.createConfigGui(this)); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + pendingTypeId = null; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + pendingTypeId = null; + openConfig(newAbility); return; } } + pendingTypeId = null; + } else if (subgui instanceof SubGuiAbilityTypeSelect) { + String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId(); + if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } + Ability newAbility = AbilityController.Instance.create(typeId); + if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } + newAbility.setId(UUID.randomUUID().toString()); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + openConfig(newAbility); + return; + } + } + } else if (subgui instanceof SubGuiDuplicateNameConfirm) { + SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; + if (confirm.isConfirmed() && pendingSaveAbility != null) { + if (pendingNewCreation) { + openConfig(pendingSaveAbility); + pendingSaveAbility = null; + pendingNewCreation = false; + return; + } else { + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; + } + } else if (pendingSaveAbility != null) { + if (pendingNewCreation) { + // Cancel new creation - discard + pendingSaveAbility = null; + pendingNewCreation = false; + } else { + // Cancel edit save - re-open config GUI to change name + Ability ability = pendingSaveAbility; + pendingSaveAbility = null; + setSubGui(ability.createConfigGui(this)); + return; + } + } + } else if (pendingSaveAbility != null) { + // Config GUI closed with a pending save (set by onAbilitySaved) + if (hasDuplicateName(pendingSaveAbility)) { + pendingNewCreation = false; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; } initGui(); } + private void openConfig(Ability ability) { + selectedAbility = ability; + selected = ability.getName(); + selectedUuid = ability.getId(); + previewExecutor.stop(); + setSubGui(ability.createConfigGui(this)); + } + + private boolean hasDuplicateName(Ability ability) { + String name = ability.getName(); + if (name == null || name.isEmpty()) return false; + for (java.util.Map.Entry entry : displayToUuid.entrySet()) { + if (entry.getKey().equals(name) && !entry.getValue().equals(ability.getId())) { + return true; + } + } + return false; + } + @Override public void confirmClicked(boolean result, int id) { NoppesUtil.openGUI(player, this); @@ -375,7 +537,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void onAbilitySaved(Ability ability) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + // Defer save until subGuiClosed where we can check for duplicate names + pendingSaveAbility = ability; } @Override diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java index 55f88ac8c..49edf72b6 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java @@ -337,18 +337,45 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData { protected void handleMouseClick(Slot slot, int slotId, int mouseButton, int modifier) { // Client-side balance prediction: immediately subtract currency cost on click // so the displayed balance updates instantly without waiting for server response. + // Must mirror ALL server-side checks in ContainerNPCTrader.slotClick() to avoid + // predicting a deduction for trades the server will reject. if (slotId >= 0 && slotId < 18 && mouseButton == 0) { long cost = currencyCost[slotId]; if (cost > 0 && playerBalance >= cost) { ItemStack sold = role.inventorySold.items.get(slotId); - if (sold != null && container.canBuy(slotId, player)) { + if (sold != null + && canGivePlayerClient(sold) + && container.isSlotEnabled(slotId, player) + && (!stockEnabled || availableStock[slotId] > 0) + && container.canBuy(slotId, player)) { playerBalance -= cost; + if (stockEnabled && availableStock[slotId] < Integer.MAX_VALUE) { + availableStock[slotId]--; + } } } } super.handleMouseClick(slot, slotId, mouseButton, modifier); } + /** + * Client-side mirror of ContainerNPCTrader.canGivePlayer. + * Checks if the item can be added to the player's cursor stack. + */ + private boolean canGivePlayerClient(ItemStack item) { + ItemStack held = player.inventory.getItemStack(); + if (held == null) { + return true; + } + if (NoppesUtilPlayer.compareItems(held, item, false, false)) { + int k1 = item.stackSize; + if (k1 > 0 && k1 + held.stackSize <= held.getMaxStackSize()) { + return true; + } + } + return false; + } + @Override public void save() { } diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java index 90204fdc4..6ed26666f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java @@ -4,15 +4,10 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityPhase; +import kamkeel.npcs.controllers.data.ability.PreviewEntityHandler; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.entity.EntityAbilityBeam; -import kamkeel.npcs.entity.EntityAbilityDisc; -import kamkeel.npcs.entity.EntityAbilityLaser; -import kamkeel.npcs.entity.EntityAbilityOrb; -import kamkeel.npcs.entity.EntityAbilityProjectile; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -import net.minecraft.world.World; import noppes.npcs.controllers.data.Animation; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.entity.EntityCustomNpc; @@ -25,38 +20,39 @@ import java.util.List; /** * Client-side executor for previewing abilities in the GUI. * - * Lifecycle: - * 1. WINDUP phase - plays windup animation, entities spawn and charge - * 2. ACTIVE phase - plays active animation, entities fire and move - * 3. EXTENDED phase - continues for +100 ticks after animations to see results - * 4. IDLE - preview complete + * Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick) + * with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true. * - * Features: - * - Invisible fake target NPC placed in front of the preview NPC for targeting - * - NPC movement tracking for abilities that move the NPC (e.g. slam) + * Lifecycle: + * 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn + * 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated + * 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating) + * 4. IDLE - preview complete */ @SideOnly(Side.CLIENT) -public class AbilityPreviewExecutor { +public class AbilityPreviewExecutor implements PreviewEntityHandler { // ==================== PREVIEW STATE ==================== private Ability previewAbility; private EntityNPCInterface previewNpc; - private AbilityPhase phase = AbilityPhase.IDLE; + + /** Executor's own phase tracking (separate from ability.getPhase()) */ + private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED } + private ExecutorPhase executorPhase = ExecutorPhase.IDLE; + private int currentTick = 0; private boolean playing = false; private boolean paused = false; // ==================== TIMING ==================== private static final int EXTENDED_DURATION = 100; - private int activeDuration = 40; + private int maxPreviewDuration = 200; // ==================== FAKE TARGET ==================== - /** Invisible fake target NPC for ability targeting (placed 5 blocks in front of preview NPC) */ private EntityNPCInterface fakeTarget; private static final double TARGET_DISTANCE = 5.0; // ==================== NPC START POSITION ==================== - /** Saved NPC position for restoring after movement abilities */ private double npcStartX, npcStartY, npcStartZ; // ==================== PREVIEW CONTENT ==================== @@ -74,7 +70,8 @@ public class AbilityPreviewExecutor { } /** - * Start previewing an ability. + * Start previewing an ability using unified execution. + * Sets previewMode=true on the ability, then calls its real methods. */ public void startPreview(Ability ability, EntityNPCInterface npc) { stop(); @@ -84,31 +81,35 @@ public class AbilityPreviewExecutor { this.currentTick = 0; this.playing = true; this.paused = false; - this.activeDuration = ability.getPreviewActiveDuration(); + this.maxPreviewDuration = ability.getMaxPreviewDuration(); // Save NPC start position for restoring later this.npcStartX = npc.posX; this.npcStartY = npc.posY; this.npcStartZ = npc.posZ; + // Enable preview mode on the ability + ability.setPreviewMode(true); + ability.setPreviewEntityHandler(this); + // Create invisible fake target NPC for targeting createFakeTarget(npc); - // Set preview target on the ability - ability.setPreviewTarget(fakeTarget); - // Start tracking NPC movement if (parentGui != null) { parentGui.startTrackingMovement(); } + // Use the ability's real start() method with the fake target + ability.start(fakeTarget); + if (ability.getWindUpTicks() <= 0) { // No windup — go straight to active - this.phase = AbilityPhase.ACTIVE; + this.executorPhase = ExecutorPhase.ACTIVE; transitionToActive(); } else { // Normal windup flow - this.phase = AbilityPhase.WINDUP; + this.executorPhase = ExecutorPhase.WINDUP; // Create telegraph for preview previewTelegraph = ability.createTelegraph(npc, fakeTarget); @@ -121,24 +122,17 @@ public class AbilityPreviewExecutor { data.setAnimation(windUpAnim); data.animation.paused = false; } - - // Spawn preview entity on first tick if ability spawns during windup - if (ability.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); - } } } /** * Create an invisible fake target NPC placed in front of the preview NPC. - * This entity is NOT rendered - it only exists for ability targeting logic. */ private void createFakeTarget(EntityNPCInterface npc) { if (npc.worldObj == null) return; try { fakeTarget = new EntityCustomNpc(npc.worldObj); - // Position target in front of NPC based on its facing direction float facingYaw = GuiAbilityInterface.NPC_FACING_YAW; double yawRad = Math.toRadians(facingYaw); double targetX = npc.posX - Math.sin(yawRad) * TARGET_DISTANCE; @@ -153,15 +147,12 @@ public class AbilityPreviewExecutor { } } - /** - * Get the fake target entity for abilities that need a target. - */ public EntityLivingBase getFakeTarget() { return fakeTarget; } public void play() { - if (previewAbility == null || phase == AbilityPhase.IDLE) { + if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) { return; } playing = true; @@ -178,6 +169,9 @@ public class AbilityPreviewExecutor { public void pause() { paused = true; + // Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter + syncPrevPositions(); + if (previewNpc != null) { AnimationData data = previewNpc.display.animationData; if (data.animation != null) { @@ -186,10 +180,37 @@ public class AbilityPreviewExecutor { } } + /** + * Sync prevPos to pos for the NPC and all preview entities. + * Prevents rendering interpolation jitter when standing still or paused. + */ + private void syncPrevPositions() { + if (previewNpc != null) { + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + } + for (Entity entity : previewEntities) { + if (entity != null && !entity.isDead) { + entity.prevPosX = entity.posX; + entity.prevPosY = entity.posY; + entity.prevPosZ = entity.posZ; + } + } + } + public void stop() { + // Clean up the ability + if (previewAbility != null) { + previewAbility.cleanup(); + previewAbility.setPreviewMode(false); + previewAbility.setPreviewEntityHandler(null); + previewAbility.reset(); + } + playing = false; paused = false; - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.IDLE; currentTick = 0; previewTelegraph = null; @@ -211,9 +232,11 @@ public class AbilityPreviewExecutor { previewNpc.prevPosX = npcStartX; previewNpc.prevPosY = npcStartY; previewNpc.prevPosZ = npcStartZ; + previewNpc.motionX = 0; + previewNpc.motionY = 0; + previewNpc.motionZ = 0; } - // Remove fake target fakeTarget = null; if (previewNpc != null) { @@ -224,13 +247,24 @@ public class AbilityPreviewExecutor { } /** - * Tick the preview forward. + * Tick the preview forward. Calls real ability methods. */ public void tick() { - if (!playing || paused || previewAbility == null || previewNpc == null) { + if (!playing || previewAbility == null || previewNpc == null) { return; } + if (paused) { + // Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused + syncPrevPositions(); + return; + } + + // Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + currentTick++; if (previewTelegraph != null) { @@ -239,14 +273,14 @@ public class AbilityPreviewExecutor { tickEntities(); - switch (phase) { + switch (executorPhase) { case WINDUP: tickWindup(); break; case ACTIVE: tickActive(); break; - case IDLE: + case EXTENDED: tickExtended(); break; default: @@ -255,7 +289,8 @@ public class AbilityPreviewExecutor { } private void tickWindup() { - previewAbility.onPreviewWindUpTick(previewNpc, currentTick); + // Call the REAL windup tick method + previewAbility.onWindUpTick(previewNpc, fakeTarget, currentTick); if (currentTick >= previewAbility.getWindUpTicks()) { transitionToActive(); @@ -263,35 +298,41 @@ public class AbilityPreviewExecutor { } private void tickActive() { - previewAbility.onPreviewActiveTick(previewNpc, currentTick); + // Call the REAL active tick method + previewAbility.onActiveTick(previewNpc, fakeTarget, currentTick); - if (currentTick == 1 && !previewAbility.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); - fireEntities(); + // Simulate physics for movement abilities + simulatePhysics(); + + // Check if the ability signaled completion (phase went to IDLE) + if (previewAbility.getPhase() == AbilityPhase.IDLE) { + transitionToExtended(); + return; } - if (currentTick >= activeDuration) { + // Safety timeout + if (currentTick >= maxPreviewDuration) { transitionToExtended(); } } private void tickExtended() { + // Continue ticking entities so they can finish their animations if (currentTick >= EXTENDED_DURATION) { playing = false; } } private void transitionToActive() { - phase = AbilityPhase.ACTIVE; + executorPhase = ExecutorPhase.ACTIVE; currentTick = 0; previewTelegraph = null; - // Notify ability of execution (for movement abilities like Slam/Charge/Dash) - previewAbility.onPreviewExecute(previewNpc); - - fireEntities(); + // Call the REAL onExecute method (fires entities, initiates movement, etc.) + previewAbility.onExecute(previewNpc, fakeTarget); + // Start active animation Animation activeAnim = previewAbility.getActiveAnimation(); if (activeAnim != null && previewNpc != null) { AnimationData data = previewNpc.display.animationData; @@ -301,7 +342,7 @@ public class AbilityPreviewExecutor { } private void transitionToExtended() { - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.EXTENDED; currentTick = 0; if (previewNpc != null) { @@ -310,26 +351,40 @@ public class AbilityPreviewExecutor { } } - private void spawnPreviewEntity() { - Entity entity = previewAbility.createPreviewEntity(previewNpc); - if (entity != null) { - previewEntities.add(entity); - if (parentGui != null) { - parentGui.addPreviewEntity(entity); - } - } - } + /** + * Simulate basic physics for movement abilities (Slam, Charge, Dash). + * Applies gravity, drag, and ground clamping to NPC position. + */ + private void simulatePhysics() { + if (!previewAbility.hasAbilityMovement()) return; + if (previewNpc == null) return; - private void fireEntities() { - for (Entity entity : previewEntities) { - if (entity instanceof EntityAbilityOrb) { - ((EntityAbilityOrb) entity).startPreviewFiring(); - } else if (entity instanceof EntityAbilityBeam) { - ((EntityAbilityBeam) entity).startPreviewFiring(); - } else if (entity instanceof EntityAbilityDisc) { - ((EntityAbilityDisc) entity).startPreviewFiring(); - } + // Save previous position for interpolation + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + + // Apply velocity + previewNpc.posX += previewNpc.motionX; + previewNpc.posY += previewNpc.motionY; + previewNpc.posZ += previewNpc.motionZ; + + // Apply gravity + previewNpc.motionY -= 0.08; + previewNpc.motionY *= 0.98; + + // Apply horizontal drag + previewNpc.motionX *= 0.91; + previewNpc.motionZ *= 0.91; + + // Ground clamp: if below start position and falling, stop + if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) { + previewNpc.posY = npcStartY; + previewNpc.motionY = 0; + previewNpc.onGround = true; } + + previewNpc.fallDistance = 0; } private void tickEntities() { @@ -347,12 +402,38 @@ public class AbilityPreviewExecutor { } } + // ==================== PreviewEntityHandler ==================== + + @Override + public void onEntitySpawned(Entity entity) { + if (entity == null) return; + previewEntities.add(entity); + if (parentGui != null) { + parentGui.addPreviewEntity(entity); + } + } + + @Override + public void onEntityRemoved(Entity entity) { + if (entity == null) return; + previewEntities.remove(entity); + if (parentGui != null) { + parentGui.removePreviewEntity(entity); + } + } + // ==================== GETTERS ==================== public boolean isPlaying() { return playing; } public boolean isPaused() { return paused; } public boolean isActive() { return playing || paused; } - public AbilityPhase getPhase() { return phase; } + public AbilityPhase getPhase() { + switch (executorPhase) { + case WINDUP: return AbilityPhase.WINDUP; + case ACTIVE: return AbilityPhase.ACTIVE; + default: return AbilityPhase.IDLE; + } + } public int getCurrentTick() { return currentTick; } public TelegraphInstance getTelegraph() { return previewTelegraph; } public List getPreviewEntities() { return previewEntities; } @@ -364,11 +445,11 @@ public class AbilityPreviewExecutor { return "Stopped"; } else if (paused) { return "Paused"; - } else if (phase == AbilityPhase.WINDUP) { + } else if (executorPhase == ExecutorPhase.WINDUP) { return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); - } else if (phase == AbilityPhase.ACTIVE) { - return "Active: " + currentTick + "/" + activeDuration; - } else if (phase == AbilityPhase.IDLE && playing) { + } else if (executorPhase == ExecutorPhase.ACTIVE) { + return "Active: " + currentTick + "/" + maxPreviewDuration; + } else if (executorPhase == ExecutorPhase.EXTENDED) { return "Extended: " + currentTick + "/" + EXTENDED_DURATION; } return ""; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java index 31a093b8d..3d0573bf2 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java @@ -11,10 +11,7 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import noppes.npcs.client.ClientEventHandler; -import noppes.npcs.client.EntityUtil; -import noppes.npcs.entity.EntityCustomNpc; import noppes.npcs.entity.EntityNPCInterface; -import noppes.npcs.entity.data.ModelData; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; @@ -50,7 +47,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { private GuiNpcButton btnLeft, btnRight; // ==================== NPC STATE ==================== - public ModelData playerdata; public EntityNPCInterface npc; /** NPC starting position (saved when preview starts, used to track movement) */ @@ -85,7 +81,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) { super(hasMenuNpc ? npc : null); this.npc = npc; - this.playerdata = ((EntityCustomNpc) npc).modelData; this.drawDefaultBackground = false; CAMERA_ZOOM = 30f; @@ -135,20 +130,17 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { * Draw the 3D preview with NPC and entities. */ protected void drawPreview(int mouseX, int mouseY, float partialTicks) { + if (hasSubGui()) + return; + GL11.glColor4f(1, 1, 1, 1); // Enable scissor to clip rendering to preview area GL11.glEnable(GL11.GL_SCISSOR_TEST); setScissorClip(previewX, previewY, previewWidth, previewHeight); - // Get the entity to render (could be transformed player model) - EntityLivingBase renderEntity = playerdata.getEntity(npc); - if (renderEntity == null) { - renderEntity = this.npc; - } - - // Sync NPC properties to render entity - EntityUtil.Copy(npc, renderEntity); + // Always use the standard NPC animation renderer for ability preview + EntityLivingBase renderEntity = this.npc; // Set NPC facing direction (affects anchor points and visual facing) npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; @@ -204,11 +196,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { ClientEventHandler.renderingEntityInGUI = true; // Render the NPC at its position delta (for movement like slam jumps) - try { - RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); - } catch (Exception e) { - playerdata.setEntityClass(null); - } + RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); // Render preview entities at their positions relative to NPC start position renderPreviewEntities(partialTicks); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java index e726239b1..f9b3df568 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java @@ -200,7 +200,8 @@ public class GuiCustomScroll extends GuiScreen { int k = (14 * i + 4) - scrollY; if (k >= 4 && k + 12 < ySize) { int xOffset = scrollHeight < ySize - 8 ? 0 : 10; - String displayString = StatCollector.translateToLocal(list.get(i)); + String rawEntry = list.get(i); + String displayString = StatCollector.translateToLocal(rawEntry); String text = ""; float maxWidth = (xSize + xOffset - 8) * 0.8f; @@ -215,7 +216,13 @@ public class GuiCustomScroll extends GuiScreen { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + + // Entries with a custom color are non-interactive (headers/separators) + Integer customColor = colors.get(rawEntry); + if (customColor != null) { + if (!text.isEmpty()) + fontRendererObj.drawString(text, j, k, customColor); + } else if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff); drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff); @@ -239,13 +246,17 @@ public class GuiCustomScroll extends GuiScreen { private int getMouseOver(int i, int j) { i -= guiLeft; j -= guiTop; - //fontRenderer.drawString(".", i , j, 0xffffff); if (i >= 4 && i < xSize - 4 && j >= 4 && j < ySize) { for (int j1 = 0; j1 < list.size(); j1++) { if (!mouseInOption(i, j, j1)) { continue; } + // Skip non-interactive entries (colored headers/separators) + if (colors.containsKey(list.get(j1))) { + continue; + } + return j1; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java index b5847d0a0..658cfc022 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -180,7 +180,7 @@ public abstract class GuiNPCInterface extends GuiScreen { return; } } - + for (GuiNpcTextField tf : new ArrayList(textfields.values())) if (tf.enabled) tf.mouseClicked(i, j, k); @@ -415,7 +415,7 @@ public abstract class GuiNPCInterface extends GuiScreen { if (tf.hasHoverText()) tf.drawHover(i, j, subGui); } - + for (GuiScreen gui : extra.values()) gui.drawScreen(i, j, f); @@ -439,8 +439,7 @@ public abstract class GuiNPCInterface extends GuiScreen { int bottomHeight = 0; int bottomTextureV = 0; if (ySize < bgTextureHeight) { - // Keep bottom border from texture bottom (last 6 pixels of actual content) - bottomHeight = 6; + bottomHeight = -1; topHeight = ySize - bottomHeight; bottomTextureV = bgTextureHeight - bottomHeight; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java index 436b47bb5..a30b53fa8 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcTextField.java @@ -22,8 +22,8 @@ public class GuiNpcTextField extends GuiTextField { private ITextfieldListener listener; public int id; public int min = 0, max = Integer.MAX_VALUE, def = 0; - public double minDouble = 0, maxDouble = Double.MAX_VALUE, defDouble = 0; - public float minFloat = 0, maxFloat = Float.MAX_VALUE, defFloat = 0; + public double minDouble = Double.NEGATIVE_INFINITY, maxDouble = Double.POSITIVE_INFINITY, defDouble = 0; + public float minFloat = Float.NEGATIVE_INFINITY, maxFloat = Float.POSITIVE_INFINITY, defFloat = 0; protected static GuiNpcTextField activeTextfield = null; public boolean canEdit = true; public String hoverableText = ""; diff --git a/src/main/java/noppes/npcs/client/renderer/ImageData.java b/src/main/java/noppes/npcs/client/renderer/ImageData.java index 15c383e40..8e6f651c5 100644 --- a/src/main/java/noppes/npcs/client/renderer/ImageData.java +++ b/src/main/java/noppes/npcs/client/renderer/ImageData.java @@ -25,7 +25,7 @@ public class ImageData { public ImageData(String directory) { this.location = new ResourceLocation(directory); - if (directory.startsWith("https://")) { + if (directory.startsWith("https://") || directory.startsWith("http://")) { this.isUrl = true; TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); this.imageDownloadAlt = new ImageDownloadAlt(null, directory, new ResourceLocation("customnpcs:textures/gui/invisible.png"), new ImageBufferDownloadAlt(true, false)); diff --git a/src/main/java/noppes/npcs/constants/EnumPotionType.java b/src/main/java/noppes/npcs/constants/EnumPotionType.java index f6d5ad111..4cf6bc8f8 100644 --- a/src/main/java/noppes/npcs/constants/EnumPotionType.java +++ b/src/main/java/noppes/npcs/constants/EnumPotionType.java @@ -1,5 +1,83 @@ package noppes.npcs.constants; +import net.minecraft.potion.Potion; + public enum EnumPotionType { - None, Fire, Poison, Hunger, Weakness, Slowness, Nausea, Blindness, Wither; + None("gui.none", -1), + Fire("tile.fire.name", -1), + Poison("potion.poison", Potion.poison.id), + Hunger("potion.hunger", Potion.hunger.id), + Weakness("potion.weakness", Potion.weakness.id), + Slowness("potion.moveSlowdown", Potion.moveSlowdown.id), + Nausea("potion.confusion", Potion.confusion.id), + Blindness("potion.blindness", Potion.blindness.id), + Wither("potion.wither", Potion.wither.id), + MiningFatigue("potion.digSlowDown", Potion.digSlowdown.id), + Manual("effect.manual", -1); + + private final String langKey; + private final int potionId; + + EnumPotionType(String langKey, int potionId) { + this.langKey = langKey; + this.potionId = potionId; + } + + public String getLangKey() { + return langKey; + } + + public int getPotionId() { + return potionId; + } + + /** + * Returns the actual potion ID to apply. + * For Manual type, returns the provided manualId. + * For all others, returns the mapped potionId. + */ + public int getResolvedPotionId(int manualId) { + if (this == Manual) return manualId; + return potionId; + } + + public static String[] getLangKeys() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length]; + for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; + return keys; + } + + /** + * Returns lang keys excluding None. For use in effect lists where None is not a valid choice. + */ + public static String[] getLangKeysNoNone() { + EnumPotionType[] types = values(); + String[] keys = new String[types.length - 1]; + for (int i = 1; i < types.length; i++) keys[i - 1] = types[i].langKey; + return keys; + } + + /** + * Maps a 0-based index (excluding None) back to the corresponding EnumPotionType. + * Index 0 = Fire, 1 = Poison, etc. + */ + public static EnumPotionType fromIndexNoNone(int index) { + return fromOrdinal(index + 1); + } + + public static EnumPotionType fromOrdinal(int ordinal) { + EnumPotionType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return None; + } + + /** + * Checks if the given potion ID is valid and registered in the Minecraft potion registry. + */ + public static boolean isValidPotionId(int id) { + return id >= 0 && id < Potion.potionTypes.length && Potion.potionTypes[id] != null; + } } diff --git a/src/main/java/noppes/npcs/constants/EnumScriptType.java b/src/main/java/noppes/npcs/constants/EnumScriptType.java index 99a8b4091..da4e8f136 100644 --- a/src/main/java/noppes/npcs/constants/EnumScriptType.java +++ b/src/main/java/noppes/npcs/constants/EnumScriptType.java @@ -125,7 +125,13 @@ public enum EnumScriptType { ABILITY_INTERRUPT("abilityInterrupt"), ABILITY_COMPLETE("abilityComplete"), ABILITY_HIT("abilityHit"), - ABILITY_TICK("abilityTick"); + ABILITY_TICK("abilityTick"), + + ENERGY_PROJECTILE_FIRED("energyProjectileFired"), + ENERGY_PROJECTILE_TICK("energyProjectileTick"), + ENERGY_PROJECTILE_ENTITY_IMPACT("energyProjectileEntityImpact"), + ENERGY_PROJECTILE_BLOCK_IMPACT("energyProjectileBlockImpact"), + ENERGY_PROJECTILE_EXPIRED("energyProjectileExpired"); public String function; diff --git a/src/main/java/noppes/npcs/constants/EnumScrollData.java b/src/main/java/noppes/npcs/constants/EnumScrollData.java index 06d5a6ec3..cbec6ad34 100644 --- a/src/main/java/noppes/npcs/constants/EnumScrollData.java +++ b/src/main/java/noppes/npcs/constants/EnumScrollData.java @@ -8,6 +8,7 @@ public enum EnumScrollData { QUEST_GROUP, ABILITY_TYPES, CUSTOM_ABILITIES, + BUILTIN_ABILITIES, ANIMATIONS, BUILTIN_ANIMATIONS } diff --git a/src/main/java/noppes/npcs/constants/ScriptContext.java b/src/main/java/noppes/npcs/constants/ScriptContext.java index dcc5b5d95..c5861927a 100644 --- a/src/main/java/noppes/npcs/constants/ScriptContext.java +++ b/src/main/java/noppes/npcs/constants/ScriptContext.java @@ -1,14 +1,17 @@ package noppes.npcs.constants; +import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.api.event.IAnimationEvent; import noppes.npcs.api.event.IBlockEvent; import noppes.npcs.api.event.ICustomGuiEvent; import noppes.npcs.api.event.IDialogEvent; +import noppes.npcs.api.event.IEnergyProjectileEvent; import noppes.npcs.api.event.IFactionEvent; import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; import noppes.npcs.api.event.INpcEvent; import noppes.npcs.api.event.IPartyEvent; +import noppes.npcs.api.event.IPlayerAbilityEvent; import noppes.npcs.api.event.IPlayerEvent; import noppes.npcs.api.event.IProjectileEvent; import noppes.npcs.api.event.IQuestEvent; @@ -52,7 +55,10 @@ public class ScriptContext { public static final ScriptContext NPC = register("NPC", "npc", INpcEvent.class, - IProjectileEvent.class + IProjectileEvent.class, + IEnergyProjectileEvent.class, + IAbilityEvent.class, + IAnimationEvent.class ); public static final ScriptContext PLAYER = register("PLAYER", "player", @@ -62,7 +68,9 @@ public class ScriptContext { IDialogEvent.class, IQuestEvent.class, IFactionEvent.class, - ICustomGuiEvent.class + ICustomGuiEvent.class, + IEnergyProjectileEvent.class, + IPlayerAbilityEvent.class ); public static final ScriptContext BLOCK = register("BLOCK", "block", diff --git a/src/main/java/noppes/npcs/controllers/ScriptHookController.java b/src/main/java/noppes/npcs/controllers/ScriptHookController.java index f3bad8e9d..88a12e20d 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptHookController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptHookController.java @@ -2,10 +2,12 @@ package noppes.npcs.controllers; import noppes.npcs.api.event.IAbilityEvent; import noppes.npcs.api.event.IAnimationEvent; +import noppes.npcs.api.event.IPlayerAbilityEvent; import noppes.npcs.api.event.IBlockEvent; import noppes.npcs.api.event.ICustomGuiEvent; import noppes.npcs.api.event.ICustomNPCsEvent; import noppes.npcs.api.event.IDialogEvent; +import noppes.npcs.api.event.IEnergyProjectileEvent; import noppes.npcs.api.event.IFactionEvent; import noppes.npcs.api.event.IForgeEvent; import noppes.npcs.api.event.IItemEvent; @@ -106,6 +108,13 @@ public class ScriptHookController implements IScriptHookHandler { hook(NPC, PROJECTILE_TICK, IProjectileEvent.UpdateEvent.class); hook(NPC, PROJECTILE_IMPACT, IProjectileEvent.ImpactEvent.class); + // Energy Projectile + hook(NPC, ENERGY_PROJECTILE_FIRED, IEnergyProjectileEvent.FiredEvent.class); + hook(NPC, ENERGY_PROJECTILE_TICK, IEnergyProjectileEvent.UpdateEvent.class); + hook(NPC, ENERGY_PROJECTILE_ENTITY_IMPACT, IEnergyProjectileEvent.EntityImpactEvent.class); + hook(NPC, ENERGY_PROJECTILE_BLOCK_IMPACT, IEnergyProjectileEvent.BlockImpactEvent.class); + hook(NPC, ENERGY_PROJECTILE_EXPIRED, IEnergyProjectileEvent.ExpiredEvent.class); + // Ability hook(NPC, ABILITY_START, IAbilityEvent.StartEvent.class); hook(NPC, ABILITY_EXECUTE, IAbilityEvent.ExecuteEvent.class); @@ -113,6 +122,12 @@ public class ScriptHookController implements IScriptHookHandler { hook(NPC, ABILITY_TICK, IAbilityEvent.TickEvent.class); hook(NPC, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class); hook(NPC, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class); + + // Animation + hook(NPC, ANIMATION_START, IAnimationEvent.Started.class); + hook(NPC, ANIMATION_END, IAnimationEvent.Ended.class); + hook(NPC, ANIMATION_FRAME_ENTER, IAnimationEvent.IFrameEvent.Entered.class); + hook(NPC, ANIMATION_FRAME_EXIT, IAnimationEvent.IFrameEvent.Exited.class); } private void initializePlayerHooks() { @@ -208,6 +223,21 @@ public class ScriptHookController implements IScriptHookHandler { hook(PLAYER, ANIMATION_FRAME_ENTER, IAnimationEvent.IFrameEvent.Entered.class); hook(PLAYER, ANIMATION_FRAME_EXIT, IAnimationEvent.IFrameEvent.Exited.class); + // Energy Projectile + hook(PLAYER, ENERGY_PROJECTILE_FIRED, IEnergyProjectileEvent.FiredEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_TICK, IEnergyProjectileEvent.UpdateEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_ENTITY_IMPACT, IEnergyProjectileEvent.EntityImpactEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_BLOCK_IMPACT, IEnergyProjectileEvent.BlockImpactEvent.class); + hook(PLAYER, ENERGY_PROJECTILE_EXPIRED, IEnergyProjectileEvent.ExpiredEvent.class); + + // Ability + hook(PLAYER, ABILITY_START, IPlayerAbilityEvent.StartEvent.class); + hook(PLAYER, ABILITY_EXECUTE, IPlayerAbilityEvent.ExecuteEvent.class); + hook(PLAYER, ABILITY_HIT, IPlayerAbilityEvent.HitEvent.class); + hook(PLAYER, ABILITY_TICK, IPlayerAbilityEvent.TickEvent.class); + hook(PLAYER, ABILITY_INTERRUPT, IPlayerAbilityEvent.InterruptEvent.class); + hook(PLAYER, ABILITY_COMPLETE, IPlayerAbilityEvent.CompleteEvent.class); + // Profile hook(PLAYER, PROFILE_CHANGE, IPlayerEvent.ProfileEvent.Changed.class); hook(PLAYER, PROFILE_REMOVE, IPlayerEvent.ProfileEvent.Removed.class); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 6d265de27..60386b8bf 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -4,6 +4,7 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilityPhase; import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket; import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket; @@ -14,13 +15,21 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.DamageSource; +import noppes.npcs.LogWriter; +import noppes.npcs.EventHooks; import noppes.npcs.api.ability.IPlayerAbilityData; +import noppes.npcs.api.entity.IPlayer; import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.ScriptController; import noppes.npcs.controllers.data.Animation; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.event.player.PlayerAbilityEvent; +import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket; import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; /** @@ -52,6 +61,13 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private int selectedIndex = 0; + /** + * Tracks whether the current animation was started by an ability. + * Persisted to NBT so orphaned ability animations can be detected and + * cleared on login (ability state is transient, but animation state is not). + */ + private boolean playingAbilityAnimation = false; + // ═══════════════════════════════════════════════════════════════════ // RUNTIME STATE (not saved) // ═══════════════════════════════════════════════════════════════════ @@ -76,6 +92,26 @@ public class PlayerAbilityData implements IPlayerAbilityData { */ private transient EntityLivingBase currentTarget; + /** + * Rotation lock state - freezes player yaw/pitch during ability phases. + */ + private transient boolean rotationLocked = false; + private transient float lockedYaw = 0; + private transient float lockedPitch = 0; + + /** + * Position lock state - freezes player position during ability phases. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + + /** + * Last synced state flags byte for change detection (avoids spamming packets). + */ + private transient byte lastSyncedFlags = 0; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -99,6 +135,20 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(player); + + // Apply rotation and position locks after ability tick + applyRotationControl(player); + applyPositionLock(player); + + // Sync lock state to client (only sends when flags change) + syncAbilityStateIfNeeded(player); + } else { + // Safety: release orphaned locks if no ability is executing + if (rotationLocked || positionLocked) { + releaseRotationControl(); + releaseLockedPosition(); + syncAbilityStateClear(player); + } } } @@ -111,38 +161,105 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Tick advances time and possibly changes phase boolean phaseChanged = currentAbility.tick(); + // Fire tick event for scripts + firePlayerTickEvent(player, currentAbility, currentTarget); + + // Fire extender tick hook (e.g., per-tick resource drain) + if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, player, currentTarget, + currentAbility.getPhase(), currentAbility.getCurrentTick())) { + interruptCurrentAbility(); + return; + } + switch (currentAbility.getPhase()) { case WINDUP: - currentAbility.onWindUpTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(player); + } + spawnTelegraph(currentAbility, player, null); + playAbilitySound(player, currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } + currentAbility.onWindUpTick(player, currentTarget, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { - // Just entered ACTIVE phase - TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); - if (telegraph != null) { + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { + // Just entered ACTIVE phase - lock all telegraph positions + for (TelegraphInstance telegraph : currentAbility.getTelegraphInstances()) { telegraph.lockPosition(); } - removeTelegraph(currentAbility, player); + // Remove telegraph unless the ability keeps it during active phase + if (!currentAbility.keepTelegraphDuringActive()) { + removeTelegraph(currentAbility, player); + } + + // Handle rotation control transition from WINDUP to ACTIVE + if (currentAbility.isRotationLockedDuringActive()) { + if (!rotationLocked) { + captureLockedRotation(player); + } + } else if (rotationLocked) { + releaseRotationControl(); + } + + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(player); + } + } else if (positionLocked) { + releaseLockedPosition(); + } // Play active sound and animation playAbilitySound(player, currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); + // Fire execute event (cancelable) + if (firePlayerExecuteEvent(player, currentAbility, currentTarget)) { + return; // Cancelled + } + // Call onExecute - currentAbility.onExecute(player, currentTarget, player.worldObj); + currentAbility.onExecute(player, currentTarget); if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(player); return; } } - currentAbility.onActiveTick(player, currentTarget, player.worldObj, currentAbility.getCurrentTick()); + currentAbility.onActiveTick(player, currentTarget, currentAbility.getCurrentTick()); if (currentAbility.getPhase() == AbilityPhase.IDLE) { handleAbilityCompletion(player); return; } + + // Auto-complete for burst overlap mode (entities fly independently) + if (currentAbility.isBurstEnabled() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + + // Release locks during burst delay + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: @@ -161,8 +278,18 @@ public class PlayerAbilityData implements IPlayerAbilityData { private void handleAbilityCompletion(EntityPlayer player) { if (currentAbility == null) return; + // Fire extender complete hook + AbilityController.Instance.fireOnAbilityComplete(currentAbility, player, currentTarget, false); + currentAbility.onComplete(player, currentTarget); + // Fire complete event + firePlayerCompleteEvent(player, currentAbility, currentTarget); + + // Release all locks + releaseRotationControl(); + releaseLockedPosition(); + // Apply universal cooldown (using base cooldownTicks only, not min/max random) if (!currentAbility.isIgnoreCooldown()) { cooldownEndTime = player.worldObj.getTotalWorldTime() + currentAbility.getCooldownTicks(); @@ -174,6 +301,9 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentAbility = null; currentAbilityKey = null; currentTarget = null; + + // Send cleared state to client + syncAbilityStateClear(player); } // ═══════════════════════════════════════════════════════════════════ @@ -223,6 +353,16 @@ public class PlayerAbilityData implements IPlayerAbilityData { // Check conditions (skip target-requiring ones) if (!ability.checkConditionsForPlayer(player)) return false; + // Fire extender start hook (e.g., resource cost checks) + if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) { + return false; + } + + // Fire start event (cancelable) + if (firePlayerStartEvent(player, ability)) { + return false; // Cancelled + } + // Start the ability currentAbility = ability; currentAbilityKey = key; @@ -231,9 +371,21 @@ public class PlayerAbilityData implements IPlayerAbilityData { if (ability.getPhase() == AbilityPhase.ACTIVE) { // Windup was 0 — skip telegraph/windup and go straight to active + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } executeImmediate(ability, player); } else { // Normal windup flow + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(player); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(player); + } spawnTelegraph(ability, player, null); playAbilitySound(player, ability.getWindUpSound()); playAbilityAnimation(ability.getWindUpAnimation()); @@ -251,8 +403,13 @@ public class PlayerAbilityData implements IPlayerAbilityData { playAbilitySound(player, ability.getActiveSound()); playAbilityAnimation(ability.getActiveAnimation()); + // Fire execute event (cancelable) + if (firePlayerExecuteEvent(player, ability, currentTarget)) { + return; // Cancelled + } + // Call onExecute - ability.onExecute(player, currentTarget, player.worldObj); + ability.onExecute(player, currentTarget); // Check if ability completed during onExecute if (ability.getPhase() == AbilityPhase.IDLE) { @@ -409,15 +566,75 @@ public class PlayerAbilityData implements IPlayerAbilityData { } public void interruptCurrentAbility() { + interruptCurrentAbility(null, 0); + } + + public void interruptCurrentAbility(DamageSource source, float damage) { if (currentAbility != null && currentAbility.isExecuting()) { + // Fire extender complete hook (interrupted) + AbilityController.Instance.fireOnAbilityComplete(currentAbility, playerData.player, currentTarget, true); + + // Fire interrupt event + firePlayerInterruptEvent(playerData.player, currentAbility, currentTarget, source, damage); + currentAbility.interrupt(); stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); currentAbility = null; currentAbilityKey = null; currentTarget = null; + syncAbilityStateClear(playerData.player); } } + /** + * Handle damage taken while an ability is executing. + * Called from LivingHurtEvent BEFORE damage is applied to health. + * Triggers Guard counter detection and handles ability interruption. + * + * @param source The damage source + * @param amount The damage amount (post-armor) + * @return The modified damage amount (reduced by guard, or 0 if counter absorbs) + */ + public float onDamage(DamageSource source, float amount) { + if (currentAbility == null || !currentAbility.isExecuting()) { + return amount; + } + + net.minecraft.entity.Entity sourceEntity = source.getEntity(); + EntityLivingBase attacker = sourceEntity instanceof EntityLivingBase ? (EntityLivingBase) sourceEntity : null; + + // Track counter state before calling onDamageTaken + boolean wasCounterTriggered = false; + if (currentAbility instanceof AbilityGuard) { + wasCounterTriggered = ((AbilityGuard) currentAbility).isCounterTriggered(); + } + + currentAbility.onDamageTaken(playerData.player, attacker, source, amount); + + // Guard: handle damage reduction and counter absorption + if (currentAbility instanceof AbilityGuard) { + AbilityGuard guard = (AbilityGuard) currentAbility; + if (guard.isGuarding()) { + // Counter just triggered — absorb full damage + if (!wasCounterTriggered && guard.isCounterTriggered()) { + return 0; + } + // Normal guard — apply flat damage reduction + float reduction = guard.getDamageReductionFactor(); + return Math.max(0, amount - reduction); + } + } + + // Check for ability interruption + if (currentAbility != null && currentAbility.canInterrupt(source)) { + interruptCurrentAbility(source, amount); + } + + return amount; + } + @Override public boolean isOnCooldown() { EntityPlayer player = playerData.player; @@ -446,28 +663,154 @@ public class PlayerAbilityData implements IPlayerAbilityData { && currentAbility.isMovementLockedForCurrentPhase(); } + // ═══════════════════════════════════════════════════════════════════ + // ROTATION CONTROL + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current rotation values to lock player's look direction. + */ + private void captureLockedRotation(EntityPlayer player) { + lockedYaw = player.rotationYaw; + lockedPitch = player.rotationPitch; + rotationLocked = true; + } + + /** + * Release rotation lock. + */ + private void releaseRotationControl() { + rotationLocked = false; + } + + /** + * Apply rotation control on the server side. + * Enforces locked rotation values on the player entity. + */ + private void applyRotationControl(EntityPlayer player) { + if (!rotationLocked || currentAbility == null) return; + + if (currentAbility.isRotationLockedForCurrentPhase()) { + player.rotationYaw = lockedYaw; + player.rotationPitch = lockedPitch; + player.prevRotationYaw = lockedYaw; + player.prevRotationPitch = lockedPitch; + if (player instanceof EntityPlayerMP) { + player.rotationYawHead = lockedYaw; + } + } + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Capture current position to lock player in place. + */ + private void captureLockedPosition(EntityPlayer player) { + lockedPosX = player.posX; + lockedPosY = player.posY; + lockedPosZ = player.posZ; + positionLocked = true; + } + + /** + * Release position lock. + */ + private void releaseLockedPosition() { + positionLocked = false; + } + + /** + * Apply position lock on the server side. + * Snaps player back to locked position and zeroes motion. + */ + private void applyPositionLock(EntityPlayer player) { + if (!positionLocked) return; + + player.setPosition(lockedPosX, lockedPosY, lockedPosZ); + player.prevPosX = lockedPosX; + player.prevPosY = lockedPosY; + player.prevPosZ = lockedPosZ; + player.motionX = 0; + player.motionY = 0; // Full vertical freeze for position lock + player.motionZ = 0; + } + + // ═══════════════════════════════════════════════════════════════════ + // ABILITY STATE SYNC + // ═══════════════════════════════════════════════════════════════════ + + /** + * Build the current ability state flags byte. + */ + private byte getAbilityStateFlags() { + byte flags = 0; + if (currentAbility == null || !currentAbility.isExecuting()) return flags; + + if (currentAbility.isMovementLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_MOVEMENT_LOCKED; + } + if (rotationLocked && currentAbility.isRotationLockedForCurrentPhase()) { + flags |= PlayerAbilityStatePacket.FLAG_ROTATION_LOCKED; + } + if (currentAbility.hasAbilityMovement() && currentAbility.getPhase() == AbilityPhase.ACTIVE) { + flags |= PlayerAbilityStatePacket.FLAG_HAS_ABILITY_MOVEMENT; + } + if (positionLocked) { + flags |= PlayerAbilityStatePacket.FLAG_POSITION_LOCKED; + } + return flags; + } + + /** + * Send ability state to client if flags changed since last sync. + */ + private void syncAbilityStateIfNeeded(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + byte flags = getAbilityStateFlags(); + if (flags != lastSyncedFlags) { + lastSyncedFlags = flags; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, flags, lockedYaw, lockedPitch); + } + } + + /** + * Send cleared (all-zero) state to client. Called on ability completion/interrupt. + */ + private void syncAbilityStateClear(EntityPlayer player) { + if (!(player instanceof EntityPlayerMP)) return; + if (lastSyncedFlags != 0) { + lastSyncedFlags = 0; + PlayerAbilityStatePacket.sendToPlayer((EntityPlayerMP) player, (byte) 0, 0, 0); + } + } + // ═══════════════════════════════════════════════════════════════════ // TELEGRAPH // ═══════════════════════════════════════════════════════════════════ private void spawnTelegraph(Ability ability, EntityPlayer player, EntityLivingBase target) { - TelegraphInstance telegraph = ability.createTelegraph(player, target); - if (telegraph != null) { - ability.setTelegraphInstance(telegraph); + List telegraphs = ability.createTelegraphs(player, target); + if (!telegraphs.isEmpty()) { + ability.setTelegraphInstances(telegraphs); if (player instanceof EntityPlayerMP) { - TelegraphSpawnPacket.sendToTracking(telegraph, player); + for (TelegraphInstance telegraph : telegraphs) { + TelegraphSpawnPacket.sendToTracking(telegraph, player); + } } } } private void removeTelegraph(Ability ability, EntityPlayer player) { - TelegraphInstance telegraph = ability.getTelegraphInstance(); - if (telegraph != null) { + List telegraphs = ability.getTelegraphInstances(); + for (TelegraphInstance telegraph : telegraphs) { if (player instanceof EntityPlayerMP) { TelegraphRemovePacket.sendToTracking(telegraph.getInstanceId(), player); } - ability.setTelegraphInstance(null); } + ability.setTelegraphInstances(null); } // ═══════════════════════════════════════════════════════════════════ @@ -479,6 +822,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { playerData.animationData.setEnabled(true); playerData.animationData.setAnimation(animation); playerData.animationData.updateClient(); + playingAbilityAnimation = true; } public void playAbilityAnimation(int animation) { @@ -500,6 +844,23 @@ public class PlayerAbilityData implements IPlayerAbilityData { private void stopAbilityAnimation() { playerData.animationData.setAnimation(null); playerData.animationData.updateClient(); + playingAbilityAnimation = false; + } + + /** + * Returns true if an ability-driven animation is currently playing. + * Used by PlayerData.onLogin() to detect orphaned ability animations. + */ + public boolean isPlayingAbilityAnimation() { + return playingAbilityAnimation; + } + + /** + * Clears an orphaned ability animation (e.g. after relog when the ability is gone). + * Stops the animation and resets the tracking flag. + */ + public void clearOrphanedAbilityAnimation() { + stopAbilityAnimation(); } private void playAbilitySound(EntityPlayer player, String sound) { @@ -508,6 +869,73 @@ public class PlayerAbilityData implements IPlayerAbilityData { } } + // ═══════════════════════════════════════════════════════════════════ + // SCRIPT EVENTS + // ═══════════════════════════════════════════════════════════════════ + + /** + * Fire the ability start event. Returns true if cancelled. + */ + private boolean firePlayerStartEvent(EntityPlayer player, Ability ability) { + if (ScriptController.Instance == null) return false; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return false; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.StartEvent event = new PlayerAbilityEvent.StartEvent(iPlayer, ability, null); + return EventHooks.onPlayerAbilityStart(handler, event); + } + + /** + * Fire the ability execute event. Returns true if cancelled. + */ + private boolean firePlayerExecuteEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return false; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return false; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.ExecuteEvent event = new PlayerAbilityEvent.ExecuteEvent(iPlayer, ability, target); + return EventHooks.onPlayerAbilityExecute(handler, event); + } + + /** + * Fire the ability tick event. + */ + private void firePlayerTickEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.TickEvent event = new PlayerAbilityEvent.TickEvent( + iPlayer, ability, target, ability.getPhase().ordinal(), ability.getCurrentTick()); + EventHooks.onPlayerAbilityTick(handler, event); + } + + /** + * Fire the ability interrupt event. + */ + private void firePlayerInterruptEvent(EntityPlayer player, Ability ability, EntityLivingBase target, + DamageSource source, float damage) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.InterruptEvent event = new PlayerAbilityEvent.InterruptEvent( + iPlayer, ability, target, source, damage); + EventHooks.onPlayerAbilityInterrupt(handler, event); + } + + /** + * Fire the ability complete event. + */ + private void firePlayerCompleteEvent(EntityPlayer player, Ability ability, EntityLivingBase target) { + if (ScriptController.Instance == null) return; + PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player); + if (handler == null) return; + IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player); + PlayerAbilityEvent.CompleteEvent event = new PlayerAbilityEvent.CompleteEvent(iPlayer, ability, target); + EventHooks.onPlayerAbilityComplete(handler, event); + } + // ═══════════════════════════════════════════════════════════════════ // NBT SERIALIZATION // ═══════════════════════════════════════════════════════════════════ @@ -519,6 +947,7 @@ public class PlayerAbilityData implements IPlayerAbilityData { } compound.setTag("PlayerAbilities", list); compound.setInteger("PlayerAbilitySelected", selectedIndex); + compound.setBoolean("AbilityAnimating", playingAbilityAnimation); } public void readFromNBT(NBTTagCompound compound) { @@ -533,8 +962,30 @@ public class PlayerAbilityData implements IPlayerAbilityData { } } selectedIndex = compound.getInteger("PlayerAbilitySelected"); + + // Prune abilities that no longer exist (deleted custom abilities or removed built-ins) + validateUnlockedAbilities(); + if (selectedIndex >= unlockedAbilities.size()) { selectedIndex = Math.max(0, unlockedAbilities.size() - 1); } + playingAbilityAnimation = compound.getBoolean("AbilityAnimating"); + } + + /** + * Remove any unlocked ability keys that can no longer be resolved. + * Called during load to clean up references to deleted abilities. + */ + private void validateUnlockedAbilities() { + if (AbilityController.Instance == null) return; + + Iterator it = unlockedAbilities.iterator(); + while (it.hasNext()) { + String key = it.next(); + if (!AbilityController.Instance.canResolveAbility(key)) { + it.remove(); + LogWriter.info("Removed invalid ability reference from player data: " + key); + } + } } } diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerData.java b/src/main/java/noppes/npcs/controllers/data/PlayerData.java index fa4e7d961..7f326a344 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerData.java @@ -95,13 +95,21 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { private boolean specialKeyDown = false; public void onLogin() { - // Continue playing animation for self when re-logging + // Handle animation state from previous session AnimationData animationData = this.animationData; if (animationData != null && animationData.isClientAnimating()) { - Animation currentAnimation = animationData.currentClientAnimation; - NBTTagCompound compound = currentAnimation.writeToNBT(); - animationData.viewAnimation(currentAnimation, animationData, compound, - animationData.isClientAnimating(), currentAnimation.currentFrame, currentAnimation.currentFrameTime); + if (abilityData.isPlayingAbilityAnimation()) { + // Ability animation was playing when player disconnected. + // Ability state is transient (lost on disconnect), so this animation + // is orphaned - clear it instead of replaying a stuck animation. + abilityData.clearOrphanedAbilityAnimation(); + } else { + // Non-ability animation (e.g. script-driven) - continue playing + Animation currentAnimation = animationData.currentClientAnimation; + NBTTagCompound compound = currentAnimation.writeToNBT(); + animationData.viewAnimation(currentAnimation, animationData, compound, + animationData.isClientAnimating(), currentAnimation.currentFrame, currentAnimation.currentFrameTime); + } } CustomEffectController controller = CustomEffectController.getInstance(); @@ -116,6 +124,8 @@ public class PlayerData implements IExtendedEntityProperties, IPlayerData { } public void onLogout() { + // Cancel any executing ability and release all locks + abilityData.interruptCurrentAbility(); this.partyInvites.clear(); this.actionManager.clear(); } diff --git a/src/main/java/noppes/npcs/controllers/data/action/Action.java b/src/main/java/noppes/npcs/controllers/data/action/Action.java index b7bce1102..cb2af9454 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/Action.java +++ b/src/main/java/noppes/npcs/controllers/data/action/Action.java @@ -6,6 +6,7 @@ import noppes.npcs.api.handler.data.IActionQueue; import noppes.npcs.api.handler.data.actions.IConditionalAction; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.scripted.CustomNPCsException; +import org.apache.commons.lang3.exception.ExceptionUtils; import java.util.HashMap; import java.util.Map; @@ -344,6 +345,10 @@ public class Action implements IAction { try { onStart.accept(this); } catch (Throwable t) { + String err = "IAction" + getName() + " onStart threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("onStart Task of " + this + " threw an exception:", t); } @@ -359,6 +364,11 @@ public class Action implements IAction { task.accept(this); count++; } catch (Throwable t) { + String err = "IAction '" + name + "' threw an exception:"; + + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Task of " + this + " threw an exception:", t); markDone(); } @@ -374,6 +384,10 @@ public class Action implements IAction { try { onDone.accept(this); } catch (Throwable t) { + String err = "IAction" + getName() + " onDone threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("onDone Task of " + this + " threw an exception:", t); } diff --git a/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java b/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java index 9e608df37..427749e33 100644 --- a/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java +++ b/src/main/java/noppes/npcs/controllers/data/action/action/ConditionalAction.java @@ -4,6 +4,7 @@ import noppes.npcs.api.handler.data.IAction; import noppes.npcs.api.handler.data.actions.IConditionalAction; import noppes.npcs.controllers.data.action.Action; import noppes.npcs.controllers.data.action.ActionManager; +import org.apache.commons.lang3.exception.ExceptionUtils; import java.util.function.Consumer; import java.util.function.Function; @@ -130,6 +131,10 @@ public class ConditionalAction extends Action implements IConditionalAction { count++; taskExecuted = true; } catch (Throwable t) { + String err = "IConditionalAction '" + getName() + "' threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Task of " + this + " threw an exception:", t); markDone(); } @@ -146,6 +151,10 @@ public class ConditionalAction extends Action implements IConditionalAction { try { onTermination.accept(this); } catch (Throwable t) { + String err = "IConditionalAction" + getName() + " onTermination threw an exception:"; + if (reportTo != null) + reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t)); + manager.LOGGER.error("Termination Task of " + this + " threw an exception:", t); } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 9e6366fdf..187ce583d 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -308,6 +308,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti @Override public void onUpdate() { super.onUpdate(); + + // Re-apply locks after super.onUpdate() to override body rotation smoothing + // in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate() + // and overwrites renderYawOffset, causing a visible twitch each frame. + abilities.applyRotationControl(); + abilities.applyLockedPosition(); + if (!isRemote()) { if (this.ticksExisted % 10 == 0) { EventHooks.onNPCUpdate(this); @@ -377,11 +384,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } } - if (stats.potionType != EnumPotionType.None) { - if (stats.potionType != EnumPotionType.Fire) - ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(this.getPotionEffect(stats.potionType), stats.potionDuration * 20, stats.potionAmp)); - else - receiver.setFire(stats.potionDuration); + if (stats.potionType == EnumPotionType.Fire) { + receiver.setFire(stats.potionDuration); + } else if (stats.potionType != EnumPotionType.None) { + int potionId = stats.potionType.getResolvedPotionId(stats.potionManualId); + if (EnumPotionType.isValidPotionId(potionId)) { + ((EntityLivingBase) receiver).addPotionEffect(new PotionEffect(potionId, stats.potionDuration * 20, stats.potionAmp)); + } } return didAttack; } @@ -481,8 +490,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti super.onLivingUpdate(); - // Apply locked rotation after super.onLivingUpdate() to override look helper changes - abilities.applyLockedRotation(); + // Apply locks after super.onLivingUpdate() to override AI/physics changes + abilities.applyRotationControl(); + abilities.applyLockedPosition(); handleMountRiderState(); @@ -670,6 +680,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (entity instanceof EntityLivingBase) attackingEntity = (EntityLivingBase) entity; + if (faction.isPassive) + return false; + if (attackingEntity != null && attackingEntity == getOwner()) return false; else if (attackingEntity instanceof EntityNPCInterface) { @@ -1032,29 +1045,6 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti return weight; } - /* - * Used for getting the applied potion effect from dataStats. - */ - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } @Override public void setAir(int air) { diff --git a/src/main/java/noppes/npcs/entity/EntityProjectile.java b/src/main/java/noppes/npcs/entity/EntityProjectile.java index e25a66083..5d322ade8 100644 --- a/src/main/java/noppes/npcs/entity/EntityProjectile.java +++ b/src/main/java/noppes/npcs/entity/EntityProjectile.java @@ -94,6 +94,7 @@ public class EntityProjectile extends EntityThrowable { public boolean destroyTerrain = true; public int explosiveRadius = 0; public EnumPotionType effect = EnumPotionType.None; + public int manualPotionId = 0; public boolean burnItem = true; public int duration = 5; public int amplify = 0; @@ -508,12 +509,12 @@ public class EntityProjectile extends EntityThrowable { } } - if (this.effect != EnumPotionType.None && entityliving != null) { - if (this.effect != EnumPotionType.Fire) { - int p = this.getPotionEffect(effect); - entityliving.addPotionEffect(new PotionEffect(p, this.duration * 20, this.amplify)); - } else { - movingobjectposition.entityHit.setFire(duration); + if (this.effect == EnumPotionType.Fire && entityliving != null) { + movingobjectposition.entityHit.setFire(duration); + } else if (this.effect != EnumPotionType.None && entityliving != null) { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + entityliving.addPotionEffect(new PotionEffect(potionId, this.duration * 20, this.amplify)); } } } else if (this.hasGravity() && (this.isArrow() || this.sticksToWalls())) { @@ -637,21 +638,23 @@ public class EntityProjectile extends EntityThrowable { d1 = 1.0D; } - int i = this.getPotionEffect(effect); + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); - if (Potion.potionTypes[i].isInstant()) { - Potion.potionTypes[i].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); - } else { - int j = (int) (d1 * (double) this.duration + 0.5D); + if (EnumPotionType.isValidPotionId(potionId)) { + if (Potion.potionTypes[potionId].isInstant()) { + Potion.potionTypes[potionId].affectEntity(this.getThrower(), entitylivingbase, this.amplify, d1); + } else { + int j = (int) (d1 * (double) this.duration + 0.5D); - if (j > 20) { - entitylivingbase.addPotionEffect(new PotionEffect(i, j, this.amplify)); + if (j > 20) { + entitylivingbase.addPotionEffect(new PotionEffect(potionId, j, this.amplify)); + } } } } } } - this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor(this.effect)); + this.worldObj.playAuxSFX(2002, (int) Math.round(this.posX), (int) Math.round(this.posY), (int) Math.round(this.posZ), this.getPotionColor()); } } @@ -693,6 +696,8 @@ public class EntityProjectile extends EntityThrowable { par1NBTTagCompound.setBoolean("explosive", explosive); par1NBTTagCompound.setInteger("accuracy", accuracy); par1NBTTagCompound.setInteger("PotionEffect", effect.ordinal()); + if (effect == EnumPotionType.Manual) + par1NBTTagCompound.setInteger("PotionManualId", manualPotionId); par1NBTTagCompound.setString("trail", this.dataWatcher.getWatchableObjectString(22)); par1NBTTagCompound.setByte("Render3D", this.dataWatcher.getWatchableObjectByte(28)); par1NBTTagCompound.setByte("Spins", this.dataWatcher.getWatchableObjectByte(29)); @@ -723,7 +728,9 @@ public class EntityProjectile extends EntityThrowable { this.accelerate = par1NBTTagCompound.getBoolean("accelerate"); this.explosive = par1NBTTagCompound.getBoolean("explosive"); this.accuracy = par1NBTTagCompound.getInteger("accuracy"); - this.effect = EnumPotionType.values()[par1NBTTagCompound.getInteger("PotionEffect") % EnumPotionType.values().length]; + this.effect = EnumPotionType.fromOrdinal(par1NBTTagCompound.getInteger("PotionEffect")); + if (effect == EnumPotionType.Manual) + this.manualPotionId = par1NBTTagCompound.getInteger("PotionManualId"); this.dataWatcher.updateObject(22, par1NBTTagCompound.getString("trail")); this.dataWatcher.updateObject(23, Integer.valueOf(par1NBTTagCompound.getInteger("size"))); this.dataWatcher.updateObject(24, Byte.valueOf((byte) (par1NBTTagCompound.getBoolean("glows") ? 1 : 0))); @@ -774,46 +781,12 @@ public class EntityProjectile extends EntityThrowable { return this.thrower; } - private int getPotionEffect(EnumPotionType p) { - switch (p) { - case Poison: - return Potion.poison.id; - case Hunger: - return Potion.hunger.id; - case Weakness: - return Potion.weakness.id; - case Slowness: - return Potion.moveSlowdown.id; - case Nausea: - return Potion.confusion.id; - case Blindness: - return Potion.blindness.id; - case Wither: - return Potion.wither.id; - default: - return 0; - } - } - - private int getPotionColor(EnumPotionType p) { - switch (p) { - case Poison: - return 32660; - case Hunger: - return 32660; - case Weakness: - return 32696; - case Slowness: - return 32698; - case Nausea: - return 32732; - case Blindness: - return Potion.blindness.id; - case Wither: - return 32732; - default: - return 0; + private int getPotionColor() { + int potionId = this.effect.getResolvedPotionId(this.manualPotionId); + if (EnumPotionType.isValidPotionId(potionId)) { + return Potion.potionTypes[potionId].getLiquidColor(); } + return 0; } public void getStatProperties(DataStats stats) { @@ -823,6 +796,7 @@ public class EntityProjectile extends EntityThrowable { this.explosive = stats.pExplode; this.explosiveRadius = stats.pArea; this.effect = stats.pEffect; + this.manualPotionId = stats.pManualId; this.burnItem = stats.pBurnItem; this.duration = stats.pDur; this.amplify = stats.pEffAmp; diff --git a/src/main/java/noppes/npcs/scripted/NpcAPI.java b/src/main/java/noppes/npcs/scripted/NpcAPI.java index c80c18d28..24f271f33 100644 --- a/src/main/java/noppes/npcs/scripted/NpcAPI.java +++ b/src/main/java/noppes/npcs/scripted/NpcAPI.java @@ -7,6 +7,10 @@ import kamkeel.npcs.controllers.AttributeController; import kamkeel.npcs.controllers.ProfileController; import kamkeel.npcs.controllers.TelegraphController; import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; import net.minecraft.block.Block; import net.minecraft.command.CommandHandler; import net.minecraft.entity.Entity; @@ -119,6 +123,10 @@ import noppes.npcs.items.ItemScripted; import noppes.npcs.scripted.entity.ScriptAnimal; import noppes.npcs.scripted.entity.ScriptArrow; import noppes.npcs.scripted.entity.ScriptDBCPlayer; +import noppes.npcs.scripted.entity.ScriptEnergyBeam; +import noppes.npcs.scripted.entity.ScriptEnergyDisc; +import noppes.npcs.scripted.entity.ScriptEnergyLaser; +import noppes.npcs.scripted.entity.ScriptEnergyOrb; import noppes.npcs.scripted.entity.ScriptEntity; import noppes.npcs.scripted.entity.ScriptEntityItem; import noppes.npcs.scripted.entity.ScriptFishHook; @@ -454,6 +462,14 @@ public class NpcAPI extends AbstractNpcAPI { data = new ScriptEntityData(new ScriptArrow<>((EntityArrow) entity)); else if (entity instanceof EntityFishHook) data = new ScriptEntityData(new ScriptFishHook<>((EntityFishHook) entity)); + else if (entity instanceof EntityAbilityOrb) + data = new ScriptEntityData(new ScriptEnergyOrb<>((EntityAbilityOrb) entity)); + else if (entity instanceof EntityAbilityBeam) + data = new ScriptEntityData(new ScriptEnergyBeam<>((EntityAbilityBeam) entity)); + else if (entity instanceof EntityAbilityDisc) + data = new ScriptEntityData(new ScriptEnergyDisc<>((EntityAbilityDisc) entity)); + else if (entity instanceof EntityAbilityLaser) + data = new ScriptEntityData(new ScriptEnergyLaser<>((EntityAbilityLaser) entity)); else data = new ScriptEntityData(new ScriptEntity<>(entity)); entity.registerExtendedProperties("ScriptedObject", data); diff --git a/src/main/java/noppes/npcs/scripted/ScriptWorld.java b/src/main/java/noppes/npcs/scripted/ScriptWorld.java index c9b806ca9..b827315d2 100644 --- a/src/main/java/noppes/npcs/scripted/ScriptWorld.java +++ b/src/main/java/noppes/npcs/scripted/ScriptWorld.java @@ -21,6 +21,10 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.world.BlockEvent; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; import noppes.npcs.CustomNpcs; import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.IBlock; @@ -28,6 +32,10 @@ import noppes.npcs.api.IParticle; import noppes.npcs.api.IPos; import noppes.npcs.api.ITileEntity; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyBeam; +import noppes.npcs.api.entity.IEnergyDisc; +import noppes.npcs.api.entity.IEnergyLaser; +import noppes.npcs.api.entity.IEnergyOrb; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.handler.data.ISound; @@ -1242,6 +1250,48 @@ public class ScriptWorld implements IWorld { return "DIM" + this.getDimensionID(); } + @Override + public IEnergyOrb createEnergyOrb(IEntity owner, double x, double y, double z, float size) { + EntityAbilityOrb entity = new EntityAbilityOrb(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setProjectileSize(size); + return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyBeam createEnergyBeam(IEntity owner, double x, double y, double z, float beamWidth, float headSize) { + EntityAbilityBeam entity = new EntityAbilityBeam(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setBeamWidth(beamWidth); + entity.setHeadSize(headSize); + return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyDisc createEnergyDisc(IEntity owner, double x, double y, double z, float radius, float thickness) { + EntityAbilityDisc entity = new EntityAbilityDisc(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setDiscRadius(radius); + entity.setDiscThickness(thickness); + return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity); + } + + @Override + public IEnergyLaser createEnergyLaser(IEntity owner, double x, double y, double z, float laserWidth) { + EntityAbilityLaser entity = new EntityAbilityLaser(world); + entity.setPosition(x, y, z); + entity.setStartPosition(x, y, z); + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + entity.setLaserWidth(laserWidth); + return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity); + } + @Override public void broadcast(String message) { world.func_73046_m().getConfigurationManager().sendChatMsg(new ChatComponentText(message)); diff --git a/src/main/java/noppes/npcs/scripted/constants/EntityType.java b/src/main/java/noppes/npcs/scripted/constants/EntityType.java index 995969682..355173646 100644 --- a/src/main/java/noppes/npcs/scripted/constants/EntityType.java +++ b/src/main/java/noppes/npcs/scripted/constants/EntityType.java @@ -15,4 +15,8 @@ public class EntityType { public static final int THROWABLE = 11; public static final int FISH_HOOK = 12; public static final int ENERGY_PROJECTILE = 13; + public static final int ENERGY_ORB = 14; + public static final int ENERGY_BEAM = 15; + public static final int ENERGY_DISC = 16; + public static final int ENERGY_LASER = 17; } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java new file mode 100644 index 000000000..b42a32b1d --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyBeam.java @@ -0,0 +1,69 @@ +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 extends ScriptEnergyProjectile implements IEnergyBeam { + + public ScriptEnergyBeam(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_BEAM; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_BEAM || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 1; + } + + // ==================== BEAM-SPECIFIC ==================== + + public float getBeamWidth() { return entity.getBeamWidth(); } + public void setBeamWidth(float width) { entity.setBeamWidth(width); } + + public float getHeadSize() { return entity.getHeadSize(); } + public void setHeadSize(float size) { entity.setHeadSize(size); } + + public boolean isAttachedToOwner() { return entity.isAttachedToOwner(); } + public void setAttachedToOwner(boolean attached) { entity.setAttachedToOwner(attached); } + + public boolean shouldRenderTailOrb() { return entity.shouldRenderTailOrb(); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startFiring(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + entity.startFiring(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java new file mode 100644 index 000000000..62dde7979 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyDisc.java @@ -0,0 +1,75 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityDisc; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyDisc; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyDisc extends ScriptEnergyProjectile implements IEnergyDisc { + + public ScriptEnergyDisc(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_DISC; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_DISC || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 2; + } + + // ==================== DISC-SPECIFIC ==================== + + public float getDiscRadius() { return entity.getDiscRadius(); } + public void setDiscRadius(float radius) { entity.setDiscRadius(radius); } + + public float getDiscThickness() { return entity.getDiscThickness(); } + public void setDiscThickness(float thickness) { entity.setDiscThickness(thickness); } + + public boolean isVertical() { return entity.isVertical(); } + public void setVertical(boolean vertical) { entity.setVertical(vertical); } + + public boolean isBoomerang() { return entity.isBoomerang(); } + public void setBoomerang(boolean boomerang) { entity.setBoomerang(boomerang); } + + public int getBoomerangDelay() { return entity.getBoomerangDelay(); } + public void setBoomerangDelay(int ticks) { entity.setBoomerangDelay(ticks); } + + public boolean isReturning() { return entity.isReturning(); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + entity.startMoving(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java new file mode 100644 index 000000000..976fd948d --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyLaser.java @@ -0,0 +1,82 @@ +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 extends ScriptEnergyProjectile implements IEnergyLaser { + + public ScriptEnergyLaser(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_LASER; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_LASER || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 3; + } + + // ==================== LASER-SPECIFIC ==================== + + public float getLaserWidth() { return entity.getLaserWidth(); } + public void setLaserWidth(float width) { entity.setLaserWidth(width); } + + public float getExpansionSpeed() { return entity.getExpansionSpeed(); } + public void setExpansionSpeed(float speed) { entity.setExpansionSpeed(speed); } + + public int getLingerTicks() { return entity.getLingerTicks(); } + public void setLingerTicks(int ticks) { entity.setLingerTicks(ticks); } + + public float getCurrentLength() { return entity.getCurrentLength(); } + public boolean isFullyExtended() { return entity.isFullyExtended(); } + + public double getDirX() { return entity.getDirX(); } + public double getDirY() { return entity.getDirY(); } + public double getDirZ() { return entity.getDirZ(); } + public void setDirection(double x, double y, double z) { entity.setDirection(x, y, z); } + + public double getEndX() { return entity.getEndX(); } + public double getEndY() { return entity.getEndY(); } + public double getEndZ() { return entity.getEndZ(); } + + public float getLingerAlpha() { return entity.getLingerAlpha(); } + + public boolean isLockVerticalDirection() { return entity.isLockVerticalDirection(); } + public void setLockVerticalDirection(boolean lock) { entity.setLockVerticalDirection(lock); } + + // ==================== FIRE ==================== + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.setDirection(dx / len, dy / len, dz / len); + } + entity.startMoving(null); + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java new file mode 100644 index 000000000..1b6a95fb7 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyOrb.java @@ -0,0 +1,53 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityOrb; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyOrb; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyOrb extends ScriptEnergyProjectile implements IEnergyOrb { + + public ScriptEnergyOrb(T entity) { + super(entity); + } + + @Override + public int getType() { + return EntityType.ENERGY_ORB; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_ORB || super.typeOf(type); + } + + @Override + public int getEnergyType() { + return 0; + } + + @Override + public void fire(IEntity target) { + ensureSpawned(); + EntityLivingBase mcTarget = null; + if (target != null && target.getMCEntity() instanceof EntityLivingBase) { + mcTarget = (EntityLivingBase) target.getMCEntity(); + } + entity.startMoving(mcTarget); + } + + @Override + public void fire(double x, double y, double z) { + ensureSpawned(); + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java new file mode 100644 index 000000000..f614b8122 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEnergyProjectile.java @@ -0,0 +1,252 @@ +package noppes.npcs.scripted.entity; + +import kamkeel.npcs.entity.EntityAbilityProjectile; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.entity.IEntityLivingBase; +import noppes.npcs.EventHooks; +import noppes.npcs.scripted.NpcAPI; +import noppes.npcs.scripted.constants.EntityType; + +public class ScriptEnergyProjectile extends ScriptEntity implements IEnergyProjectile { + protected T entity; + + public ScriptEnergyProjectile(T entity) { + super(entity); + this.entity = entity; + } + + // ==================== TYPE ==================== + + @Override + public int getType() { + return EntityType.ENERGY_PROJECTILE; + } + + @Override + public boolean typeOf(int type) { + return type == EntityType.ENERGY_PROJECTILE || super.typeOf(type); + } + + public int getEnergyType() { + return -1; + } + + // ==================== OWNER & TARGET ==================== + + public int getOwnerEntityId() { + return entity.getOwnerEntityId(); + } + + public IEntity getOwner() { + return entity.getOwner(); + } + + public void setOwner(IEntity owner) { + if (owner != null) { + entity.setOwnerEntityId(owner.getMCEntity().getEntityId()); + } + } + + public int getTargetEntityId() { + return entity.getTargetEntityId(); + } + + public IEntity getTarget() { + return entity.getTarget(); + } + + public void setTarget(IEntity target) { + if (target != null) { + entity.setTargetEntityId(target.getMCEntity().getEntityId()); + } else { + entity.setTargetEntityId(-1); + } + } + + // ==================== SIZE ==================== + + public float getSize() { + return entity.getSize(); + } + + public void setSize(float size) { + entity.setProjectileSize(size); + } + + // ==================== DISPLAY ==================== + + public int getInnerColor() { return entity.getInnerColor(); } + public void setInnerColor(int color) { entity.setInnerColor(color); } + + public int getOuterColor() { return entity.getOuterColor(); } + public void setOuterColor(int color) { entity.setOuterColor(color); } + + public boolean isOuterColorEnabled() { return entity.isOuterColorEnabled(); } + public void setOuterColorEnabled(boolean enabled) { entity.setOuterColorEnabled(enabled); } + + public float getOuterColorWidth() { return entity.getOuterColorWidth(); } + public void setOuterColorWidth(float width) { entity.setOuterColorWidth(width); } + + public float getOuterColorAlpha() { return entity.getOuterColorAlpha(); } + public void setOuterColorAlpha(float alpha) { entity.setOuterColorAlpha(alpha); } + + public float getRotationSpeed() { return entity.getRotationSpeed(); } + public void setRotationSpeed(float speed) { entity.setRotationSpeed(speed); } + + // ==================== INTERPOLATION ==================== + + public float getInterpolatedRotationX(float partialTicks) { return entity.getInterpolatedRotationX(partialTicks); } + public float getInterpolatedRotationY(float partialTicks) { return entity.getInterpolatedRotationY(partialTicks); } + public float getInterpolatedRotationZ(float partialTicks) { return entity.getInterpolatedRotationZ(partialTicks); } + public float getInterpolatedSize(float partialTicks) { return entity.getInterpolatedSize(partialTicks); } + + // ==================== LIGHTNING ==================== + + public boolean hasLightningEffect() { return entity.hasLightningEffect(); } + public void setLightningEffect(boolean enabled) { entity.setLightningEffect(enabled); } + + public float getLightningDensity() { return entity.getLightningDensity(); } + public void setLightningDensity(float density) { entity.setLightningDensity(density); } + + public float getLightningRadius() { return entity.getLightningRadius(); } + public void setLightningRadius(float radius) { entity.setLightningRadius(radius); } + + public int getLightningFadeTime() { return entity.getLightningFadeTime(); } + public void setLightningFadeTime(int ticks) { entity.setLightningFadeTime(ticks); } + + // ==================== LIFESPAN ==================== + + public float getMaxDistance() { return entity.getMaxDistance(); } + public void setMaxDistance(float distance) { entity.setMaxDistance(distance); } + + public int getMaxLifetime() { return entity.getMaxLifetime(); } + public void setMaxLifetime(int ticks) { entity.setMaxLifetime(ticks); } + + // ==================== COMBAT ==================== + + public float getDamage() { return entity.getDamage(); } + public void setDamage(float damage) { entity.setCombatDamage(damage); } + + public float getKnockback() { return entity.getKnockback(); } + public void setKnockback(float knockback) { entity.setCombatKnockback(knockback); } + + public float getKnockbackUp() { return entity.getKnockbackUp(); } + public void setKnockbackUp(float knockbackUp) { entity.setCombatKnockbackUp(knockbackUp); } + + public boolean isExplosive() { return entity.isExplosive(); } + public void setExplosive(boolean explosive) { entity.setExplosive(explosive); } + + public float getExplosionRadius() { return entity.getExplosionRadius(); } + public void setExplosionRadius(float radius) { entity.setExplosionRadius(radius); } + + public float getExplosionDamageFalloff() { return entity.getExplosionDamageFalloff(); } + public void setExplosionDamageFalloff(float falloff) { entity.setExplosionDamageFalloff(falloff); } + + // ==================== MOVEMENT ==================== + + public float getSpeed() { return entity.getSpeed(); } + public void setSpeed(float speed) { entity.setSpeed(speed); } + + public boolean isHoming() { return entity.isHoming(); } + public void setHoming(boolean homing) { entity.setHomingEnabled(homing); } + + public float getHomingStrength() { return entity.getHomingStrength(); } + public void setHomingStrength(float strength) { entity.setHomingStrength(strength); } + + public float getHomingRange() { return entity.getHomingRange(); } + public void setHomingRange(float range) { entity.setHomingRange(range); } + + // ==================== ANCHOR ==================== + + public int getAnchor() { return entity.getAnchor(); } + public float getAnchorOffsetX() { return entity.getAnchorOffsetX(); } + public float getAnchorOffsetY() { return entity.getAnchorOffsetY(); } + public float getAnchorOffsetZ() { return entity.getAnchorOffsetZ(); } + + // ==================== POSITION ==================== + + public double getStartX() { return entity.getStartX(); } + public double getStartY() { return entity.getStartY(); } + public double getStartZ() { return entity.getStartZ(); } + + // ==================== STATE ==================== + + public boolean hasHit() { return entity.getHasHit(); } + public boolean isCharging() { return entity.isCharging(); } + public float getChargeProgress() { return entity.getChargeProgress(); } + + // ==================== FIRE ==================== + + public void fire(IEntity target) { + if (target != null) { + Entity mcTarget = target.getMCEntity(); + setMotionToward(mcTarget.posX, mcTarget.posY + mcTarget.getEyeHeight(), mcTarget.posZ); + } + ensureSpawned(); + } + + public void fire(double x, double y, double z) { + setMotionToward(x, y, z); + ensureSpawned(); + } + + public void fire(float yaw, float pitch) { + float yawRad = (float) Math.toRadians(yaw); + float pitchRad = (float) Math.toRadians(pitch); + entity.motionX = -Math.sin(yawRad) * Math.cos(pitchRad) * entity.getSpeed(); + entity.motionY = -Math.sin(pitchRad) * entity.getSpeed(); + entity.motionZ = Math.cos(yawRad) * Math.cos(pitchRad) * entity.getSpeed(); + ensureSpawned(); + } + + public void fire(IEntityLivingBase caster) { + if (caster == null) return; + initFromCaster(caster); + fire(caster.getRotation(), caster.getPitch()); + } + + public void fire(IEntityLivingBase caster, IEntity target) { + if (caster == null) return; + initFromCaster(caster); + fire(target); + } + + /** + * Sets owner from caster and positions projectile at caster's eye level. + */ + private void initFromCaster(IEntityLivingBase caster) { + EntityLivingBase mc = (EntityLivingBase) caster.getMCEntity(); + entity.setOwnerEntityId(mc.getEntityId()); + double eyeY = mc.posY + mc.getEyeHeight(); + entity.setPosition(mc.posX, eyeY, mc.posZ); + entity.setStartPosition(mc.posX, eyeY, mc.posZ); + } + + /** + * Calculates and sets motion from the projectile's current position toward a target point. + */ + private void setMotionToward(double x, double y, double z) { + double dx = x - entity.posX; + double dy = y - entity.posY; + double dz = z - entity.posZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + entity.motionX = (dx / len) * entity.getSpeed(); + entity.motionY = (dy / len) * entity.getSpeed(); + entity.motionZ = (dz / len) * entity.getSpeed(); + } + } + + protected void ensureSpawned() { + if (!entity.addedToChunk && entity.worldObj != null) { + entity.worldObj.spawnEntityInWorld(entity); + if (!entity.worldObj.isRemote) { + EventHooks.onEnergyProjectileFired(entity); + } + } + } + +} diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java b/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java index caac8d87d..65b2866af 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptEntity.java @@ -1,5 +1,10 @@ package noppes.npcs.scripted.entity; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.entity.EntityAbilityDisc; +import kamkeel.npcs.entity.EntityAbilityLaser; +import kamkeel.npcs.entity.EntityAbilityOrb; +import kamkeel.npcs.entity.EntityAbilityProjectile; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -526,6 +531,16 @@ public class ScriptEntity implements IEntity { cls = EntityMob.class; else if (type == EntityType.NPC) cls = EntityNPCInterface.class; + else if (type == EntityType.ENERGY_PROJECTILE) + cls = EntityAbilityProjectile.class; + else if (type == EntityType.ENERGY_ORB) + cls = EntityAbilityOrb.class; + else if (type == EntityType.ENERGY_BEAM) + cls = EntityAbilityBeam.class; + else if (type == EntityType.ENERGY_DISC) + cls = EntityAbilityDisc.class; + else if (type == EntityType.ENERGY_LASER) + cls = EntityAbilityLaser.class; List entities = entity.worldObj.getEntitiesWithinAABB(cls, entity.boundingBox.expand(range, range, range)); List list = new ArrayList(); diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java b/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java index 15459194e..50f1914a7 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptLivingBase.java @@ -6,6 +6,7 @@ import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSource; +import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import noppes.npcs.api.IBlock; import noppes.npcs.api.IDamageSource; @@ -380,4 +381,53 @@ public class ScriptLivingBase extends ScriptEntity 0.4D) { + entity.motionY = 0.4D; + } + + entity.velocityChanged = true; + } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java index f534f9dbc..2379c2035 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java @@ -7,6 +7,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.ITimers; import noppes.npcs.api.ability.IDataAbilities; import noppes.npcs.api.entity.ICustomNpc; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntityLivingBase; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.entity.data.IModelData; @@ -28,6 +29,7 @@ import noppes.npcs.constants.EnumMovingType; import noppes.npcs.constants.EnumNavType; import noppes.npcs.constants.EnumRoleType; import noppes.npcs.constants.EnumStandingType; +import kamkeel.npcs.entity.EntityAbilityProjectile; import noppes.npcs.controllers.FactionController; import noppes.npcs.controllers.data.DialogOption; import noppes.npcs.controllers.data.Line; @@ -1463,4 +1465,13 @@ public class ScriptNpc extends ScriptLiving imp public IDataAbilities getAbilityData() { return new ScriptDataAbilities(npc); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + java.util.List entities = EntityAbilityProjectile.getActiveProjectiles(npc.getEntityId()); + IEnergyProjectile[] result = new IEnergyProjectile[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + result[i] = (IEnergyProjectile) NpcAPI.Instance().getIEntity(entities.get(i)); + } + return result; + } } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java index a1b91e1db..3608b9d1e 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptPlayer.java @@ -1,6 +1,7 @@ package noppes.npcs.scripted.entity; import kamkeel.npcs.controllers.AttributeController; +import kamkeel.npcs.entity.EntityAbilityProjectile; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.packets.data.AchievementPacket; import kamkeel.npcs.network.packets.data.ChatAlertPacket; @@ -31,6 +32,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.IScreenSize; import noppes.npcs.api.ITimers; import noppes.npcs.api.IWorld; +import noppes.npcs.api.entity.IEnergyProjectile; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.api.gui.ICustomGui; @@ -933,4 +935,13 @@ public class ScriptPlayer extends ScriptLivingBase public String getFormattedCurrencyBalance() { return getData().tradeData.formatBalance(); } + + public IEnergyProjectile[] getActiveEnergyProjectiles() { + List entities = EntityAbilityProjectile.getActiveProjectiles(player.getEntityId()); + IEnergyProjectile[] result = new IEnergyProjectile[entities.size()]; + for (int i = 0; i < entities.size(); i++) { + result[i] = (IEnergyProjectile) NpcAPI.Instance().getIEntity(entities.get(i)); + } + return result; + } } diff --git a/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java new file mode 100644 index 000000000..4a1fab5a2 --- /dev/null +++ b/src/main/java/noppes/npcs/scripted/event/EnergyProjectileEvent.java @@ -0,0 +1,132 @@ +package noppes.npcs.scripted.event; + +import cpw.mods.fml.common.eventhandler.Cancelable; +import noppes.npcs.api.IBlock; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; +import noppes.npcs.api.event.IEnergyProjectileEvent; +import noppes.npcs.constants.EnumScriptType; + +public class EnergyProjectileEvent extends CustomNPCsEvent implements IEnergyProjectileEvent { + public final IEnergyProjectile projectile; + public final IEntity owner; + + public EnergyProjectileEvent(IEnergyProjectile projectile) { + this.projectile = projectile; + this.owner = projectile.getOwner(); + } + + @Override + public IEnergyProjectile getProjectile() { + return projectile; + } + + @Override + public IEntity getOwner() { + return owner; + } + + @Override + public String getHookName() { + return "energyProjectileEvent"; + } + + /** + * energyProjectileFired + */ + public static class FiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.FiredEvent { + public FiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_FIRED.function; + } + } + + /** + * energyProjectileTick + */ + public static class UpdateEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.UpdateEvent { + public UpdateEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_TICK.function; + } + } + + /** + * energyProjectileEntityImpact + */ + @Cancelable + public static class EntityImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.EntityImpactEvent { + private final IEntity target; + private float damage; + + public EntityImpactEvent(IEnergyProjectile projectile, IEntity target, float damage) { + super(projectile); + this.target = target; + this.damage = damage; + } + + @Override + public IEntity getTarget() { + return target; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_ENTITY_IMPACT.function; + } + } + + /** + * energyProjectileBlockImpact + */ + public static class BlockImpactEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.BlockImpactEvent { + private final IBlock block; + + public BlockImpactEvent(IEnergyProjectile projectile, IBlock block) { + super(projectile); + this.block = block; + } + + @Override + public IBlock getBlock() { + return block; + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_BLOCK_IMPACT.function; + } + } + + /** + * energyProjectileExpired + */ + public static class ExpiredEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.ExpiredEvent { + public ExpiredEvent(IEnergyProjectile projectile) { + super(projectile); + } + + @Override + public String getHookName() { + return EnumScriptType.ENERGY_PROJECTILE_EXPIRED.function; + } + } +} diff --git a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java index cb7def405..b99aac1a1 100644 --- a/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java +++ b/src/main/java/noppes/npcs/scripted/event/player/PlayerAbilityEvent.java @@ -3,6 +3,8 @@ package noppes.npcs.scripted.event.player; import cpw.mods.fml.common.eventhandler.Cancelable; import kamkeel.npcs.controllers.data.ability.Ability; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.util.DamageSource; +import noppes.npcs.api.IDamageSource; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.entity.IEntityLivingBase; import noppes.npcs.api.entity.IPlayer; @@ -38,6 +40,108 @@ public class PlayerAbilityEvent extends PlayerEvent implements IPlayerAbilityEve return "playerAbilityEvent"; } + /** + * Fired when a player's ability starts executing (enters WINDUP phase). + */ + @Cancelable + public static class StartEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.StartEvent { + public StartEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_START.function; + } + } + + /** + * Fired when a player's ability enters the ACTIVE phase and performs its effect. + */ + @Cancelable + public static class ExecuteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.ExecuteEvent { + public ExecuteEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_EXECUTE.function; + } + } + + /** + * Fired when a player's ability is interrupted by damage. + */ + public static class InterruptEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.InterruptEvent { + private final IDamageSource damageSource; + private final float damage; + + public InterruptEvent(IPlayer player, Ability ability, EntityLivingBase target, DamageSource source, float damage) { + super(player, ability, target); + this.damageSource = source != null ? NpcAPI.Instance().getIDamageSource(source) : null; + this.damage = damage; + } + + @Override + public IDamageSource getDamageSource() { + return damageSource; + } + + @Override + public float getDamage() { + return damage; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_INTERRUPT.function; + } + } + + /** + * Fired when a player's ability completes its full execution cycle. + */ + public static class CompleteEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.CompleteEvent { + public CompleteEvent(IPlayer player, Ability ability, EntityLivingBase target) { + super(player, ability, target); + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_COMPLETE.function; + } + } + + /** + * Fired every tick while a player's ability is executing. + */ + public static class TickEvent extends PlayerAbilityEvent implements IPlayerAbilityEvent.TickEvent { + private final int abilityPhase; + private final int tick; + + public TickEvent(IPlayer player, Ability ability, EntityLivingBase target, int phase, int tick) { + super(player, ability, target); + this.abilityPhase = phase; + this.tick = tick; + } + + @Override + public int getAbilityPhase() { + return abilityPhase; + } + + @Override + public int getTick() { + return tick; + } + + @Override + public String getHookName() { + return EnumScriptType.ABILITY_TICK.function; + } + } + /** * Fired when a player's ability hits an entity with damage. * Canceling prevents the damage from being applied. diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java index d0b5259ea..e27f6e075 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -42,12 +42,25 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void addAbility(IAbility ability) { if (ability instanceof Ability) { - data.addAbility((Ability) ability); + Ability a = (Ability) ability; + // Validate ability allows NPCs + if (!a.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } + data.addAbility(a); } } @Override public void addAbilityReference(String key) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } data.addAbilityReference(key); } @@ -158,6 +171,14 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean executeAbility(String key, Object target) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return false; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return false; // Ability is PLAYER_ONLY + } EntityLivingBase targetEntity = resolveTarget(target); return data.executeAbility(key, targetEntity); } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java index a36c65d51..42ed3372e 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -1,5 +1,7 @@ package noppes.npcs.scripted.wrapper; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.ability.IPlayerAbilityData; @@ -26,7 +28,17 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void unlockAbility(String key) { - data.unlockAbility(key); + // Validate ability exists and allows players + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsPlayer()) { + return; // Ability is NPC-only + } + // Use canonical key (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.unlockAbility(canonicalKey); } @Override diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json new file mode 100644 index 000000000..82b2294ca --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Active.json @@ -0,0 +1,59 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 28, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json new file mode 100644 index 000000000..c627007e3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Charge_Windup.json @@ -0,0 +1,122 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -6.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 44.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -10.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -10.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 75.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 18 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_ARM", + "Rotation1": 50.0f, + "Rotation0": -75.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 45.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 27, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Charge_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json index 8fbaa73da..98a3299a2 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json @@ -1,17 +1,17 @@ { - "Loop": 5, + "Loop": -1, "Speed": 1.0f, "Frames": [ { "ColorMarker": 16777215, "Comment": "", - "Speed": 2.0f, + "Speed": 3.0f, "FrameParts": [ { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, "Pivot0": 3.0f, "Pivot1": 2.0f, "Rotation2": 0.0f @@ -25,15 +25,6 @@ "Pivot1": 2.0f, "Rotation2": 56.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_ARM", @@ -43,33 +34,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_LEG", - "Rotation1": -18.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 2 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 1.5f, - "FrameParts": [ { "Pivot2": -5.0f, "Part": "BODY", @@ -79,33 +43,6 @@ "Pivot1": 2.0f, "Rotation2": 0.0f }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 56.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": 120.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, { "Pivot2": -1.0f, "Part": "RIGHT_LEG", @@ -115,42 +52,6 @@ "Pivot1": 0.0f, "Rotation2": 0.0f }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - } - ], - "Smooth": 0b, - "Duration": 4 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.5f, - "FrameParts": [ - { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -7.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 56.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_LEG", @@ -159,37 +60,10 @@ "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": -25.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": 0.0f, - "Rotation0": 120.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "RIGHT_LEG", - "Rotation1": -18.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 }, { "ColorMarker": 16777215, @@ -198,8 +72,8 @@ "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -214,15 +88,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -232,6 +97,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -242,17 +116,17 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 2 + "Duration": 3 }, { "ColorMarker": 16777215, @@ -261,8 +135,8 @@ "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -277,15 +151,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -295,6 +160,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -305,27 +179,27 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 }, { "ColorMarker": 16777215, "Comment": "", - "Speed": 0.5f, + "Speed": 0.25f, "FrameParts": [ { "Pivot2": 2.0f, - "Part": "BODY", - "Rotation1": -25.0f, + "Part": "HEAD", + "Rotation1": 0.0f, "Rotation0": -12.0f, "Pivot0": -1.0f, "Pivot1": 1.0f, @@ -340,15 +214,6 @@ "Pivot1": 0.0f, "Rotation2": 75.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -25.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": 2.0f, "Part": "LEFT_ARM", @@ -358,6 +223,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, { "Pivot2": 0.0f, "Part": "RIGHT_LEG", @@ -368,17 +242,17 @@ "Rotation2": 6.0f }, { - "Pivot2": 2.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": -12.0f, - "Pivot0": -1.0f, - "Pivot1": 1.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f } ], "Smooth": 0b, - "Duration": 4 + "Duration": 3 } ], "CurrentFrameTime": 0, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json index 080306c95..0dc050b19 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json @@ -7,51 +7,6 @@ "Comment": "", "Speed": 0.5f, "FrameParts": [ - { - "Pivot2": -8.0f, - "Part": "BODY", - "Rotation1": 25.0f, - "Rotation0": 31.0f, - "Pivot0": -2.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 50.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -2.0f, - "Part": "LEFT_LEG", - "Rotation1": 0.0f, - "Rotation0": 25.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -31.0f - }, - { - "Pivot2": -8.0f, - "Part": "LEFT_ARM", - "Rotation1": 31.0f, - "Rotation0": -56.0f, - "Pivot0": -2.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -3.0f, - "Part": "RIGHT_LEG", - "Rotation1": 25.0f, - "Rotation0": 18.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "FULL_MODEL", @@ -69,6 +24,51 @@ "Pivot0": -2.0f, "Pivot1": 2.0f, "Rotation2": -12.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 31.0f, + "Rotation0": -56.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "BODY", + "Rotation1": 25.0f, + "Rotation0": 31.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_LEG", + "Rotation1": 25.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -31.0f } ], "Smooth": 0b, @@ -79,51 +79,6 @@ "Comment": "", "Speed": 0.35f, "FrameParts": [ - { - "Pivot2": 0.0f, - "Part": "BODY", - "Rotation1": 50.0f, - "Rotation0": -6.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": 50.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": 170.0f - }, - { - "Pivot2": -3.0f, - "Part": "LEFT_ARM", - "Rotation1": 75.0f, - "Rotation0": -107.0f, - "Pivot0": -6.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -6.0f, - "Rotation0": 12.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "RIGHT_LEG", - "Rotation1": 50.0f, - "Rotation0": 18.0f, - "Pivot0": -3.0f, - "Pivot1": -4.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "FULL_MODEL", @@ -141,6 +96,51 @@ "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 170.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -107.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 50.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": -4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f } ], "Smooth": 0b, @@ -153,9 +153,18 @@ "FrameParts": [ { "Pivot2": 0.0f, - "Part": "BODY", - "Rotation1": 50.0f, - "Rotation0": -6.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -179,10 +188,10 @@ "Rotation2": 0.0f }, { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -6.0f, - "Rotation0": 12.0f, + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -197,19 +206,10 @@ "Rotation2": 0.0f }, { - "Pivot2": 0.0f, - "Part": "FULL_MODEL", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": 0.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, "Pivot0": 0.0f, "Pivot1": 0.0f, "Rotation2": 0.0f @@ -221,13 +221,13 @@ { "ColorMarker": 16777215, "Comment": "", - "Speed": 2.0f, + "Speed": 3.0f, "FrameParts": [ { - "Pivot2": -5.0f, - "Part": "BODY", - "Rotation1": -37.0f, - "Rotation0": 37.0f, + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, "Pivot0": 3.0f, "Pivot1": 2.0f, "Rotation2": 0.0f @@ -241,15 +241,6 @@ "Pivot1": 2.0f, "Rotation2": 56.0f }, - { - "Pivot2": 0.0f, - "Part": "LEFT_LEG", - "Rotation1": -37.0f, - "Rotation0": 31.0f, - "Pivot0": 0.0f, - "Pivot1": 0.0f, - "Rotation2": -25.0f - }, { "Pivot2": 0.0f, "Part": "LEFT_ARM", @@ -259,6 +250,15 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, { "Pivot2": -1.0f, "Part": "RIGHT_LEG", @@ -269,13 +269,13 @@ "Rotation2": 0.0f }, { - "Pivot2": -6.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 18.0f, - "Pivot0": 3.0f, - "Pivot1": 2.0f, - "Rotation2": 0.0f + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f } ], "Smooth": 0b, @@ -283,7 +283,7 @@ } ], "CurrentFrameTime": 0, - "CurrentFrame": 1, + "CurrentFrame": 3, "Smooth": 0b, "ID": 17, "WhileAttacking": 1b, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json new file mode 100644 index 000000000..38e42bd1e --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Generic_Dazed.json @@ -0,0 +1,770 @@ +{ + "Loop": 11, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 20 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": -18.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": -145.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 11, + "Smooth": 0b, + "ID": 100, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Generic_Dazed", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json index 15d49bce6..a276742ba 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json @@ -7,24 +7,6 @@ "Comment": "", "Speed": 0.8f, "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 31.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -12.0f - }, { "Pivot2": -1.0f, "Part": "HEAD", @@ -34,15 +16,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 6.0f - }, { "Pivot2": -1.0f, "Part": "BODY", @@ -60,24 +33,6 @@ "Pivot0": 0.0f, "Pivot1": 1.0f, "Rotation2": 6.0f - } - ], - "Smooth": 0b, - "Duration": 10 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f }, { "Pivot2": -4.0f, @@ -86,16 +41,16 @@ "Rotation0": 31.0f, "Pivot0": 2.0f, "Pivot1": 0.0f, - "Rotation2": -18.0f + "Rotation2": -12.0f }, { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 31.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, "Pivot1": 1.0f, - "Rotation2": -6.0f + "Rotation2": -37.0f }, { "Pivot2": -2.0f, @@ -104,7 +59,25 @@ "Rotation0": 25.0f, "Pivot0": -2.0f, "Pivot1": -1.0f, - "Rotation2": 0.0f + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 13 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f }, { "Pivot2": -1.0f, @@ -123,24 +96,6 @@ "Pivot0": 0.0f, "Pivot1": 1.0f, "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f }, { "Pivot2": -4.0f, @@ -151,51 +106,6 @@ "Pivot1": 0.0f, "Rotation2": -18.0f }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ { "Pivot2": 3.0f, "Part": "RIGHT_ARM", @@ -205,24 +115,6 @@ "Pivot1": 1.0f, "Rotation2": -37.0f }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, { "Pivot2": -2.0f, "Part": "RIGHT_LEG", @@ -231,997 +123,16 @@ "Pivot0": -2.0f, "Pivot1": -1.0f, "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f } ], "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 - }, - { - "ColorMarker": 16777215, - "Comment": "", - "Speed": 0.1f, - "FrameParts": [ - { - "Pivot2": 3.0f, - "Part": "RIGHT_ARM", - "Rotation1": 40.0f, - "Rotation0": -107.0f, - "Pivot0": 2.0f, - "Pivot1": 1.0f, - "Rotation2": -37.0f - }, - { - "Pivot2": -4.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 2.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, - { - "Pivot2": -1.0f, - "Part": "HEAD", - "Rotation1": 0.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 37.0f, - "Rotation0": 25.0f, - "Pivot0": -2.0f, - "Pivot1": -1.0f, - "Rotation2": 0.0f - }, - { - "Pivot2": -1.0f, - "Part": "BODY", - "Rotation1": 18.0f, - "Rotation0": 0.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - }, - { - "Pivot2": 0.0f, - "Part": "LEFT_ARM", - "Rotation1": -40.0f, - "Rotation0": -40.0f, - "Pivot0": 0.0f, - "Pivot1": 1.0f, - "Rotation2": -6.0f - } - ], - "Smooth": 0b, - "Duration": 1 + "Duration": 15 }, { "ColorMarker": 16777215, "Comment": "", "Speed": 2.0f, "FrameParts": [ - { - "Pivot2": -5.0f, - "Part": "RIGHT_ARM", - "Rotation1": 0.0f, - "Rotation0": -90.0f, - "Pivot0": 0.0f, - "Pivot1": 2.0f, - "Rotation2": 90.0f - }, - { - "Pivot2": 2.0f, - "Part": "LEFT_LEG", - "Rotation1": -31.0f, - "Rotation0": 31.0f, - "Pivot0": 1.0f, - "Pivot1": 0.0f, - "Rotation2": -18.0f - }, { "Pivot2": 0.0f, "Part": "HEAD", @@ -1231,15 +142,6 @@ "Pivot1": 1.0f, "Rotation2": 0.0f }, - { - "Pivot2": -2.0f, - "Part": "RIGHT_LEG", - "Rotation1": 6.0f, - "Rotation0": 12.0f, - "Pivot0": -1.0f, - "Pivot1": 0.0f, - "Rotation2": 0.0f - }, { "Pivot2": 0.0f, "Part": "BODY", @@ -1257,6 +159,33 @@ "Pivot0": -2.0f, "Pivot1": 1.0f, "Rotation2": -6.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f } ], "Smooth": 0b, @@ -1264,7 +193,7 @@ } ], "CurrentFrameTime": 0, - "CurrentFrame": 19, + "CurrentFrame": 1, "Smooth": 0b, "ID": 15, "WhileAttacking": 1b, diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json new file mode 100644 index 000000000..0a0ba828c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Active.json @@ -0,0 +1,203 @@ +{ + "Loop": 1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_ARM", + "Rotation1": 25.0f, + "Rotation0": -90.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 25.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 26, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbBarrage_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json new file mode 100644 index 000000000..dfe8f601b --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbBarrage_Windup.json @@ -0,0 +1,201 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Duration": 8 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 19 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 31.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "LEFT_ARM", + "Rotation1": -25.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -25.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 2, + "Smooth": 0b, + "ID": 25, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbBarrage_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json new file mode 100644 index 000000000..747f73860 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": 3, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 1.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -37.0f, + "Pivot0": -2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -37.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 24, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Zone_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json new file mode 100644 index 000000000..40a6abef7 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Zone_Windup.json @@ -0,0 +1,392 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -37.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -37.0f, + "Rotation0": -37.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.75f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 6 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -56.0f, + "Rotation0": -132.0f, + "Pivot0": -2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 56.0f, + "Rotation0": -132.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -12.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 82.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -10.0f, + "Part": "LEFT_ARM", + "Rotation1": 6.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -11.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 101.0f, + "Pivot0": 0.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -10.0f, + "Part": "RIGHT_ARM", + "Rotation1": -6.0f, + "Rotation0": 0.0f, + "Pivot0": 1.0f, + "Pivot1": 12.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 5, + "Smooth": 0b, + "ID": 23, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Zone_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index 2158e9ea4..eaaf48a45 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -164,6 +164,7 @@ gui.playerMap=Regen PlayerMap gui.unused=Unused gui.apply=Apply gui.cancel=Cancel +gui.continue=Continue gui.yes=Yes gui.lineColor1=Upper line color @@ -638,6 +639,7 @@ faction.friendly=Friendly faction.points=Points faction.ondeath=On death faction.hidden=Hidden +faction.hidden.hover=Hides this faction from the player's faction standings UI faction.default=Default faction.attackHostile=Attack hostile factions faction.defend=Defence faction members @@ -646,8 +648,9 @@ faction.options=Faction Options faction.increasepoints=Faction %s increased by %s points faction.decreasepoints=Faction %s decreased by %s points faction.attacked=Attacked by mobs +faction.attacked.hover=Whether vanilla mobs will target and attack NPCs in this faction faction.passive=Is Passive -faction.passive.hover=Passive factions will not queue any attacking tasks [Good for Performance] +faction.passive.hover=Passive faction NPCs cannot be damaged and will not queue any attacking tasks [Good for Performance] menu.inventory=Inventory menu.display=Display @@ -1546,6 +1549,7 @@ ability.anchor.rightHand=Right Hand ability.anchor.leftHand=Left Hand ability.anchor.aboveHead=Above Head ability.anchor.chest=Chest +ability.anchor.eye=Eye # Sweep Mode ability.sweep.swipe=Swipe @@ -1559,10 +1563,52 @@ ability.dash.defensive=Defensive ability.counter.flat=Flat ability.counter.percent=Percent -# Hazard Shape +# Zone Shape ability.shape.circle=Circle +ability.shape.square=Square ability.shape.ring=Ring ability.shape.cone=Cone +ability.zoneShape=Shape + +# Zone Presets +ability.preset.custom=Custom +ability.preset.default=Default +ability.preset.toxic=Toxic +ability.preset.inferno=Inferno +ability.preset.arcane=Arcane +ability.preset.electric=Electric +ability.preset.frost=Frost +ability.preset.hidden=Hidden +ability.preset.venom=Venom +ability.preset.explosive=Explosive +ability.preset.cursed=Cursed +ability.preset.shock=Shock +ability.preset.snare=Snare + +# Accent Styles +ability.accentStyle.static=Static +ability.accentStyle.swaying=Swaying +ability.accentStyle.flickering=Flickering + +# Particle Motion Styles +ability.particleMotion.rising=Rising +ability.particleMotion.drifting=Drifting +ability.particleMotion.sparks=Sparks + +# Zone Settings +ability.section.zone=Zone Placement +ability.telegraphSize=Telegraph Size +ability.coneAngle=Cone Angle +ability.ignoreInvulnFrames=Ignore Invuln Frames +ability.visible=Visible + +# Visual Layer Section Headers +ability.section.ground=Ground Fill +ability.section.rings=Rings +ability.section.border=Border +ability.section.accents=Accents +ability.section.lightning=Lightning +ability.section.particles=Particles # Placement Mode ability.placement.atCaster=At Caster @@ -1604,11 +1650,8 @@ ability.cnpc.slam=Slam ability.cnpc.heavy_hit=Heavy Hit ability.cnpc.cutter=Cutter ability.cnpc.beam=Beam -ability.cnpc.beam_dual=Beam Dual ability.cnpc.projectile=Projectile ability.cnpc.orb=Orb -ability.cnpc.orb_dual=Orb Dual -ability.cnpc.orb_barrage=Orb Barrage ability.cnpc.charge=Charge ability.cnpc.dash=Dash ability.cnpc.teleport=Teleport @@ -1619,7 +1662,6 @@ ability.cnpc.heal=Heal ability.cnpc.hazard=Hazard ability.cnpc.trap=Trap ability.cnpc.disc=Disc -ability.cnpc.disc_dual=Disc Dual ability.cnpc.laser_shot=Laser Shot ability.cnpc.sweeper=Sweeper @@ -1631,11 +1673,12 @@ ability.cnpc.sweeper=Sweeper ability.weight=Weight ability.windUpTicks=Wind Up ability.cooldownTicks=Cooldown -ability.lockPosition=Lock Position -ability.lockType=Lock Type -ability.lockType.movement=Movement -ability.lockType.rotation=Rotation -ability.lockType.both=Both +ability.lockMovement=Lock Movement +ability.rotationMode=Rotation +ability.rotationPhase=Phase +ability.rotation.free=Free +ability.rotation.locked=Locked +ability.rotation.track=Track ability.interruptible=Interruptible ability.dazedTicks=Dazed Ticks ability.targetingMode=Targeting @@ -1661,6 +1704,7 @@ ability.section.timing=Timing ability.section.movement=Movement ability.section.sounds=Sounds ability.section.animations=Animations +ability.section.animation=Animation ability.section.telegraph=Telegraph ability.section.beam=Beam ability.section.sweep=Sweep @@ -1672,14 +1716,16 @@ ability.section.boomerang=Boomerang ability.section.explosive=Explosive ability.section.colors=Colors ability.section.effects=Effects -ability.section.dual=Dual -ability.section.beam1=Beam 1 -ability.section.beam2=Beam 2 -ability.section.disc1=Disc 1 -ability.section.disc2=Disc 2 -ability.section.orb1=Orb 1 -ability.section.orb2=Orb 2 -ability.section.barrage=Barrage +ability.section.burst=Burst +ability.section.visual=Visual +ability.section.projectile1=Projectile 1 +ability.section.projectile2=Projectile 2 +ability.section.projectile3=Projectile 3 +ability.section.projectile4=Projectile 4 +ability.section.projectile5=Projectile 5 +ability.section.projectile6=Projectile 6 +ability.section.projectile7=Projectile 7 +ability.section.projectile8=Projectile 8 ability.section.counter=Counter ability.section.area=Area ability.section.damage=Damage @@ -1708,6 +1754,20 @@ gui.animation=Animation gui.duration=Duration gui.amp=Amp gui.speed=Speed +gui.size=Size +gui.alpha=Alpha +gui.count=Count +gui.style=Style +gui.scale=Scale +gui.motion=Motion +gui.glow=Glow +gui.texture=Texture +gui.dps=DPS +gui.interval=Interval +gui.cooldown=Cooldown +gui.max=Max +gui.preset=Preset +gui.applyPreset=Apply Preset # Common Type Settings ability.radius=Radius @@ -1720,9 +1780,14 @@ ability.stunTicks=Stun Ticks ability.hitWidth=Hit Width ability.hitLength=Hit Length ability.effects=Effects +ability.effect.burn=Burn ability.mode=Mode ability.duration=Duration ability.anchorPoint=Anchor Point +ability.anchor.offsetX=Offset X +ability.anchor.offsetY=Offset Y +ability.anchor.offsetZ=Offset Z +ability.vertical=Vertical ability.rotationSpeed=Rotation Speed # Slam @@ -1786,7 +1851,6 @@ ability.healAllies=Heal Allies # Hazard ability.shape=Shape ability.placement=Placement -ability.damagePerSecond=Damage/Sec ability.damageInterval=Damage Interval ability.slownessLevel=Slowness Level ability.debuffDuration=Debuff Duration @@ -1795,8 +1859,6 @@ ability.affectsCaster=Affects Caster # Trap ability.armTime=Arm Time -ability.maxTriggers=Max Triggers -ability.triggerCooldown=Trigger Cooldown # Sweeper ability.sweepSpeed=Sweep Speed @@ -1819,16 +1881,27 @@ ability.outerEnabled=Outer Glow ability.outerWidth=Outer Width ability.outerAlpha=Outer Alpha ability.lightning=Lightning -ability.lightningDensity=Density ability.lightningRadius=Radius -# Dual Energy Projectile Settings -ability.dualFire=Dual Fire +# Projectile Count / Settings +ability.projectileCount=Count ability.dualFireDelay=Fire Delay +ability.fireDelay=Fire Delay +ability.colorOverride=Color Override + +# Burst System +ability.burstEnabled=Burst +ability.burstAmount=Amount +ability.burstDelay=Delay +ability.burstReplayAnimations=Replay Animations +ability.burstOverlap=Overlap +ability.hover.burstOverlap=When enabled, projectiles from previous bursts keep flying while new ones fire +ability.hover.burstReplay=Replay windup and active animations for each burst iteration # Ability Save/Load ability.save.confirm=Save ability preset ability.save.overwrite=Overwrite existing preset +ability.duplicate.name=A preset with this name already exists ability.load.select=Select ability to load: ability.load.mode=How should this ability be loaded? ability.clone=Clone @@ -1841,6 +1914,13 @@ ability.edit.mode=How should this ability be edited? ability.cloneModify=Clone & Edit ability.modifyParent=Edit Parent +# Ability Variant Selection +ability.selectVariant=Select Variant +ability.variant.base=Base +ability.variant.single=Single +ability.variant.dual=Dual +ability.variant.barrage=Barrage + # Ability Type Selection ability.selectType=Select Ability Type: @@ -1862,8 +1942,9 @@ ability.noTypeSettings=No type-specific settings # ═══════════════════════════════════════════════════════════════ ability.hover.weight=Higher weight = more likely to be chosen when multiple abilities available -ability.hover.lockPosition=Prevents NPC from moving or rotating while ability is charging or active -ability.hover.lockType=What to lock: Movement (pathfinding), Rotation (facing direction), or Both +ability.hover.lockMovement=Prevents NPC pathfinding during the selected phases (Windup, Active, or Both) +ability.hover.rotationMode=Free: normal AI rotation. Locked: freeze facing direction. Track: force face target for precise aiming. +ability.hover.rotationPhase=When the rotation mode applies (Windup, Active, or Both) ability.hover.interruptible=If enabled, ability can be interrupted by taking damage ability.hover.dazed=Stun duration in ticks if ability is interrupted (20 ticks = 1 second) ability.hover.windup=Charge-up time before ability activates (20 ticks = 1 second) @@ -1884,6 +1965,7 @@ ability.hover.piercing=Hits multiple targets instead of stopping on first hit ability.hover.lightning=Add electrical effect to visuals ability.hover.outerGlow=Enable outer glow layer around projectile ability.hover.anchorPoint=Where on the NPC the ability spawns from +ability.hover.vertical=Disc flies standing up with thin edge facing target (like a saw blade) ability.hover.dualCharge=Whether or not should create two anchor points ability.hover.damage=Base damage dealt to targets ability.hover.speed=Movement speed of projectile @@ -1903,7 +1985,6 @@ ability.hover.placement=Where the ability effect is placed (Caster, Target, etc. ability.hover.lockTarget=Sweeper beam tracks the target's position ability.hover.canCounter=Enable counterattack when blocking damage ability.hover.counterType=Flat = fixed damage, Percent = % of blocked damage -ability.hover.shape=Shape of the hazard zone (Circle, Ring, Cone) ability.hover.affectsCaster=Hazard can damage the NPC that created it ability.hover.sweepMode=Swipe = single arc attack, Spin = continuous rotation @@ -1933,6 +2014,8 @@ condition.hover.threshold=Health percentage threshold (1-99%) effect.hover.type=Potion effect type to apply to targets effect.hover.duration=Effect duration in ticks (20 ticks = 1 second) effect.hover.amplifier=Effect strength level (higher = stronger) +effect.manual=Manual +effect.potionid=Potion ID # ========================================= # Auction House